[python-opencv]超大影象二值化方法
阿新 • • 發佈:2018-11-12
*分塊
*全域性閾值 VS 區域性閾值
1 import cv2 as cv 2 import numpy as np 3 4 def big_image_binary(image): 5 print(image.shape) 6 cw = 213 7 ch = 547 8 h,w = image.shape[:2] 9 gray = cv.cvtColor(image,cv.COLOR_BGR2GRAY) 10 for row in range(0,h,ch): 11 for col inrange(0,w,cw): 12 roi = gray[row:row+ch,col:col+cw] #進行分塊 13 print(np.std(roi),np.mean(roi)) 14 #全域性閾值方法 15 # ret,dst = cv.threshold(roi,127,256,cv.THRESH_BINARY|cv.THRESH_OTSU) 16 # gray[row:row + ch, col:col + cw] = dst 17 18 #全域性閾值過濾噪點方法 19 if np.std(roi) < 20: 20 gray[row:row + ch, col:col + cw] = 255 #塊的二維陣列平方差小於20時 將其設為255-變白 21 else: 22 ret,dst = cv.threshold(roi,127,256,cv.THRESH_BINARY|cv.THRESH_OTSU) 23 gray[row:row + ch, col:col + cw] = dst24 25 #區域性閾值方法 26 # dst = cv.adaptiveThreshold(roi,255,cv.ADAPTIVE_THRESH_GAUSSIAN_C,cv.THRESH_BINARY,127,20) 27 # gray[row:row + ch, col:col + cw] = dst 28 # print(np.std(dst),np.mean(dst)) #np.std(dst)計算矩陣的標準差 np.mean(dst) 均值 29 30 cv.imwrite('new_big_image3.jpg',gray) 31 32 src = cv.imread('BigImage_Binary1.jpg') 33 # cv.namedWindow('input_image',cv.WINDOW_AUTOSIZE) 34 # cv.imshow('input_image',src) 35 36 big_image_binary(src) 37 38 cv.waitKey(0) 39 cv.destroyAllWindows()
原圖:
全域性閾值效果:
全域性閾值過濾掉噪點效果:【上一張圖全域性閾值右邊還有噪點 過濾後噪點消失】
高斯C方法區域性閾值效果:
補充知識點:
#np.std() 標準差
#np.mean() 均值
>>> a = np.array([[1, 2], [3, 4]]) >>> np.std(a) # 計算矩陣全域性標準差 1.1180339887498949
>>> np.std(a) # 計算矩陣全域性標準差
2.5
>>> np.std(a, axis=0) # axis=0計算每一列的標準差
array([ 1., 1.])
>>> np.std(a, axis=1) # 計算每一行的標準差 array([ 0.5, 0.5])