Numpy entered the room.
from typing import Callable, FrozenSet, List, Set
+import numpy as np
+
from .position import Point2
@@ -8,7 +10,9 @@ class PixelMap:
self._proto = proto
assert self.bits_per_pixel % 8 == 0, "Unsupported pixel density"
assert self.width * self.height * self.bits_per_pixel / 8 == len(self._proto.data)
- self.data = bytearray(self._proto.data)
+ self.data_numpy = np.array(np.frombuffer(proto.data, dtype=np.uint8)).reshape(proto.size.y, proto.size.x)[
+ ::-1, :
+ ]
@property
def width(self):
@@ -27,27 +31,16 @@ class PixelMap:
return self._proto.bits_per_pixel // 8
def __getitem__(self, pos):
- x, y = pos
-
- assert 0 <= x <= self.width, f"x is {x}, self.width is {self.width}"
- assert 0 <= y <= self.height, f"y is {y}, self.height is {self.height}"
-
- index = -self.width * y + x
- # print(f"INDEX IS {index} FOR {pos}")
- start = index * self.bytes_per_pixel
- data = self.data[start : start + self.bytes_per_pixel]
- return int.from_bytes(data, byteorder="little", signed=False)
-
- def __setitem__(self, pos, val):
- """ Example usage: self._game_info.pathing_grid[Point2((20, 20))] = [255] """
- x, y = pos
-
- assert 0 <= x <= self.width, f"x is {x}, self.width is {self.width}"
- assert 0 <= y <= self.height, f"y is {y}, self.height is {self.height}"
-
- index = -self.width * y + x
- start = index * self.bytes_per_pixel
- self.data[start : start + self.bytes_per_pixel] = val
+ assert 0 <= pos[0] < self.width, f"x is {pos[0]}, self.width is {self.width}"
+ assert 0 <= pos[1] < self.height, f"y is {pos[1]}, self.height is {self.height}"
+ return int(self.data_numpy[pos[1] - 1, pos[0]])
+
+ def __setitem__(self, pos, value):
+ assert 0 <= pos[0] < self.width, f"x is {pos[0]}, self.width is {self.width}"
+ assert 0 <= pos[1] < self.height, f"y is {pos[1]}, self.height is {self.height}"
+ assert 0 <= value < 256, f"value is {value}, it should be between 0 and 255"
+ assert isinstance(value, int), f"value is of type {type(value)}, it should be an integer"
+ self.data_numpy[pos[1] - 1, pos[0]] = value
def is_set(self, p):
return self[p] != 0
