首先咱們來看看圖像二值化的過程,opencv一共有好幾種不一樣的二值化算法能夠使用,通常來講圖像的像素,亮度等條件若是超過了某個或者低於了某個閾值,就會恆等於某個值,能夠用於某些物體輪廓的監測:算法
導包:spa
import numpy as np import cv2 import matplotlib.pyplot as plt def show(image): plt.imshow(image) plt.axis('off') plt.show() def imread(image): image=cv2.imread(image) image=cv2.cvtColor(image,cv2.COLOR_BGR2RGB) return image
讀入圖像:code
image=imread('123.jpg') show(image) gray=cv2.cvtColor(image,cv2.COLOR_RGB2GRAY) plt.imshow(gray,'gray')#這裏須要加一個參數以後才能夠顯示灰度圖 plt.axis('off') plt.show()
進行二值化的參數設定:blog
ret1,thresh1 = cv2.threshold(gray,127,255,cv2.THRESH_BINARY) ret2,thresh2 = cv2.threshold(gray,127,255,cv2.THRESH_BINARY_INV) ret3,thresh3 = cv2.threshold(gray,127,255,cv2.THRESH_TRUNC) ret4,thresh4 = cv2.threshold(gray,127,255,cv2.THRESH_TOZERO) ret5,thresh5 = cv2.threshold(gray,127,255,cv2.THRESH_TOZERO_INV)
進行二值化:it
titles = ['original','BINARY','BINARY_INV','TRUNC','TOZERO','TOZERO_INV'] images = [gray, thresh1, thresh2, thresh3, thresh4, thresh5] plt.figure(figsize=(15,5)) for i in range(6): plt.subplot(2,3,i+1) plt.imshow(images[i],'gray') plt.title(titles[i]) plt.axis('off') plt.show()