Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

color percentage in image python opencv using histogram

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.

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

the image that I use

the image that I use

I have this output of the code enter image description here

like image 237
Majazen ـG Avatar asked Apr 02 '17 11:04

Majazen ـG


1 Answers

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)

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.

like image 97
mmensing Avatar answered Sep 22 '22 11:09

mmensing