【发布时间】:2019-11-21 14:02:52
【问题描述】:
我有一个相对较大的 RGBA 图像(转换为 numpy),我需要替换所有未出现在列表中的颜色。我怎么能以 pythonic 快速的方式做到这一点?
使用简单的迭代我有一个解决这个问题的方法,但是由于图像非常大(2500 x 2500),这个过程非常慢。
# Keep only these colors in the image, otherwise replace with (0,255,0,255)
palette = [[0,0,0,255],[0, 255, 0,255], [255, 0, 0,255], [128, 128, 128,255], [0, 0, 255,255], [255, 0, 255,255], [0, 255, 255,255], [255, 255, 255,255], [128, 128, 0,255], [0, 128, 128,255], [128, 0, 128,255]]
# Current slow solution with a 2500 x 2500 x 4 array (mask)
for z in range(mask.shape[0]):
for y in range(mask.shape[1]):
if (mask[z,y,:].tolist() not in palette):
mask[z, y] = (0,255,0,255)
每张图像的预期操作时间:不到半分钟
当前时间:两分钟
【问题讨论】:
-
请注意,你不是在做递归,你是在做迭代。
-
已编辑,谢谢@Jmonsky
标签: python image list numpy colors