将图像中的像素值(numpy)替换为dict中最接近的颜色

r7xajy2e  于 2023-03-08  发布在  其他
关注(0)|答案(1)|浏览(172)

我有一个图像与4通道的rgba,但我只想计算每个像素的rgb的差异,并取代它与最接近的颜色在一个口述。

  1. myMap = {
  2. 'a': ([255, 27, 255, 255]),
  3. 'b': ([255, 255, 27, 255]),
  4. 'c': ([255, 27, 27, 255]),
  5. }

把这个作为我的阵列,

  1. np.random.seed(seed=777)
  2. s = np.random.randint(low=0, high = 255, size=(3, 4, 4))
  3. print(s)

这就是我如何替换pix的,但是效率非常低,因为使用了3个循环。
其逻辑是循环遍历每个像素并计算与dict中每个值的距离,然后用dict中的值替换该特定像素的值。
运行该函数后,图像shd最多只包含3种颜色。
有没有更好的方法来实现我的愿望?

  1. for i in range(s.shape[0]):
  2. for j in range(s.shape[1]):
  3. _min = math.inf
  4. r, g, b, _ = s[i][j].tolist()
  5. for color in myMap.values():
  6. cr, cg, cb, ca = color
  7. color_diff = math.sqrt((r - cr)**2 + (g - cg)**2 + (b - cb)**2)
  8. if color_diff < _min:
  9. _min = color_diff
  10. s[i][j] = np.array([cr, cg, cb, ca])
  11. print(s)
qnakjoqk

qnakjoqk1#

你的问题有点模糊。你想提高性能还是可读性?
可通过使用附加维度和花哨的索引来提高可读性:

  1. import numpy as np
  2. # Use array instead of dictionary (np.array(list(myMap.values()))
  3. myMap = np.array([[255, 27, 255, 255],
  4. [255, 255, 27, 255],
  5. [255, 27, 27, 255]])
  6. np.random.seed(seed=777)
  7. s = np.random.randint(low=0, high = 255, size=(3,4,4))
  8. # Determine color differences (Use additional dimension)
  9. cdiffs = np.sum((s[:,:,None,:]-myMap)[...,:-1]**2,axis=-1)**0.5
  10. # Get the indices of the closest value
  11. idx = np.argmin(cdiffs,axis=-1)
  12. # Extract closest value to assemble array (Fancy Indexing)
  13. s = myMap[idx]
  14. print(s)
展开查看全部

相关问题