color quantization experiment
authorTomas Musil <tomik.musil@gmail.com>
Tue, 8 Jul 2014 11:54:57 +0000 (13:54 +0200)
committerTomas Musil <tomik.musil@gmail.com>
Tue, 8 Jul 2014 11:54:57 +0000 (13:54 +0200)
quantize.py [new file with mode: 0644]

diff --git a/quantize.py b/quantize.py
new file mode 100644 (file)
index 0000000..fc2232d
--- /dev/null
@@ -0,0 +1,39 @@
+from PIL import Image, ImageFilter
+import src.im_debug as imd
+
+rr , gg, bb = 0, 0, 0
+s = 0
+
+def color_quant(image):
+    # TODO comment
+    image_l = image.load()
+    new_image = Image.new('RGB', image.size)
+    new_image_l = new_image.load()
+
+    def nearest((r, g, b)):
+        global rr, gg, bb, s
+        o = ((r - 166) ** 2 + (g - 166) ** 2 + (b - 166) ** 2, (166, 166, 166))
+        bl = (r * r + g * g + b * b, (0, 0, 0))
+        r, g, b = r - 255, g - 255, b - 255
+        w = (r * r + g * g + b * b, (255, 255, 255))
+        if min([o, bl, w]) == o:
+            rr += r + 255
+            gg += g + 255
+            bb += b + 255
+            s += 1
+        return min([o, bl, w])[1]
+
+    new_image = Image.new('RGB', image.size)
+    new_image_l = new_image.load()
+    for x in xrange(image.size[0]):
+        for y in xrange(image.size[1]):
+            new_image_l[x, y] = nearest(image_l[x, y])
+
+    print rr / s, gg /s, bb /s
+
+    return new_image
+
+im = Image.open('image.jpg')
+imd.show(color_quant(im))
+
+