opencv for python (11) image threshold and adaptive threshold

Keywords: REST

Function cv2.threshold (IMG, 127255, CV2. Threshold)
The four parameters in the function are original image, threshold, maximum value and threshold type
Generally, there are five types of thresholds:
Cv2.threshold - part of the pixel value greater than the threshold becomes the maximum value, others become 0
Cv2.thresh ﹣ binary ﹣ inv -- the part greater than the threshold value becomes 0, and the other parts become the maximum value
Cv2.thresh ﹣ TRUNC -- the part greater than the threshold becomes the threshold, and the rest remains unchanged
Cv2.thresh_zero -- the part greater than the threshold value remains unchanged, and the rest becomes 0
Cv2.thresh ﹣ zero ﹣ inv -- the part greater than the threshold value changes to 0, and the rest remains unchanged

import cv2   
import numpy as np   
from matplotlib import pyplot as plt 

img = cv2.imread('test2.jpg')
ret,thresh1 = cv2.threshold(img,127,255,cv2.THRESH_BINARY)
ret,thresh2 = cv2.threshold(img,127,255,cv2.THRESH_BINARY_INV)
ret,thresh3 = cv2.threshold(img,127,255,cv2.THRESH_TRUNC)
ret,thresh4 = cv2.threshold(img,127,255,cv2.THRESH_TOZERO)
ret,thresh5 = cv2.threshold(img,127,255,cv2.THRESH_TOZERO_INV)

titles = ['Original Image','BINARY','BINARY_INV','TRUNC','TOZERO','TOZERO_INV']
images = [img,thresh1,thresh2,thresh3,thresh4,thresh5]

for i in xrange(6):
    plt.subplot(2,3,i+1),plt.imshow(images[i],'gray')
    plt.title(titles[i])
    plt.xticks([]),plt.yticks([])
plt.show()

cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,11,2)
Adaptive threshold is to calculate the corresponding threshold according to each small area of the image, so different thresholds are used in the same image, so that we can get better results in the case of different brightness.

import cv2   
import numpy as np   
from matplotlib import pyplot as plt 

img = cv2.imread('CAM003.png',0)
img = cv2.medianBlur(img,5)
ret,th1 = cv2.threshold(img,110,255,cv2.THRESH_BINARY)
th2 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,11,2)
th3 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,11,2)

titles = ['orgianl Image','Gllobal Thresholding(v=127)','ADaptive Mean Thresholding','Adaptive Gaussian Thresholding']
images = [img,th1,th2,th3]

for i in xrange(4):
    plt.subplot(2,2,i+1),plt.imshow(images[i],'gray')
    plt.title(titles[i])
    plt.xticks([]),plt.yticks([])
plt.show()

Posted by deed02392 on Sun, 03 May 2020 02:45:24 -0700