1. 程式人生 > >opencv學習(十六):超大影象二值化

opencv學習(十六):超大影象二值化

超大影象二值化的方法

        1.可以採用分塊方法;2.先縮放處理就行二值化,然後還原大小。

一:分塊處理超大影象的二值化問題

#匯入cv模組
import cv2 as cv
import numpy as np

#超大影象二值化
def big_image_binary(image):
    print(image.shape) #超大影象,螢幕無法顯示完整
    cw=256
    ch=256
    h,w=image.shape[:2]
    gray=cv.cvtColor(image,cv.COLOR_BGR2GRAY) #要二值化影象,要先進行灰度化處理
    for row in range(0,h,ch):     
        for col in range(0,w,cw):
            roi=gray[row:row+ch,col:cw+col]#獲取分塊
            print(np.std(roi),np.mean(roi))
            ret,dst=cv.threshold(roi,0,255,cv.THRESH_BINARY|cv.THRESH_OTSU)#全域性閾值 
            gray[row:row+ch,col:cw+col]=dst   #分塊覆蓋
            print(np.std(dst),np.mean(dst))
    cv.imshow("big_image_binary",gray)
    cv.imwrite("F:/Projects/images/result_binary.jpg",gray)


print("------------Hi,Python!-------------")
# 讀取影象,支援 bmp、jpg、png、tiff 等常用格式
src = cv.imread("F:/Projects/images/big_text.jpg")
#建立視窗並顯示影象
cv.namedWindow("input image",cv.WINDOW_AUTOSIZE)
cv.imshow("input image",src)   #顯示原圖
big_image_binary(src)
cv.waitKey(0)
#釋放視窗
cv.destroyAllWindows()

(一)全域性閾值處理

ret,dst=cv.threshold(roi,0,255,cv.THRESH_BINARY|cv.THRESH_OTSU)#全域性閾值

(二)區域性閾值處理

binary = cv.adaptiveThreshold(roi,255,cv.ADAPTIVE_THRESH_GAUSSIAN_C,cv.THRESH_BINARY,127,20)  #區域性閾值

二:空白區域過濾

def big_image_binary(image):
    print(image.shape)  #(4208, 2368, 3)
    cw,ch = 128,128
    h,w = image.shape[:2]
    gray = cv.cvtColor(image,cv.COLOR_RGB2GRAY)   #要二值化影象,要先進行灰度化處理
    for row in range(0,h,ch):
        for col in range(0,w,cw):
            roi = gray[row:row+ch,col:col+cw]   #獲取分塊
            dev = np.std(roi)
            avg = np.mean(roi)
            if dev < 15 and avg > 200:  #滿足條件,接近空白區域,讓他變黑
                gray[row:row + ch, col:col + cw] = 0    #全部都賦值為0
            else:
                ret,binary = cv.threshold(roi,0,255,cv.THRESH_BINARY|cv.THRESH_OTSU)
                gray[row:row + ch, col:col + cw] = binary
                print(np.std(binary), np.mean(binary))

    cv.imwrite("binary.jpg",gray)