gpt4 book ai didi

python直方图opencv计算每种颜色

转载 作者:太空宇宙 更新时间:2023-11-03 22:21:46 24 4
gpt4 key购买 nike

你好,我正在尝试计算每个 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

enter image description here

enter image description here

enter image description here

关于python直方图opencv计算每种颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48370095/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com