In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
Most people do not understand the knowledge points of this article "how to deal with Python image thresholding", so the editor summarizes the following contents, detailed contents, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "how to deal with Python image thresholding" article.
one。 Image thresholding
Image thresholding (Binarization) aims to remove some pixels that are lower than or higher than a certain value in the image, so as to extract objects in the image and distinguish the background of the image from noise.
In the grayscaled image, each pixel has only one gray value, and its size indicates the degree of light and shade. Threshold processing can divide pixels in an image into two types of colors. Common thresholding algorithms are shown in formula (1):
When the gray Gray of a pixel is less than the threshold T, the pixel is set to 0, which means black; when the gray Gray is greater than or equal to the threshold T, the pixel value is 255, indicating white.
In the OpenCV library of Python, fixed thresholding function threshold () and adaptive thresholding function adaptiveThreshold () are provided to threshold an image [3-4].
two。 Fixed threshold treatment
The function threshold () is provided in OpenCV to realize the fixed threshold processing. The function prototype is as follows:
Dst = cv2.threshold (src, thresh, maxval, type [, dst])
-src represents an array of input images, 8-bit or 32-bit floating-point multichannel numbers
-dst represents the output image after threshold processing, and its type and number of channels are the same as those of src.
-thresh indicates threshold
-maxval represents the maximum value. When the parameter threshold type type selects CV_THRESH_BINARY or CV_THRESH_BINARY_INV, this parameter is the maximum value of the threshold type.
-type indicates the threshold type
The different types of processing algorithms for the threshold () function are shown in Table 1.
The corresponding threshold description is shown in figure 1:
Threshold processing is widely used in various industries, such as cell map segmentation in biology, license plate recognition in traffic field and so on. Through threshold processing, the image is converted into black and white image, so as to provide better support for subsequent image recognition and image segmentation. Five thresholding algorithms are described in detail below.
1. Binary thresholding
The prototype of this function is threshold (Gray,127,255,cv2.THRESH_BINARY). The method first selects a specific threshold value, such as 127, and then carries out the threshold processing according to the rules shown below.
When the grayscale value of the current pixel is greater than the thresh threshold, the grayscale value of the pixel is set to the maximum (for example, the maximum grayscale value of 8 bits is 255); otherwise, the grayscale value of the pixel is set to 0. If the threshold is 127 and the gray value of the pixel is 163, the threshold is set to 255; if the gray value of the pixel is 82, the threshold is set to 0.
The Python code for binary thresholding processing is as follows:
#-*-coding: utf-8-*-# By:Eastmountimport cv2 import numpy as np # read picture src = cv2.imread ('luo.png') # Grayscale image processing grayImage = cv2.cvtColor (src,cv2.COLOR_BGR2GRAY) # binary threshold processing r, b = cv2.threshold (grayImage, 127,255, cv2.THRESH_BINARY) # display image cv2.imshow ("src", src) cv2.imshow ("result", b) # waiting for cv2.waitKey (0) cv2.destroyAllWindows ()
The output is shown in figure 2. On the left is the original image of Xiao Luo, and on the right is the effect of binary thresholding of the original image. Pixel values greater than 127 are set to 255, and those less than or equal to 127 are set to 0.
two。 Anti-binary thresholding
The prototype of this function is threshold (Gray,127,255,cv2.THRESH_BINARY_INV). The method first selects a specific threshold value, such as 127, and then carries out the threshold processing according to the rules shown below.
When the grayscale value of the current pixel is greater than the thresh threshold, the grayscale value of the pixel is set to 0; otherwise, the grayscale value of the pixel is set to the maximum value. If the threshold is 127 and the gray value of the pixel is 211, the threshold is set to 0; if the gray value of the pixel is 101, the threshold is set to 255.
The Python code for the anti-binary thresholding process is as follows:
#-*-coding: utf-8-*-# By:Eastmountimport cv2 import numpy as np # read picture src = cv2.imread ('luo.png') # Grayscale image processing grayImage = cv2.cvtColor (src,cv2.COLOR_BGR2GRAY) # Anti-binary threshold processing r, b = cv2.threshold (grayImage, 127,255, cv2.THRESH_BINARY_INV) # display image cv2.imshow ("src", src) cv2.imshow ("result" B) # wait for cv2.waitKey (0) cv2.destroyAllWindows () to be displayed
The output is shown in figure 3:
3. Truncation threshold
The prototype of this function is threshold (Gray,127,255,cv2.THRESH_TRUNC). Pixels in the image that are greater than the threshold are set to the threshold, and those less than or equal to the threshold remain unchanged, such as 127. The new threshold generation rules are as follows:
For example, when the threshold is 127 and the gray value of the pixel is 167, the threshold is set to 127; if the gray value of the pixel is 82, the threshold is set to 82. The Python code to truncate the thresholding process is as follows:
#-*-coding: utf-8-*-# By:Eastmountimport cv2 import numpy as np # read picture src = cv2.imread ('luo.png') # Grayscale image processing grayImage = cv2.cvtColor (src,cv2.COLOR_BGR2GRAY) # truncated threshold processing r, b = cv2.threshold (grayImage, 127,255, cv2.THRESH_TRUNC) # display image cv2.imshow ("src", src) cv2.imshow ("result", b) # waiting for cv2.waitKey (0) cv2.destroyAllWindows ()
The output result is shown in figure 4, and the gray value of the image is processed between 0 and 127 after truncation threshold processing.
4. Threshold to 0
The prototype of this function is threshold (Gray,127,255,cv2.THRESH_TOZERO). The grayscale value of the image is processed according to the following formula.
When the grayscale value of the current pixel is greater than the thresh threshold, the grayscale value of the pixel remains the same; otherwise, the grayscale value of the pixel is set to 0. If the threshold is 127 and the gray value of the pixel is 211, the threshold is set to 211, and the gray value of the pixel is 101, the threshold is set to 0.
The Python code for image thresholding to zero is as follows:
#-*-coding: utf-8-*-# By:Eastmountimport cv2 import numpy as np # read picture src = cv2.imread ('luo.png') # Grayscale image processing grayImage = cv2.cvtColor (src,cv2.COLOR_BGR2GRAY) # threshold to zero processing r, b = cv2.threshold (grayImage, 127,255, cv2.THRESH_TOZERO) # display image cv2.imshow ("src", src) cv2.imshow ("result", b) # waiting for cv2.waitKey (0) cv2.destroyAllWindows ()
The output is shown in figure 5, where the lighter part is unchanged and the darker part is treated as 0.
5. The inverse threshold is changed to 0
The prototype of this function is threshold (Gray,127,255, cv2.THRESH_TOZERO_INV). The grayscale value of the image is processed according to the following formula.
When the grayscale value of the current pixel is greater than the thresh threshold, the grayscale value of the pixel is set to 0; otherwise, the grayscale value of the pixel remains the same. If the threshold is 127 and the gray value of the pixel is 211, the threshold is set to 0; if the gray value of the pixel is 101, the threshold is set to 101.
The Python code for processing an image with an inverse threshold of 0 is as follows:
#-*-coding: utf-8-*-# By:Eastmountimport cv2 import numpy as np # read picture src = cv2.imread ('luo.png') # Grayscale image processing GrayImage = cv2.cvtColor (src,cv2.COLOR_BGR2GRAY) # binary threshold processing r, b = cv2.threshold (GrayImage, 127,255, cv2.THRESH_TOZERO_INV) # display image cv2.imshow ("src", src) cv2.imshow ("result") B) # wait for cv2.waitKey (0) cv2.destroyAllWindows () to be displayed
The output is shown in figure 6:
Similarly, when we identify and protect the national totem and image, we also need to carry out image threshold processing. The following code is the comparison of the Miao clothing image of the five fixed threshold processing results.
#-*-coding: utf-8-*-# By:Eastmountimport cv2 import numpy as np import matplotlib.pyplot as plt# read image img=cv2.imread ('miao.png') grayImage=cv2.cvtColor (img,cv2.COLOR_BGR2GRAY) # threshold processing ret,thresh2=cv2.threshold (grayImage,127,255,cv2.THRESH_BINARY) ret,thresh3=cv2.threshold (grayImage,127,255,cv2.THRESH_BINARY_INV) ret,thresh4=cv2.threshold (grayImage,127,255,cv2.THRESH_TRUNC) ret,thresh5=cv2.threshold (grayImage,127255 Cv2.THRESH_TOZERO) ret,thresh6=cv2.threshold (grayImage,127,255,cv2.THRESH_TOZERO_INV) # shows the result titles = ['Gray Image','BINARY','BINARY_INV','TRUNC','TOZERO','TOZERO_INV'] images = [grayImage, thresh2, thresh3, thresh4, thresh5, thresh6] for i in range (6): plt.subplot (2), plt.imshow (images [I],' gray') plt.title (titles [I]) plt.xticks ([]) Plt.yticks ([]) plt.show ()
The output is shown in figure 7:
three。 Adaptive threshold processing
The previous description is the fixed value threshold processing method, but when different parts of the same image have different brightness, the above method is no longer applicable. At this time, it is necessary to adopt the adaptive threshold processing method, and calculate the corresponding threshold according to each small region of the image, so that different regions of the same image adopt different thresholds and get better results in the case of different brightness.
The adaptive thresholding process is implemented by calling the cv2.adaptiveThreshold () function in OpenCV, and the prototype is as follows:
Dst = adaptiveThreshold (src, maxValue, adaptiveMethod, thresholdType, blockSize, C [, dst])
-src represents the input image
-dst represents the output image after threshold processing, and its type and size should be the same as that of src.
-maxValue represents the maximum qualified value assigned to a pixel
-adaptiveMethod indicates the adaptive threshold algorithm to be applied. Common values include ADAPTIVE_THRESH_MEAN_C (the threshold takes the average of the neighborhood) or ADAPTIVE_THRESH_GAUSSIAN_C (the threshold is taken from the weighted and average of the neighborhood, and the weight distribution is a Gaussian function distribution).
-thresholdType indicates the threshold type. The value must be THRESH_BINARY or THRESH_BINARY_INV.
-blockSize indicates the neighborhood size of the pixel for calculating the threshold, with values of 3, 5, 7, etc.
-C represents a constant, and the threshold is equal to the average or the weighted average minus the constant
When the threshold type thresholdType is THRESH_BINARY, the formula for converting its grayscale image into a thresholding image is as follows:
When the threshold type thresholdType is THRESH_BINARY_INV, the formula for converting its grayscale image into a thresholding image is as follows:
Where dst (x _ ()) represents the grayscale value after threshold processing, and T (x _ ()) represents the threshold at which each individual pixel is calculated. The values are as follows:
When ADAPTIVE_THRESH_MEAN_C is used as the adaptiveMethod parameter, the threshold T (XMague y) is the average value of the parameter C in the neighborhood of blockSize × blockSize.
When ADAPTIVE_THRESH_GAUSSIAN_C is used as the adaptiveMethod parameter, the threshold T (XMagney) is the weighted sum of the cross-correlation between parameter C and Gaussian window in the neighborhood of blockSize × blockSize.
The following code compares fixed-value thresholding with adaptive thresholding.
#-*-coding: utf-8-*-# By:Eastmountimport cv2 import numpy as np import matplotlib.pyplot as pltimport matplotlib# read image img = cv2.imread ('miao.png') # Image graying processing grayImage = cv2.cvtColor (img, cv2.COLOR_BGR2GRAY) # fixed threshold processing r, thresh2 = cv2.threshold (grayImage, 127,255, cv2.THRESH_BINARY) # Adaptive threshold processing method-thresh3 = cv2.adaptiveThreshold (grayImage, 255, cv2.ADAPTIVE_THRESH_MEAN_C) Cv2.THRESH_BINARY, 11,2) # Adaptive threshold processing method II thresh4 = cv2.adaptiveThreshold (grayImage, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11,2) # set font matplotlib.rcParams ['font.sans-serif'] = [' SimHei'] # display image titles = ['grayscale image', 'global threshold', 'adaptive average threshold', 'adaptive Gaussian threshold'] images = [grayImage, thresh2, thresh3 Thresh4] for i in range (4): plt.subplot (2,2, iTun1), plt.imshow (images [I], 'gray') plt.title (titles [I]) plt.xticks ([]), plt.yticks ([]) plt.show ()
The output result is shown in figure 8, the upper left corner is the gray processing image, the upper right corner is the fixed global threshold processing image (cv2.threshold), the lower left corner is adaptive neighborhood average segmentation with more noise, and the lower right corner is adaptive neighborhood weighted average segmentation, using Gaussian function distribution, the effect is relatively good.
The above is about the content of this article on "how to deal with Python image thresholding". I believe we all have some understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please pay attention to the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.