kai.pet...@gmail.com wrote:

> I just wrote this bit (coming from Pascal) 

>     if (((xdim / 8) * ydim) + header) <> filesize:

Yeah, either Pascal or Barry Warsaw is your uncle ;)

https://www.python.org/dev/peps/pep-0401/

> and am wondering how seasoned
> Python programmers would have done the same? Anything terribly non-python?

> def RenderByte(draw, byte, x, y):

Please read PEP 8 for naming conventions etc.

The function at the core of your code

> def RenderByte(draw, byte, x, y):
> 
>     blist = list(bin(byte).lstrip('0b')) # turn byte into list with 8
>     elements,
>     c = 0                                # each representing one bit
>     for bit in blist:
>         if bit:
>             draw.point((x + c, y), fcolor)
>             
>         c += 1
>     return

can be fixed/micro-optimised, and if I were to do that I'd precreate a 
lookup table that maps every byte (i. e. value in the range 0...255) to a 
sequence of offsets 

lookup = [
    (),      # for b"\x00" the inner loop is empty
    (0),
    (1),
    (0, 1),
    ...
    (0, 1, 2, 3, 4, 5, 6, 7), # for b"\xFF" the inner loop comprises 
                              # all 8 bits
]
or to a 8x1 image, but my idea of a "seasoned Python programmer" will try to 
keep the big picture in mind -- and that is that handling individual 
bits/pixels in Python is inefficient. Therefore many libraries tend to offer 
an alternative that is both easier to use and faster.

In this case that's

   img = Image.frombytes("1", (width, height), data)
 
and with the extra comfort of reading the size from the EPD file

from PIL import Image
import struct

EPDFILE = "tmp.epd"
PNGFILE = "tmp.png"

class EPDError(Exception):
    pass

with open(EPDFILE, "rb") as f:
    header = f.read(16)
    width, height, colordepth = struct.unpack("<HHb", header[1:6])
    if colordepth != 1:
        raise EPDError("Unsupported color depth {}".format(colordepth))
    data = f.read()
    datasize = width // 8 * height
    if len(data) != datasize:
        raise EPDError(
            "Inconsistent pixel data size. "
            "Expected {} but got {} bytes".format(
                datasize, len(data)))
    img = Image.frombytes("1", (width, height), data)
    img.save(PNGFILE)


I'm assuming the header follows the format spec given in this PDF:

http://www.pervasivedisplays.com/_literature_112691/Developer_Guide_for_Demo_Kit

PS: I thought that Image.frombytes() was already pointed out to you, but I 
failed to find it in the archives. So there.

-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to