Linked Questions

Popular Questions

Python: Issues with reading image pixels from file

Asked by At

I understand that in Python there are multiple ways to get all of the pixels of an image, using external libraries like PIL or Image. Interested to try out my binary skills, I figured I'd go ahead and try to read the pixels in raw Python with the binary data from the file. This is the image I used as an example:

The image I used in my program.

What I gathered from other questions was that I needed to convert the bytes to a whole bunch of unsigned integers before processing. I used struct.unpack to do this. Here's my program so far:

import struct

with open('connect.jpg', 'rb') as fp:
    data =
    print(struct.unpack("I"*int(len(data)/4), data))

This gives me a whole bunch of crazy integers. I figured these were just RGB integers that I had to convert, so I did that. A couple of issues here:

  • The list of pixels was only 2019 long, while my image is 320x240.

  • The pixel colors were horrendously off. I would have figured the first few thousand pixels would have been close to rgb(0,0,0), but I was getting green, purple, yellow, red - everything.

For reference, here is the code I used to convert the unsigned integers into RGB tuples:

def rgb_int2tuple(rgbint):
    return (rgbint // 256 // 256 % 256, rgbint // 256 % 256, rgbint % 256)

I feel like I am taking the whole wrong approach here. Am I possible not reading the data into the right format, or is something messed up with my int-to-RGB function? Any help would be appreciated, thanks!

Related Questions