我有一个包含 12 种不同颜色的 RGB 图像,但我事先不知道颜色(像素值)。我想转换 0 到 11 之间的所有像素值,每个像素值象征原始 RGB 图像的唯一颜色。
例如所有 [230,100,140] 转换为 [0,0,0] ,所有 [130,90,100] 转换为 [0,0,1] 等等...所有 [210,80,50] 转换为 [0,0, 11]。
快速而肮脏的应用程序。还有很多可以改进的地方,特别是逐个像素地浏览整个图像既不是很numpy,也不是很opencv,但我太懒了,记不清如何设置阈值和替换RGB像素。
import cv2
import numpy as np
#finding unique rows
#comes from this answer : http://stackoverflow.com/questions/8560440/removing-duplicate-columns-and-rows-from-a-numpy-2d-array
def unique_rows(a):
a = np.ascontiguousarray(a)
unique_a = np.unique(a.view([('', a.dtype)]*a.shape[1]))
return unique_a.view(a.dtype).reshape((unique_a.shape[0], a.shape[1]))
img=cv2.imread(your_image)
#listing all pixels
pixels=[]
for p in img:
for k in p:
pixels.append(k)
#finding all different colors
colors=unique_rows(pixels)
#comparing each color to every pixel
res=np.zeros(img.shape)
cpt=0
for color in colors:
for i in range(img.shape[0]):
for j in range(img.shape[1]):
if (img[i,j,:]==color).all(): #if pixel is this color
res[i,j,:]=[0,0,cpt] #set the pixel to [0,0,counter]
cpt+=1
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)