使用opencv和python的图像中所有颜色的列表

Kal*_*n M 0 python opencv numpy image

Python初学者在这里.我正在使用python 3.6和opencv,我正在尝试创建一个图像中存在的所有颜色的rgb值列表.我可以使用cv2.imread后跟image [px,px]读取一个像素的rgb值.结果是一个numpy数组.我想要的是图像中存在的独特颜色的rgb元组列表,我不知道该怎么做.任何帮助表示赞赏.TIA

iR0*_*Nic 5

看看numpy的numpy.unique()函数:

import numpy as np

test = np.array([[255,233,200], [23,66,122], [0,0,123], [233,200,255], [23,66,122]])
print(np.unique(test, axis=0, return_counts = True))

>>> (array([[  0,   0, 123],
       [ 23,  66, 122],
       [233, 200, 255],
       [255, 233, 200]]), array([1, 2, 1, 1]))
Run Code Online (Sandbox Code Playgroud)

您可以在2D numpy数组中收集RGB numpy数组,然后使用带axis=0参数的numpy.unique()函数来遍历其中的数组.可选参数return_counts=True还将为您提供出现的次数.

  • @KalyanM 这应该没有必要。我尚未验证它,但以下内容应该可以工作,因为 cv2.imread() 函数已经返回一个 numpy ndarray:`img = cv2.imread(path_to_img)` 以获得每像素 rbgs 的 3D ndarray。`all_rgb_codes = img.reshape(-1, img.shape[-1])` 将 3D 数组按一维扁平化为我们需要的 2D 数组。`unique_rgbs = np.unique(all_rgb_codes, axis=0)` 以根据我上面的回答获得独特的颜色。在生产中使用它之前,请测试和评估它。快乐编码:) (2认同)