我试图在图像中找到主要颜色,然后将最主要的颜色设置为阈值。但是我在数据类型方面遇到了麻烦。
我的公式给出了最主要的颜色:
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)
最佳答案
没有 cv2
代码,我在这里猜测形状。但看起来像 img
是 (n,m,3)
大批。 img_list
是 (m1,3)
, 和 clt
作为 m1
的列表项目和 clt.cluster_centers_
形状为 (3,)
的 m1 数组的列表.
为了测试起见,让我们制作一个列表列表(它也可以是一个数组列表):
ctrs=[[10,10,10], [3,5,3], [20,10,10], [0,0,0]]
color = np.array(ctrs,dtype=np.uint8) # (4,3) array
color = color.reshape(len(ctrs),1,3)
只需将其包裹在
np.array
,并 reshape 为 3d。array([[[10, 10, 10]],
[[ 3, 5, 3]],
[[20, 10, 10]],
[[ 0, 0, 0]]], dtype=uint8)
或者可以将其 reshape 为 (1,4,3) 或 (2,2,3)。
或更接近您正在尝试的内容:
np.concatenate([np.array(i,np.uint8).reshape(1,1,3) for i in ctrs])
你不想使用
atleast_3d
在这里,因为它将 (N,) 数组 reshape 为 (1,N,1) (请参阅其文档)。 np.concatenate
在第一个轴上连接,其中 np.array
添加第一个维度,然后加入。你可能会得到
append
工作,但它只是一步一步地连接,速度较慢。一般来说,如果您需要追加,请使用列表,然后在最后转换为数组。切片后有多种方法可以保留或恢复尺寸。如果
color
是 3d 并且您需要第 i 行也为 3d:color[[i]]
color[i].reshape(1,...)
color[i][np.newaxis,...]
像这样的 reshape 操作不会为处理增加大量时间,所以不要害怕使用它们。
关于python - 在 numpy 中附加 3d 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28258497/