【发布时间】:2015-03-31 06:19:03
【问题描述】:
我试图在图像中找到主要颜色,然后确定最主要的颜色。但是我在数据类型方面遇到了麻烦。 我的公式给出了最主要的颜色:
color=[10,10,10] # type=numpy.ndarray ,uint8
但是当我尝试转换它时它给出了断言错误:
color=cv2.cvtColor(color, cv2.COLOR_BGR2HSV) #gives assertion error
cv2.cvtColor 想要作为输入的是:
color_ideal=[[[ 10, 10, 10 ]]] #type=numpy.ndarray, uint8
为了获得它,我设法像这样操纵颜色:
color=np.uint8(np.atleast_3d(clr).astype(int).reshape(1,1,3))
这似乎可行,但知道我不能将多种颜色附加到 numpy 数组。不知何故,附加维度后,维度减少到 1。我的代码是:
color=np.uint8([[[]]])
for item in clt.cluster_centers_:
color=np.append(color,(np.uint8(np.atleast_3d(item).astype(int).reshape(1,1,3))))
#returns: color=[10,10,10] somehow its dimension is down to 1
我的问题是:
1-如何在不丢失维度的情况下正确附加颜色数据?
2-有没有更简单的方法来处理这个问题?我很惊讶操作自定义颜色像素有多么困难。
完整的代码在这里以防万一:
<!-- language: lang-py -->
import cv2
import numpy as np
from sklearn.cluster import KMeans
def find_kmean_colors(img,no_cluster=2):
clt = KMeans(no_cluster).fit(img)
return clt
def initialize(img='people_frontal.jpg'):
img=cv2.imread('people_frontal_close_body.jpg')
img=cv2.bilateralFilter(img,9,75,75)
return img
img=initialize()
img_hsv =cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
img_list= img.reshape((img.shape[0] * img_hsv.shape[1], 3))
clt=(find_kmean_colors(img_list,1))
color=np.uint8([[[]]])
for i in clt.cluster_centers_:
color=np.append(color,(np.uint8(np.atleast_3d(i).astype(int).reshape(1,1,3))))
#color=np.uint8(np.atleast_3d(clt.cluster_centers_).astype(int).reshape(1,1,3))
up=cv2.cvtColor(color,cv2.COLOR_BGR2HSV)
【问题讨论】:
-
重复
append很慢。初始化一个正确大小的空数组,并在正确的位置插入值。或者用所有新东西创建一个,然后concatenate它在正确的维度上。
标签: python opencv numpy multidimensional-array