我们如何能够直接在列表的列表上映射该函数?
#First I convert my image to a list
#Below list represents a true image size
list1=[[255, 114, 70],
[120, 89, 15],
[247, 190, 6],
[41, 38, 37],
[102, 102, 10],
[255,255,255]]*3583180
然后,我们定义要映射颜色的聚类以及执行此操作的函数(该函数来自PIL库)。
#Define colors of interest
#Colors of interest
RED=[255, 114, 70]
DARK_YELLOW=[120, 89, 15]
LIGHT_YELLOW=[247, 190, 6]
BLACK=[41, 38, 37]
GREY=[102, 102, 10]
WHITE=[255,255,255]
Colors=[RED, DARK_YELLOW, LIGHT_YELLOW, GREY, BLACK, WHITE]
#Function to find closes cluster by root and squareroot distance of RGB
def distance(c1, c2):
(r1,g1,b1) = c1
(r2,g2,b2) = c2
return math.sqrt((r1 - r2)**2 + (g1 - g2) ** 2 + (b1 - b2) **2)
现在需要做的是匹配每个颜色,并使用原始颜色列表中匹配的索引创建一个新列表:
Filt_lab=[]
#Match colors and make new list with indexed colors
for pixel in tqdm(list1):
closest_colors = sorted(Colors, key=lambda color: distance(color, pixel))
closest_color = closest_colors[0]
for num, clust in enumerate(Colors):
if list(clust) == list(closest_color):
Filt_lab.append(num)
运行单个图像大约需要5分钟,这很好,但很可能有一种方法可以大大缩短这个时间?
36% | ███▌ | 7691707/21499080 [01:50 <03:18,69721.86it/s]
Filt_lab的预期结果:
[0, 1, 2, 4, 3, 5]*3583180
[r1, g1, b1, r2, g2, b2, ...]
或者3个数组[r1, r2, ...], [g1, g2, ...], [b1, b2, ...]
或者一个多路复用器(利用 int 的前几位表示 r,接下来的 8 位表示 g...)。然后,不要在 for 循环中逐像素计算差异,因为这样会使用高度非连续的内存区域。对于每个类别,计算红色数组、绿色数组和蓝色数组的差异。然后求和差异,然后分类。并且使用 numpy 来实现向量化运算。 - GPI