假设有600张带注释的语义分割掩膜图片,其中包含10种不同的颜色,每种颜色表示一个实体。 这些图像以形状为(600, 3, 72, 96)的numpy数组存在其中,其中n = 600,3 = RGB通道,72 =高度,96 =宽度。
如何将numpy数组中的每个RGB像素映射到颜色索引值?例如,颜色列表可能是[(128, 128, 0), (240, 128, 0), ... n],numpy数组中所有(240, 128, 0)像素都将转换为唯一映射中的索引值(=1)。
如何高效且减少代码量地完成此操作?以下是我想出的一种解决方案,但速度相当慢。
如何将numpy数组中的每个RGB像素映射到颜色索引值?例如,颜色列表可能是[(128, 128, 0), (240, 128, 0), ... n],numpy数组中所有(240, 128, 0)像素都将转换为唯一映射中的索引值(=1)。
如何高效且减少代码量地完成此操作?以下是我想出的一种解决方案,但速度相当慢。
# Input imgs.shape = (N, 3, H, W), where (N = count, W = width, H = height)
def unique_map_pixels(imgs):
original_shape = imgs.shape
# imgs.shape = (N, H, W, 3)
imgs = imgs.transpose(0, 2, 3, 1)
# tupleview.shape = (N, H, W, 1); contains tuples [(R, G, B), (R, G, B)]
tupleview = imgs.reshape(-1, 3).view(imgs.dtype.descr * imgs.shape[3])
# get unique pixel values in images, [(R, G, B), ...]
uniques = list(np.unique(tupleview))
# map uniques into hashed list ({"RXBXG": 0, "RXBXG": 1}, ...)
uniqmap = {}
idx = 0
for x in uniques:
uniqmap["%sX%sX%s" % (x[0], x[1], x[2])] = idx
idx = idx + 1
if idx >= np.iinfo(np.uint16).max:
raise Exception("Can handle only %s distinct colors" % np.iinfo(np.uint16).max)
# imgs1d.shape = (N), contains RGB tuples
imgs1d = tupleview.reshape(np.prod(tupleview.shape))
# imgsmapped.shape = (N), contains uniques-index values
imgsmapped = np.empty((len(imgs1d))).astype(np.uint16)
# map each pixel into unique-pixel-ID
idx = 0
for x in imgs1d:
str = ("%sX%sX%s" % (x[0], x[1] ,x[2]))
imgsmapped[idx] = uniqmap[str]
idx = idx + 1
imgsmapped.shape = (original_shape[0], original_shape[2], original_shape[3]) # (N, H, W)
return (imgsmapped, uniques)
测试它:
import numpy as np
n = 30
pixelvalues = (np.random.rand(10)*255).astype(np.uint8)
images = np.random.choice(pixelvalues, (n, 3, 72, 96))
(mapped, pixelmap) = unique_map_pixels(images)
assert len(pixelmap) == mapped.max()+1
assert mapped.shape == (len(images), images.shape[2], images.shape[3])
assert pixelmap[mapped[int(n*0.5)][60][81]][0] == images[int(n*0.5)][0][60][81]
print("Done: %s" % list(mapped.shape))