I'm using the rasterio.features.shapes method to generate GeoJSON information from a PNG file. This answer shows what I'm trying to do, except I need to analyze the RGB bands simultaneously otherwise the polygons won't be correct. I'm circumventing this by converting first the triplet of 3 int8 to a single 32bit integer using the bitshift operator, but I feel I'm missing the obvious solution to combine the 3 bands together in some way. I'm also using PIL and numpy to process the image.
import numpy as np
from PIL import Image
from rasterio.features import shapes
def find_polygons():
im = Image.open(f"myimage.png")
arr = np.array(im)
out = np.vectorize(rgb_to_int32, otypes=[np.int32])(*np.rollaxis(arr, 2, 0))
for i, (s, v) in enumerate(shapes(out)):
r, g, b = int32_to_rgb(v)
print(i)
def rgb_to_int32(r, g, b):
return (r << 16) + (g << 8) + b
def int32_to_rgb(n):
n = int(n)
return n >> 16 & 0xFF, n >> 8 & 0xFF, n & 0xFF
This produces the desired result, but I feel like I'm missing the obvious solution. Any tips in the right direction?
For reference, this is the image I'm trying to extract data from: