使用直方图的图像python opencv中的颜色百分比 [英] color percentage in image python opencv using histogram

查看:1260
本文介绍了使用直方图的图像python opencv中的颜色百分比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是python和图像处理的初学者.我想使用直方图功能从图像中找到棕色的百分比.

I am beginner in python and image processing. I want to find the percentage of brown color from an image using histogram function.

我做了直方图功能,但是我不知道如何找到图像中棕色的百分比.

I did the histogram function but I do not know how to find the percentage of the brown color in the image.

这是我的python代码

this is my python code

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()

我使用的图像

我有这段代码的输出

I have this output of the code

推荐答案

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).

This should work for you. However, note that it is highly dependent on your RGB value of brown as well as your desired tolerance (diff).

如果您对上述代码的细节还有其他疑问,请随时提问.

If you have further questions on the details of the above code, feel free to ask.

这篇关于使用直方图的图像python opencv中的颜色百分比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆