]> git.aero2k.de Git - sirius.git/commitdiff
Add image processing pipeline.
authorTom Hunger <tehunger@gmail.com>
Mon, 2 Feb 2015 13:21:49 +0000 (13:21 +0000)
committerTom Hunger <tehunger@gmail.com>
Mon, 2 Feb 2015 13:57:37 +0000 (13:57 +0000)
We're now using PIL to threshold the image before previewing it.

sirius/coding/encoders.py
sirius/coding/image_encoding.py
sirius/coding/test_image_coding.py
sirius/web/printer_print.py
sirius/web/templates/printer_print.html

index 70be6d68d0cd5e55c3bc0f1d2e065ff63a295473..351c47b0b16127bd92859b7398796984d581ef0b 100644 (file)
@@ -85,7 +85,7 @@ def encode_bridge_command(bridge_address, command, command_id, timestamp):
         })
 
     elif type(command) == messages.SetDeliveryAndPrint:
-        pixel_count, pixels = image_encoding.rle_image(command.pixels)
+        pixel_count, pixels = image_encoding.rle_from_bw(command.pixels)
         return make({
             'binary_payload': base64.b64encode(_encode_printer_message(
                 0x1, pixel_count, pixels, command_id)),
@@ -94,7 +94,7 @@ def encode_bridge_command(bridge_address, command, command_id, timestamp):
         })
 
     elif type(command) == messages.SetDelivery:
-        pixel_count, pixels = image_encoding.rle_image(command.pixels)
+        pixel_count, pixels = image_encoding.rle_from_bw(command.pixels)
         return make({
             'binary_payload': base64.b64encode(_encode_printer_message(
                 0x2, pixel_count, pixels, command_id)),
index b77efaeaaceb7aa0a5e01e2502834a5c4acc30c2..2459bd32dcc33a1906e5ec53eefcca0dcc147f83 100644 (file)
@@ -4,8 +4,8 @@ import struct
 import io
 import tempfile
 
-WHITE = 0
-BLACK = 1
+WHITE = '\xff'
+BLACK = '\x00'
 THRESHOLD = 127
 TRANSLATE = [(1536, 255), (1152, 254), (768, 253), (384, 252), (251, 251)]
 
@@ -56,18 +56,26 @@ def rle(lengths):
                     yield remainder
 
 
-def rle_image(data):
+def crop_384(im):
+    w, h = im.size
+    return im.crop((0, 0, 384, min(h, 10000)))
+
+
+def threshold(im):
+    thresholded = ''.join(pixel_to_bw(x) for x in im.convert('RGBA').getdata())
+    return Image.fromstring('L', im.size, thresholded)
+
+
+def rle_from_bw(bw_image):
     """
-    :param data: A python bytearray containing a PNG.
+    :param bw_image: A mode "1" PIL image.
     :returns: A 2-tuple of (number of pixels, RLE-encoded pixel data)
     """
-    im = Image.open(io.BytesIO(data))
-    im = im.convert('RGBA')
-    pixels = im.getdata()
+    pixels = list(bw_image.getdata())
 
-    # convert to B&W and group each run length into lists
-    # each list is (result of identity function, [actual pixels])
-    grouped = groupby(pixels, pixel_to_bw)
+    # Group each run length into lists each list is (result of
+    # identity function, [actual pixels])
+    grouped = groupby(pixels)
 
     # create list of tuples (WHITE|BLACK, run_length)
     groups = []
@@ -76,7 +84,7 @@ def rle_image(data):
 
     # the decoder assumes that the first run is white, so if the
     # first pixel is black, add a zero run of white
-    if groups[k][0] == BLACK:
+    if groups[0][0] == BLACK:
         groups.insert(0, (WHITE, 0))
 
     # encode using our custom encoding
@@ -112,8 +120,16 @@ def html_to_png(html):
             f.write(html)
             f.flush()
             driver.get('file://' + f.name)
-            data = driver.get_screenshot_as_png()
+            data = io.BytesIO(driver.get_screenshot_as_png())
 
         return data
     finally:
         driver.quit()
+
+
+def default_pipeline(html):
+    """Encode HTML into an RLE image."""
+    data = html_to_png(html)
+    image = Image.open(data)
+    image = crop_384(image)
+    return threshold(image)
index dc9b9d6c8a2029cb163e202119fee0e89dd3261f..502f425d74ab210f7314de97a45d7f0645174ccf 100644 (file)
@@ -1,25 +1,43 @@
 from PIL import Image
 import unittest
-import io
 
 from sirius.coding import image_encoding
 
 
 class ImageCase(unittest.TestCase):
 
-    def test_normal_text(self):
+    def _test_normal_text(self):
         data = image_encoding.html_to_png('')
-        image = Image.open(io.BytesIO(data))
+        image = Image.open(data)
         self.assertEquals(image.size[0], 384)
 
-    def test_normal_height(self):
+    def _test_normal_height(self):
         data = image_encoding.html_to_png(
             '<html><body style="margin: 0px; height: 100px;"></body></html>')
-        image = Image.open(io.BytesIO(data))
+        image = Image.open(data)
         self.assertEquals(image.size[1], 100)
 
-    def test_rle(self):
+    def _test_rle(self):
         data = image_encoding.html_to_png('')
-        image = Image.open(io.BytesIO(data))
+        image = Image.open(data)
         n_bytes, _ = image_encoding.rle_image(data)
         self.assertEquals(n_bytes, 3072)
+
+
+class PipeTestCase(unittest.TestCase):
+
+    def test_full(self):
+        data = image_encoding.html_to_png('')
+
+        image = Image.open(data)
+        image = image_encoding.crop_384(image)
+        image = image_encoding.threshold(image)
+
+        n_bytes, _ = image_encoding.rle_from_bw(image)
+        self.assertEquals(n_bytes, 3072)
+
+    def test_default_pipeline(self):
+        n_bytes, _ = image_encoding.rle_from_bw(
+            image_encoding.default_pipeline('')
+        )
+        self.assertEquals(n_bytes, 3072)
index 942c2ad0288ec17c8e31067316e0c48f5b62ac45..2238a226cfb00975ab732c45a3d1b3b71232cadb 100644 (file)
@@ -1,3 +1,4 @@
+import io
 import datetime
 import flask
 from flask.ext import login
@@ -57,7 +58,7 @@ def printer_print(user_id, username, printer_id):
     if form.validate_on_submit():
         # TODO: move image encoding into a pthread.
         # TODO: use templating to avoid injection attacks
-        pixels = image_encoding.html_to_png(
+        pixels = image_encoding.default_pipeline(
             '<html><body>{}</body></html>'.format(form.message.data))
         hardware_message = messages.SetDeliveryAndPrint(
             device_address=printer.device_address,
@@ -79,9 +80,11 @@ def printer_print(user_id, username, printer_id):
             stats.inc('printer.print.offline')
 
         # Store the same message in the database.
+        png = io.BytesIO()
+        pixels.save(png, "PNG")
         model_message = model_messages.Message(
             print_id=next_print_id,
-            pixels=bytearray(pixels),
+            pixels=bytearray(png.getvalue()),
             sender_id=login.current_user.id,
             target_printer=printer,
         )
@@ -112,9 +115,11 @@ def preview(user_id, username, printer_id):
     assert username == login.current_user.username
 
     message = flask.request.data
-    pixels = image_encoding.html_to_png(
+    pixels = image_encoding.default_pipeline(
         '<html><body>{}</body></html>'.format(message))
+    png = io.BytesIO()
+    pixels.save(png, "PNG")
 
     stats.inc('printer.preview')
 
-    return '<img style="width: 6cm;" src="data:image/png;base64,{}">'.format(base64.b64encode(pixels))
+    return '<img style="width: 6cm;" src="data:image/png;base64,{}">'.format(base64.b64encode(png.getvalue()))
index 7510df7c5eec67ad2b5031fc1f358560b6ebcbb6..c6e2f1e3fe3066d352e7fa28d9deb1e076f3c7d7 100644 (file)
@@ -35,7 +35,7 @@
 <button class="btn" type="button" id="preview">Preview</button>
 
 Preview:
-<div id="preview_pane" style="width: 6cm;border: 1px solid black;">
+<div id="preview_pane" style="width: 6cm;border: 1px solid black;overflow: hidden;">
 </div>
 {% endblock %}