How to draw grayscale histogram with opencv C++
This article mainly introduces "how to use opencv C++ to draw grayscale histogram" related knowledge, editor through the actual case to show you the operation process, the method of operation is simple and fast, practical, I hope this "how to use opencv C++ to draw grayscale histogram" article can help you solve the problem.
The calculation of the histogram is very simple. It is nothing more than traversing the pixels of the image and counting the number of each gray level. The calcHist function in opencv can simultaneously calculate the gray histogram of an image, multiple channels and different gray ranges.
Void calcHist (const Mat* images, int nimages, const int* channels, InputArray mask, OutputArray hist, int dims, const int* histSize, const float** ranges, bool uniform = true, bool accumulate = false)
Parameter interpretation
Image entered by images
Number of images input by nimages
The channel of channels statistical histogram
Optional operation mask for mask
Histogram array of hist output
Dims needs to count the number of histogram channels.
How many intervals is the histSize histogram divided into?
Ranges pixel value interval
Whether uniform is normalized or not
Whether accumulate calculates the number of pixel values in multiple images
Next, look directly at the code:
Mat img; img = imread ("cat 1.jpg", 0); int channels [] = {0}; int bins = 256; Mat hist; int hist_size [] = {bins}; float range [] = {0256}; const float*ranges [] = {range}; calcHist (& img, 1,0, Mat (), hist, 1, hist_size, ranges); double max_val MinMaxLoc (hist, 0, & max_val); / / defines the position of the minimum and maximum values in the matrix int scale = 2; int hist_height = 256; Mat hist_ing = Mat::zeros (hist_height, scale*bins, CV_8UC3); for (int I = 0; I < bins; iTunes +) {float bin_val = hist.at (I) / / Image grayscale frequency table int inten = cvRound (bin_val*hist_height / max_val); / / drawing height rectangle (hist_ing, Point (scale*i, hist_height-1), Point ((I + 1) * scale-1, hist_height-inten), CV_RGB (255,255,255);} imshow ("histogram", hist_ing); waitKey (0)
The effect is as follows:
This is the end of the introduction to "how to draw a grayscale histogram with opencv C++". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.