gpt4 book ai didi

python - 使用直方图的图像python opencv中的颜色百分比

转载 作者:太空狗 更新时间:2023-10-30 02:39:53 26 4
gpt4 key购买 nike

我是 python 和图像处理的初学者。我想使用直方图函数找出图像中棕色的百分比。

我做了直方图函数,但我不知道如何找到图像中棕色的百分比。

这是我的python代码

import cv2
import numpy as np
from matplotlib import pyplot as plt

img = cv2.imread('C:\Users\MainUser\Desktop\histogram\dates.jpg', -1)
cv2.imshow('GoldenGate',img)

color = ('b','g','r')
for channel,col in enumerate(color):
histr = cv2.calcHist([img],[channel],None,[256],[0,256])
plt.plot(histr,color = col)
plt.xlim([0,256])
plt.title('Histogram for color scale picture')
plt.show()

while True:
k = cv2.waitKey(0) & 0xFF
if k == 27: break # ESC key to exit
cv2.destroyAllWindows()

我用的图片

the image that I use

我有这个代码输出 enter image description here

最佳答案

import numpy as np
import cv2

img = cv2.imread('J9MbW.jpg')

brown = [145, 80, 40] # RGB
diff = 20
boundaries = [([brown[2]-diff, brown[1]-diff, brown[0]-diff],
[brown[2]+diff, brown[1]+diff, brown[0]+diff])]
# in order BGR as opencv represents images as numpy arrays in reverse order

for (lower, upper) in boundaries:
lower = np.array(lower, dtype=np.uint8)
upper = np.array(upper, dtype=np.uint8)
mask = cv2.inRange(img, lower, upper)
output = cv2.bitwise_and(img, img, mask=mask)

ratio_brown = cv2.countNonZero(mask)/(img.size/3)
print('brown pixel percentage:', np.round(ratio_brown*100, 2))

cv2.imshow("images", np.hstack([img, output]))
cv2.waitKey(0)

这应该适合您。但是,请注意,它在很大程度上取决于您的棕色 RGB 值以及您所需的容差 (diff)。

如果您对上述代码的细节有进一步的疑问,请随时提问。

关于python - 使用直方图的图像python opencv中的颜色百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43167867/

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