python直方图opencv计算每种颜色

时间:2018-01-21 18:12:45

标签: python opencv histogram

你好我试图计算每个R / G / B的像素并创建一些图片的直方图,直方图看起来不错,但我不能计算每种颜色的像素。它说每种颜色的数量相同,我怀疑是正确的。

这是我的代码,我是相当新的,我的想法已经用完了

import numpy as np
import cv2 as cv
from matplotlib import pyplot as plt
img = cv.imread('photo.jpg')
color = ('b','g','r')


qtdBlue = 0
qtdGreen = 0
qtdRed = 0
totalPixels = 0


for i,col in enumerate(color):
    histr = cv.calcHist([img],[i],None,[256],[0,256])
    plt.plot(histr,color = col)
    plt.xlim([0, 256])


    totalPixels+=sum(histr)
    if i==0:
        qtdBlue = sum(histr)
    elif i==1:
        qtdGreen = sum(histr)
    elif i==2:
        qtdRed = sum(histr)


print("Red Quantity")
print(qtdRed)

print("Blue Quantity")
print(qtdBlue)

print("Green Quantity")
print(qtdGreen)

plt.show()

2 个答案:

答案 0 :(得分:1)

如果我理解正确,您想要提取每种颜色对图像的贡献。以下是如何使用matplotlib。正如您在代码末尾看到的那样,每种颜色的形状(像素数)都相同。

import numpy as np
import matplotlib.pyplot as plt

# Load the image
img = plt.imread('C:\Documents\Roses.jpg')

# Extract each colour channel
red, green, blue = img[:,:,0], img[:,:,1], img[:,:,2]

# Total red+green+blue intensity
intensity = img.sum(axis=2)

# Function to calculate proportion of a certain channel
def colour_frac(color):
    return np.sum(color)/np.sum(intensity)

# Calculate the proportion of each colour
red_fraction = colour_frac(red)
green_fraction = colour_frac(green)
blue_fraction = colour_frac(blue)

sum_colour_fraction = red_fraction + green_fraction + blue_fraction
print('Red fraction: {}'.format(red_fraction))
print('\nGreen fraction: {}'.format(green_fraction))
print('\nBlue fraction: {}'.format(blue_fraction))
print('\nRGB sum: {}'.format(sum_colour_fraction))
print(red.shape == green.shape == blue.shape)

# Output
Red fraction: 0.3798302547713819

Green fraction: 0.33196874775790813

Blue fraction: 0.28820099747071

RGB sum: 1.0

red.shape == green.shape == blue.shape
Out[68]: True

enter image description here

enter image description here

enter image description here

答案 1 :(得分:0)

这可能无法回答您的问题,但我会解释为什么不同渠道的sum of your histograms结果具有相同的价值。直方图全部是intensity分布,这意味着最后,等式和将是相同的。

让我们看一个更简化的例子:一张用红色像素填充的3x3图片。

红色通道bin 255的强度计数为9。在另外两个通道(b,g)中,强度也是9,但 bin 0 。正如您所看到的,计数在直方图比较中没有变化。

直方图值

b = [9, 0, 0, ..., 0]    #0 - 255
g = [9, 0, 0, ..., 0]    #0 - 255
r = [0, 0, 0, ..., 9]    #0 - 255

enter image description here

  

Anywho:你可能真的对图片的dominant colors感兴趣