Draw the image grayscale histogram - a summary of the method of visualizing the grayscale distribution of the image

        Today, when implementing image threshold segmentation, it is necessary to find a gray threshold that can distinguish the background from the object, because the processed image is relatively simple, and its histogram has a very obvious feature, that is, its histogram is in double Presented in the form of a peak and a valley, the threshold that distinguishes the object from the background is also the threshold corresponding to the valley. Using mathematical concepts to explain, the double peaks correspond to two maximum values, and the valley corresponds to the minimum value, that is, Find the minimum value between the two maximum values. Of course, you can also visualize the gray value distribution by counting the distribution of the gray value of the image, and then find the appropriate threshold, which is better than sorting to find the minimum value. The efficiency is much faster, here I will introduce three ways to visualize the gray distribution.

        Method 1 - use the hist() function in the matplotlib library

matplotlib.pyplot.hist(xbins=Nonerange=Nonedensity=Falseweights=Nonecumulative=Falsebottom=Nonehisttype='bar'align='mid'orientation='vertical'rwidth=Nonelog=Falsecolor=Nonelabel=Nonestacked=False*data=None**kwargs)

Generally only the first three parameters are defined:

x: input data

bins: If the bins input is an integer, it represents how many parts the abscissa is divided into in the output image

range: It defines the range of the abscissa, the input is a list that stores two numbers, the number on the left is the starting point of the abscissa, and the number on the right is the cut-off point of the abscissa

The final result of this function output is a continuous graph showing each gray value and its corresponding frequency 

        Method 2 - use the calcHist function in opencv

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

 image: The image whose gray value distribution needs to be counted, there is a bloody lesson, the image must be framed by []

channels: image channel, for a BGR image, [0], [1], [2] for B, G, R three channels respectively

mask: Generally, it is None by default

histSize: defines the abscissa range of the histogram

ranges: defines how many parts the abscissa is divided into

        Method 3——Using PLotly for visual drawing

The chart generated by Plotly is interactive, that is to say, when you point the mouse to a corresponding gray value, it will directly display the frequency of the gray value, but it takes a long time, because it needs to be calculated by the program What is the frequency corresponding to each gray value.

        Mainly used here:

        Bar function to store the horizontal and vertical coordinates of the input data

        Layout function, used to define the title of the function, horizontal and vertical coordinates

        offline.plot, the final plot

The general procedure of the realization process of the three methods is as follows:

import cv2
import matplotlib.pyplot as plt
from plotly import offline
from  plotly.graph_objs import Bar, Layout
img_source = cv2.imread('C:\\Users\\yu\\Desktop\\picture_csdn\\cells_segmentation.jpg', cv2.IMREAD_COLOR)
img_gray = cv2.cvtColor(img_source, cv2.COLOR_BGR2GRAY)
cv2.imshow('img_gray', img_gray)
#   方法二————利用opencv中的calcHist函数
img_hist = cv2.calcHist([img_gray], [0], None, [256], [0, 256])
plt.plot(img_hist, color='blue')
plt.show()
#   方法一————利用matplotlib库中的hist()函数
plt.hist(img_gray.ravel(), 256, [0, 256])#ravel函数功能是将多维数组降为一维数组
plt.show()
ret, img_segmentation = cv2.threshold(img_gray, 80, 255, cv2.THRESH_TRUNC)#    对图像进行阈值分割
cv2.imshow('img_segmentation', img_segmentation)#    图像分割结果
#    方法三————利用PLotly进行可视化绘图
a_input = list(img_gray.ravel())
frequencies = []
for value in list(range(0, 256)):
    print(value)
    frequency = a_input.count(value)
    frequencies.append(frequency)
#   对结果可视化
x_values = list(range(0, 256))
data = [Bar(x=x_values, y=frequencies)]
x_axis_config = {'title': '灰度值'}
y_axis_config = {'title': '灰度值的频率'}
my_layout = Layout(title='一个图像的灰度直方图', xaxis=x_axis_config, yaxis=y_axis_config)
offline.plot({'data': data, 'layout': my_layout}, filename='gray_histogram.html')
cv2.waitKey(0)
cv2.destroyAllWindows()

   In the above program, there are two codes for thresholding the image, and readers can comment them out when using the program.

The image I count here is a cell image that converts a color image into a grayscale image:

 The results of the three gray level histogram distributions are as follows:

method one

Method Two

method three

Guess you like

Origin blog.csdn.net/kuwola/article/details/122546479