Search code examples
matlabimage-processinghistogramobject-detection

Matlab: histogram of object's color pixels based on the hue values


I'm new to DIP, but I need to reproduce the following histogram. enter image description here

When I use the simple code below, it cannot generate the same figure!

img1 = imread('013.png');  
figure(1), imshow(img1)
img_hsv = rgb2hsv(img1);
imhist(img_hsv(:,:,1))

Here is the original image

enter image description here

and the image of the yellow ball segmented.

enter image description here

Edit After Raviteja Narra's ANSWER:

But when I use a similar code in Matlab, I get the following figure

img1 = imread('img.png');  
img_hsv = rgb2hsv(img1);
hue_img = img_hsv(:,:,1)
array = hue_img(find(hue_img > 0.1))
hist(array, 20)

My hue values are in range 0.11-0.17, and it seems that the bins of my histogram are mirrored versions of Raviteja's plot! What's the reason for this strange plot?

enter image description here


Solution

  • The problem here is almost all the pixels in the image have hue value 0. So the histogram is dominated by that. So, the result just looks like it has a big spike at 0. To see the expected histogram, create a new array by removing the 0 values from the original hue_img. This will show a gaussian distribution. Here is the python code for this.

    img = cv2.imread(r"\img.png") 
    rgb_img = img 
    hsv_img = rgb2hsv(rgb_img) 
    hue_img = hsv_img[:, :, 0] 
    array = hue_img[np.where(hue_img > 0.1)] 
    plt.hist(array,bins=100)
    

    The image would look like this. enter image description here