How to draw grayscale and color histograms with Python matplotlib
1. Introduction to Matplotlib.Pyplot 1. Matplotlib
Matplotlib is the drawing library of Python, which allows users to easily graphize data and provide a variety of output formats.
Matplotlib can be used to draw a variety of static, dynamic, interactive charts.
Matplotlib is a very powerful Python drawing tool, we can use this tool to show a lot of data more intuitively in the form of charts.
Matplotlib can draw lines, scatters, contours, bars, bar charts, 3D graphics, and even graphic animations.
2 、 Pyplot
Pyplot is a sublibrary of Matplotlib and provides a drawing API similar to MATLAB.
Pyplot is a commonly used drawing module, which is very convenient for users to draw 2D charts.
Pyplot contains a series of drawing functions, each of which will make some changes to the current image, such as tagging the image, generating a new image, generating a new drawing area in the image, and so on.
When using it, we can use import to import the pyplot library and set an alias plt:
Import matplotlib.pyplot as plt
And then we can use it to draw graphics.
Second, gray histogram 1, main functions
Two functions are mainly used.
(1) calcHist ()
(2) hist ()
I will not introduce the specific usage too much. I can refer to the documentation by myself, or look for the explanations of the great gods on the Internet.
2. Implementation code import cv2 as cvimport numpy as npimport matplotlib.pyplot as pltimg = cv.imread ('Photos/1.bmp') cv.imshow (' Img', img) gray_img = cv.cvtColor (img, cv.COLOR_BGR2GRAY) cv.imshow ('GrayImg', gray_img) # Gray Histogramgray_hist = cv.calcHist ([gray_img], [0], None, [0256], False) # cv.calcHist (images, channels, mask, histSize, ranges) Accumulate) plt.figure (1) plt.title ('Gray Histogram Contour') plt.xlabel (' gray level') plt.ylabel ('number of pixels') plt.plot (gray_hist) plt.xlim ([0256]) plt.figure (2) plt.title (' Gray Histogram') plt.xlabel ('gray level') plt.ylabel (' number of pixels') plt.hist (gray_img.ravel (), plt.show () cv.waitKey (0) 3, effect example
3. Color histogram
Similar to the principle of grayscale histogram, it requires a simple traversal of three colors to output graphics in a loop.
1. Implementation code import cv2 as cvimport matplotlib.pyplot as pltimport numpy as npimg = cv.imread ('Photos/1.bmp') cv.imshow (' Img', img) plt.figure () plt.title ('Color Histogram') plt.xlabel (' level') plt.ylabel ('number of pixels') colors = (' baked, 'grubbed,' r') for I in enumerate (colors): hist = cv.calcHist ([img], [I], None, [256]) [0256]) plt.plot (hist, color=item) plt.xlim ([0256]) plt.show () cv.waitKey (0) 2, effect example
From this picture, we can directly see the frequency of different thresholds of the three colors.