我是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()
我使用的图像
答案 0 :(得分:5)
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
)。
如果您对上述代码的详细信息有任何疑问,请随时提出。
答案 1 :(得分:0)
我需要相同的结果,因此我使用了您的代码并计算了百分比。
import cv2
import numpy as np
from matplotlib import pyplot as plt
import operator
img = cv2.imread('azul200.png', -1)
cv2.imshow('Imagem:',img)
color = ('b','g','r')
qtdBlue = 0
qtdGreen = 0
qtdRed = 0
totalPixels = 0
for channel,col in enumerate(color):
histr = cv2.calcHist([img],[channel],None,[256],[1,256])
plt.plot(histr,color = col)
plt.xlim([0,256])
totalPixels+=sum(histr)
print histr
if channel==0:
qtdBlue = sum(histr)
elif channel==1:
qtdGreen = sum(histr)
elif channel==2:
qtdRed = sum(histr)
qtdBlue = (qtdBlue/totalPixels)*100
qtdGreen = (qtdGreen/totalPixels)*100
qtdRed = (qtdRed/totalPixels)*100
qtdBlue = filter(operator.isNumberType, qtdBlue)
qtdGreen = filter(operator.isNumberType, qtdGreen)
qtdRed = filter(operator.isNumberType, qtdRed)
plt.title("Red: "+str(qtdRed)+"%; Green: "+str(qtdGreen)+"%; Blue: "+str(qtdBlue)+"%")
plt.show()
我希望它有所帮助,对我有用。