I'm trying to obtain a RGB histogram of a picture thanks to OpenCV calcHist function for each of RGB channels. For the moment, I've succeeded to obtain a histogram showing how many pixels are in my image for each value of hue (on each of the three color channels) from 0 to 256. But what I would like to obtain is the number of pixels in numerous ranges of color value. For example :
How many pixels on my image from 0 to 50 in Red channel, then from 51 to 100, and so on ? Until 256, and in green and blue channels too.
I've read several documentation and topics about OpenCV and calcHist function, but I don't understand how do ranges and Bins work in Python.
I've especially read this : https://docs.opencv.org/2.4/modules/imgproc/doc/histograms.html?highlight=calchist#calchist
And this : OpenCV - Confusion using calcHist
(on this former source, they pass from RGB to HSV, which I don't need to)
Here is the code I used to obtain number of pixels for each hue value from 0 to 256 on each on the RGB channels.
import cv2
import matplotlib.pyplot as plt
name = "imagePath"
img = cv2.imread(name)
color = ('b','g','r')
for i, col in enumerate(color):
histr = cv2.calcHist([img],[i],None,[256],[0,256])
plt.plot(histr,color = col)
plt.xlim([0,256])
plt.show()
I obtain this histogram. It seems correct to me :
https://zupimages.net/up/19/34/c3qf.png
When I tried this code :
import cv2
import matplotlib.pyplot as plt
name = "imagePath"
img = cv2.imread(name)
color = ('b','g','r')
for i, col in enumerate(color):
histr = cv2.calcHist([img],[i],None,[256],[0,9])
plt.plot(histr,color = col)
plt.xlim([0,256])
plt.show()
I obtain this histogram :
https://zupimages.net/up/19/34/2tty.png
And that does not seem correct. Compared to the first histogram, I should have pikes of pixels on red curve between 150 and 200, and on green curve between 200 and 255.
What am I doing wrong ? What haven't I understood about ranges and bins in calcHist function ?
Thank you,
You ask a range on [0 9] thus the output values are on that range. And from the first histogram, it seems there is only blue here. You plot the 9 values on [0 256] but you still have nine values.
To have 10 ranges of 25 values each, you can try:
for i, col in enumerate(color):
histr = cv2.calcHist([img],[i],None,[10],[0,256])
plt.plot(histr,color = col)
plt.xlim([0,10])
plt.show()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.