Histograms - 1 : Find, Plot, Analyze !!!

摘自https://docs.opencv.org/4.2.0/d1/db7/tutorial_py_histogram_begins.html

Histogram gives you an overall idea about the intensity distribution of an image. By looking at the histogram of an image, you get intuition about contrast, brightness, intensity distribution etc of that image. 

 

Histogram Calculation in OpenCV

Now we use cv.calcHist() function to find the histogram. 

cv.calcHist(images, channels, mask, histSize, ranges[, hist[, accumulate]])

  1. images : it is the source image of type uint8 or float32. it should be given in square brackets, ie, "[img]".
  2. channels : it is also given in square brackets. It is the index of channel for which we calculate histogram. For example, if input is grayscale image, its value is [0]. For color image, you can pass [0], [1] or [2] to calculate histogram of blue, green or red channel respectively.
  3. mask : mask image. To find histogram of full image, it is given as "None". But if you want to find histogram of particular region of image, you have to create a mask image for that and give it as mask. 
  4. histSize : this represents our BIN count. Need to be given in square brackets. For full scale, we pass [256].
  5. ranges : this is our RANGE. Normally, it is [0,256].
img = cv.imread('home.jpg',0)
hist = cv.calcHist([img],[0],None,[256],[0,256])

hist is a 256x1 array, each value corresponds to number of pixels in that image with its corresponding pixel value.

Plotting Histograms

1. Using Matplotlib

Matplotlib comes with a histogram plotting function : matplotlib.pyplot.hist()

It directly finds the histogram and plot it. You need not use calcHist() to find the histogram. 

img = cv.imread('home.jpg',0)
plt.hist(img.ravel(),256,[0,256]); plt.show()

Or you can use normal plot of matplotlib, which would be good for BGR plot. For that, you need to find the histogram data first. 

img = cv.imread('home.jpg')
color = ('b','g','r')

for i,col in enumerate(color):
    histr = cv.calcHist([img],[i],None,[256],[0,256])
    plt.plot(histr,color = col)
    plt.xlim([0,256])

plt.show()

2. Using OpenCV

Well, here you adjust the values of histograms along with its bin values to look like x,y coordinates so that you can draw it using cv.line() or cv.polyline() function to generate same image as above. 

Application of Mask

What if you want to find histograms of some regions of an image? Just create a mask image with white color on the region you want to find histogram and black otherwise. Then pass this as the mask.

img = cv.imread('home.jpg',0)

# create a mask
mask = np.zeros(img.shape[:2], np.uint8)
mask[100:300, 100:400] = 255
masked_img = cv.bitwise_and(img,img,mask = mask)

hist_mask = cv.calcHist([img],[0],mask,[256],[0,256])

猜你喜欢

转载自blog.csdn.net/Airfrozen/article/details/104439272