我希望我的图像只有10种特定的颜色,在颜色列表中指定。 因此,我循环遍历每个像素,如果该像素的颜色不包括在颜色列表中,我将指定相邻区域的颜色。但是因为图像是2k乘2k像素。这个循环大约需要30分钟。 我确信我这样做的方式不是最优的。如何优化我的工作方式
atlas_img_marked, atlas_img_cleaned = clean_img_pixels(atlas_img, color_list)
def clean_img_pixels(atlas_img, color_list):
dd = 3
for ii in range(atlas_img.shape[0]-1):
for jj in range(atlas_img.shape[1]-1):
pixelcolor = (atlas_img[ii,jj,0],atlas_img[ii,jj,1],atlas_img[ii,jj,2])
if pixelcolor not in color_list:
pixel2color = (atlas_img[ii-dd,jj,0],atlas_img[ii-dd,jj,1],atlas_img[ii-dd,jj,2])
if (pixel2color == (0,0,0)) | (pixel2color not in color_list):
pixel2color = (atlas_img[ii+dd,jj,0],atlas_img[ii+dd,jj,1],atlas_img[ii+dd,jj,2])
if (pixel2color == (0,0,0)) | (pixel2color not in color_list):
pixel2color = (atlas_img[ii+5,jj,0],atlas_img[ii+5,jj,1],atlas_img[ii+5,jj,2])
atlas_img_cleaned[ii,jj] = pixel2color
return atlas_img_cleaned
更准确地说,以下是耗时最长的部分:
out_colors = []
for ii in range(atlas_img.shape[0]-1):
for jj in range(atlas_img.shape[1]-1):
pixelcolor = (atlas_img[ii,jj,0],atlas_img[ii,jj,1],atlas_img[ii,jj,2])
if pixelcolor not in color_list:
out_colors.append((ii,jj))
需要177秒
试着这样做:
out_colors = [(ii,jj) for (ii,jj) in itertools.product(range(atlas_img.shape[0]), range(atlas_img.shape[1])) if (atlas_img[ii,jj,0],atlas_img[ii,jj,1],atlas_img[ii,jj,2]) not in color_list]
但没什么区别。需要173秒
这是颜色列表:
color_list = [(52, 26, 75), (9, 165, 216), (245, 34, 208), (146, 185, 85), (251, 6, 217), (223, 144, 239), (190, 224, 121), (252, 26, 157), (150, 130, 142), (51, 129, 172), (97, 85, 204), (1, 108, 233), (138, 201, 180), (210, 63, 175), (26, 138, 43), (216, 141, 61), (38, 89, 118), (0, 0, 0)]
如果您完全抛弃
numpy
,直接使用枕头数组操作,并使用元组集而不是列表,则速度要快得多(对于我来说,这在示例图片上5秒钟内执行):我仍然建议你做一些额外的边界检查,因为你的图像是这样布置的
以下是我根据问题陈述,托马斯·荣布卢特的答案和答案here得出的结论
该算法执行单像素查找并生成仅限于颜色列表中颜色的图像
相关问题 更多 >
编程相关推荐