Commits

Sergey Astanin  committed 6e04c0f

support for lines wider than 1 px; now reusable as a library

  • Participants
  • Parent commits 2972ac1

Comments (0)

Files changed (1)

 
 from PIL import Image
 
+default_sensitivity = 10
+default_color = (255,0,0)
+
 def html_to_rgb(colorstring):
     """Convert #RRGGBB to an (R, G, B) tuple.
     Source: http://code.activestate.com/recipes/266466/"""
     else:
         sys.exit(1)
 
+def unplot_file(imgfile, angles_coords, angles_values, \
+                sensitivity=default_sensitivity, color=default_color):
+    ((x1,y1),(x2,y2)) = angles_values
+    ((x1p,y1p),(x2p,y2p)) = angles_coords
+    xscale, yscale = (x2-x1)/(x2p-x1p), (y2-y1)/(y2p-y1p)
+    pts = []
+    im = Image.open(file(imgfile))
+    w, h = im.size
+    for i in xrange(x1p,x2p+1):
+        js = xrange(y1p,y2p-1,-1)
+        pixels = imap(lambda j: (j, im.getpixel((i,j))), js)
+
+        def similar(px):
+            j, c = px
+            return color_diff(c,color)*100 < sensitivity
+
+        pixels = ifilter(similar, pixels)
+        js = map(itemgetter(0), pixels)
+
+        if js:
+            j = sorted(js)[len(js)/2]  # median ordinate
+            pts.append(((i-x1p)*xscale+x1, (j-y1p)*yscale+y1))
+    return pts
+
 if __name__ == '__main__':
     opts, args = getopt(sys.argv[1:], "hs:")
     opts = dict(opts)
     except ValueError:
         usage(sys.stderr, "Wrong number of arguments: %d" % len(args))
 
-    sensitivity = int(opts.get("-s",10))
+    sensitivity = int(opts.get("-s",default_sensitivity))
     color = html_to_rgb(color)
+
     x1, y1, x2, y2 = map(float, [x1, y1, x2, y2])
     x1p, y1p, x2p, y2p = map(int, [x1p, y1p, x2p, y2p])
-    xscale, yscale = (x2-x1)/(x2p-x1p), (y2-y1)/(y2p-y1p)
 
-    im = Image.open(file(imgfile))
-    w, h = im.size
-    for i in xrange(x1p,x2p+1):
-        js = xrange(y1p,y2p-1,-1)
-        pixels = imap(lambda j: (j, im.getpixel((i,j))), js)
-
-        def similar(px):
-            j, c = px
-            return color_diff(c,color)*100 < sensitivity
-
-        pixels = ifilter(similar, pixels)
-        pixels = sorted(pixels, key=lambda (j,c): color_diff(c,color))
-        if pixels:
-            j, c = pixels[0]
-            print (i-x1p)*xscale+x1, (j-y1p)*yscale+y1
+    pts = unplot(imgfile, ((x1p,y1p), (x2p,y2p)), ((x1,y1), (x2,y2)), sensitivity, color)
+    for x,y in pts:
+        print x,y