您好我正在尝试计算每个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()
最佳答案
如果我对您的理解正确,则希望提取每种颜色对图像的贡献。这就是使用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
关于python - python直方图opencv计算每种颜色,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48370095/