Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/opencv/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何通过直方图从蒙版图像中提取颜色特征?_Python_Opencv_Background Color_Feature Extraction_Feature Detection - Fatal编程技术网

Python 如何通过直方图从蒙版图像中提取颜色特征?

Python 如何通过直方图从蒙版图像中提取颜色特征?,python,opencv,background-color,feature-extraction,feature-detection,Python,Opencv,Background Color,Feature Extraction,Feature Detection,我从图像中提取了一个对象,所以现在我有了 我想通过直方图单独从网球中提取颜色特征。这是我到目前为止的代码,但从直方图的外观来看,黑色背景主导了任何其他颜色,这使得直方图无效: from PIL import Image from pylab import * # Import image and convert to gray image = Image.open("res_300.png") im = image.convert('L') im_array = array(im) # Cr

我从图像中提取了一个对象,所以现在我有了

我想通过直方图单独从网球中提取颜色特征。这是我到目前为止的代码,但从直方图的外观来看,黑色背景主导了任何其他颜色,这使得直方图无效:

from PIL import Image
from pylab import *

# Import image and convert to gray
image = Image.open("res_300.png")
im = image.convert('L')
im_array = array(im)

# Create a new figure
figure()
gray()

# Show contours with origin upper left corner
contour(im, origin='image')
axis('equal')
axis('off')

# Create histogram
figure()
hist(im_array.flatten(), 128)
show()
有没有一种方法可以在不考虑黑色背景的情况下,从网球BGR颜色特征中绘制直方图


我是python新手。谢谢。

您可以忽略/删除所有3个RGB通道中的低强度值(对应于黑色)。然后在所有3个通道中取平均值,以获得所需对象的相应RGB值。

要将颜色通道分割为
BGR
,我们可以使用
cv2.split()
,然后使用直方图提取颜色特征。要去除主要的黑色背景,我们可以将范围设置为
[1256]


还有
np.柱状图也可以这样做。与nathancy的回答类似,可以从
1
设置限制以忽略黑色背景:

image = cv2.imread('8fk43.png')

plt.figure(figsize=(10,6))

for i, c in zip(range(3), 'bgr'):
    hist,bins = np.histogram(image[:,:,i], bins=range(0,256))

    plt.plot(bins[1:-1], hist[1:], c=c)

plt.show()
输出:

注意:上述方法有些不正确。想想纯绿色的
(0255,0)
将在红色/蓝色通道被忽略。正确的方法是先遮住网球,然后将遮罩作为权重传递到
np.histogram

例如,在这种情况下,可以简单地将
掩码
视为所有通道均为非零:

mask = (image>0).sum(-1)
mask = np.array(mask>0, dtype=np.uint8)
这给了面具:

然后呢,

plt.figure(figsize=(10,6))

for i, c in zip(range(3), 'bgr'):
    hist,bins = np.histogram(image[:,:,i], bins=range(0,256), weights=mask)

    plt.plot(bins[:-1], hist, c=c)

plt.show()
根据球的实际大小给出更合理的柱状图:

plt.figure(figsize=(10,6))

for i, c in zip(range(3), 'bgr'):
    hist,bins = np.histogram(image[:,:,i], bins=range(0,256), weights=mask)

    plt.plot(bins[:-1], hist, c=c)

plt.show()