程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Realization of batch image binarization in Python

編輯:Python

The meaning of binarization : An image contains the target object 、 There's noise in the background , In order to extract the target object directly from the multi value digital image , The common way is to set a threshold T, use T Divide the image data into two parts : Greater than T The pixel group of and less than T The pixel group of . This is the most special way to study gray scale transformation , Called image Two valued Binarization). 

There are two commonly used threshold functions : Global threshold and Adaptive threshold

  • cv2.threshold(src, thresh, maxval, type) 
  • cv2.adaptiveThreshold(src, maxValue, adaptiveMethod, thresholdType, blockSize, C, dst=None)

1. cv2.threshold() function  

cv2.threshold(src, thresh, maxval, type)

Function explanation  

  Parameter meaning :

Parameters describe return src Source image , It has to be a single channel , That's grayscale Returns two values : threshold 、 Binary figure thresh Threshold value for classifying pixel values , Value range 0~255maxval Fill color , If the pixel value is greater than ( Sometimes less than ) Threshold is the value to be given , Value range 0~255type Threshold type

Threshold type table :

threshold Show by number Pixels smaller than the threshold Pixels larger than the threshold cv2.THRESH_BINARY0 Set up 0 Set fill color maxvalcv2.THRESH_BINARY_INV1 Set fill color maxval Set up 0cv2.THRESH_TRUNC2 Keep the primary color Gray cv2.THRESH_TOZERO3 Set up 0 Keep the primary color cv2.THRESH_TOZERO_INV4 Keep the primary color

Set up 0

Functional expression :

  visualization :

python Code & design sketch

import cv2
import numpy as np
from matplotlib import pyplot as plt
img=cv2.imread('123.jpg')
GrayImage=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret,thresh1=cv2.threshold(GrayImage,127,255,cv2.THRESH_BINARY)
ret,thresh2=cv2.threshold(GrayImage,127,255,cv2.THRESH_BINARY_INV)
ret,thresh3=cv2.threshold(GrayImage,127,255,cv2.THRESH_TRUNC)
ret,thresh4=cv2.threshold(GrayImage,127,255,cv2.THRESH_TOZERO)
ret,thresh5=cv2.threshold(GrayImage,127,255,cv2.THRESH_TOZERO_INV)
titles = ['Gray Image','BINARY','BINARY_INV','TRUNC','TOZERO','TOZERO_INV']
images = [GrayImage, 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()

effect : 

 2. Single image binarization

Code : 

import cv2
img = cv2.imread("001.png")
print(img)
# First, perform grayscale processing , Then binary
Grayimg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 127 Is the binarization threshold , Greater than 255 All pixel values of are set to 0
ret, thresh = cv2.threshold(Grayimg, 127, 255, cv2.THRESH_TOZERO_INV)
cv2.imwrite('0001.png', thresh)

effect ( The picture on the left is the original , The figure on the right is a binary graph ) :

3. Batch image binarization

  Code :

def binarization():
# Get all the picture names in the directory
filename = os.listdir(r"F:\python_Demo\DeepLearning\tools3\shapes\cmutestGT")
print(filename)
# os.listdir() Method to return a list of the names of the files or folders contained in the specified folder .
base_dir = r"F:\python_Demo\DeepLearning\tools3\shapes\CmutestGT" # input
new_dir = r"F:\python_Demo\DeepLearning\tools3\shapes\GT1" #output
for img in filename:
name = img
path1= os.path.join(base_dir,img)
img = cv2.imread(path1)
# print(img)
Grayimg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(Grayimg, 250, 255,cv2.THRESH_TOZERO_INV)
cv2.imwrite('img.png', thresh)
image = Image.open('img.png')
# The image can be resized if necessary
#image = image.resize((350, 350),Image.ANTIALIAS)
path= os.path.join(new_dir,name)
image.save(path)
binarization()

effect :

 4. cv2.adaptiveThreshold() function

The global threshold only needs to specify a threshold value , The whole image is compared to this threshold .

Adaptive threshold can be regarded as a local threshold , By specifying the size of an area , Compare this point with the average value of pixels in the area size ( Or other characteristics ) The size relationship determines whether the pixel belongs to black or white ( If it's a binary case ).

When different parts of the same image have different brightness , Adaptive threshold is adopted . At this time, the threshold value is calculated according to each small area on the image . Thus, better results can be obtained in the case of different brightness .

cv2.adaptiveThreshold(src, maxValue, adaptiveMethod, thresholdType, blockSize, C, dst=None)

Function explanation  

Parameter meaning : 

Parameters describe return src The source image , grayscale Returns two values : threshold 、 Binary figure maxValue Fill color ,0-255adaptiveMethod Adaptive threshold method thresholdType Threshold type blockSize Domain size , Take an odd number C Constant term for threshold calculation dst Output chart , Negligible

adaptiveMethod:

Adaptive methods explain Calculation cv2.ADPTIVE_THRESH_MEAN_C Is the average of local neighborhood blocks . The threshold value is taken from the average value of adjacent areas First find the average of the blocks , Subtract the constant term Ccv2.ADPTIVE_THRESH_GAUSSIAN_C Is the Gaussian weighted sum of local neighborhood blocks . The threshold value is the weighted sum of adjacent areas , The weight is a Gaussian window First find the weighted sum of the blocks , Subtract the constant term C

thresholdType: 

threshold Show by number Pixels smaller than the threshold Pixels larger than the threshold cv2.THRESH_BINARY0 Set up 0 Set fill color maxvalcv2.THRESH_BINARY_INV1 Set fill color maxval Set up 0

python Code & design sketch  

import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread('test.jpg', 0)
# median filtering
img = cv2.medianBlur(img, 5)
ret, th1 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
th2 = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2)
th3 = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2)
titles = ['Original Image', 'Global Thresholding(v=127)', 'Adaptive Mean Thresholding', 'Adaptivw Gaussian Thresholding']
images = [img, th1, th2, th3]
for i in range(4):
plt.subplot(2, 2, i+1), plt.imshow(images[i], 'gray')
plt.title(titles[i])
plt.xticks([]),plt.yticks([])
plt.show()

effect : 

Reference blog

Batch image binarization python Code implementation

Opencv: Image binarization cv2.threshold()_ Accomplish sth. lasting by leading a quiet life * The blog of -CSDN Blog _cv2 Two valued

 OpenCV-Python: For image binarization / Denoising cv2.threshold() Function details - Grey letter network ( Software development blog aggregation )

Image threshold _ Yes cv2.threshold,cv2.adaptiveThreshold etc. . - Mind, Ruogu - Blog Garden


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved