I'm working with binary PBM format. When I read it, I have an array with integers, where integers are ordinals of bytes. Each integer in array is transformed to list of 0 and 1 integers as binary representation, then I inverse this list. Pixel grid starts from 0:0, so position of the first pixel is [0:0].
I need to get pixel color if x >= 8. If x < 8, everything works great. Code for getting pixel color.
def getpixel(self, x, y):
'''PNMReader.getpixel(x, y) -> int
Get pixel at coordinates [x:y] and return it as integer.'''
if not isinstance(x, int) or not isinstance(y, int):
raise(TypeError('both x and y must be integers'))
if x < -1 or y < -1:
raise(ValueError('both x and y are interpreted as in slice notation'))
if x > (self.width-1):
raise(ValueError('x cannot be equal or greater than width'))
if y > (self.height-1):
raise(ValueError('x cannot be equal or greater than height'))
width, height = self.width, self.height
x = (x, width-1)[x == -1]
y = [y, height-1][y == -1]
p = (y *height) +x
width, height = self.width, self.height
pixels = self._array_
q = (8, width)[width -8 < 0]
if x >= q:
while x % q:
y += 1
x -= 1
from pprint import pprint
color = bitarray(pixels[y])[::-1][:q][x]
print(color)
bitarray which you can see here is my defined function for getting bits for integer as list; self._array_ is a sequence of integers (which are just ordinals for bytes which were read from PBM).
I need to fix this function for getting pixel color if x >= 8. I can't understand how to calculate offset for x and y in such situations.
Only fast-working answers are accepted. I don't want joining all bits as 1-dimensional array, since it can be too slow if image is big (e.g. it can be 3000x5000 pixels).
I know that I could use some modules like imagemagick or freeimage, etc., but I can use only standart library (no additional modules). I need pure Python solution without bindings or non-default modules.