Opencv for Python之圖像二值化

Opencv4 官方文檔 : https://docs.opencv.org/4.2.0/
Opencv4 for Python中文文檔點擊下載:Opencv4 for Python 中文文檔

圖像二值化就是讓圖像的像素點矩陣中的每個像素點的灰度值爲0(黑色)或者255(白色),也就是讓整個圖像呈現只有黑和白的效果。在灰度化的圖像中灰度值的範圍爲0~255,在二值化後的圖像中的灰度值範圍是0或者255。比如下圖就是二值化後的圖片:

在這裏插入圖片描述

1.環境

Python 3.7 + OpenCV 4.2

2.部分api及其參數解析

方法一:

cv.threshold(src, thresh, maxval, type, dst=None)

參數:
. @src: input array (multiple-channel, 8-bit or 32-bit floating point).輸入圖像(多通道,8位或者32位或者浮點型)
. @dst:output array of the same size and type and the same number of channels as src.輸出圖像,
. @thresh:threshold value.二值化閾值,大於該閾值變爲白色 小於變爲黑色。
. @maxval:maximum value to use with the #THRESH_BINARY and #THRESH_BINARY_INV thresholding types.最大閾值。
. @type:thresholding type (see #ThresholdTypes).閾值類型。
. @return the computed threshold value if Otsu’s or Triangle methods used.

方法二:

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

參數:
blockSize:Size of a pixel neighborhood that is used to calculate a threshold value for the pixel: 3, 5, 7, and so on.表.示塊大小(奇數且大於1,比如3,5,7… )

3.二值化方法及其效果:

3.1 全局閾值

def all_threshold(image):#全局閾值
    gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)

    ret, binary = cv.threshold(gray, 90, 255, cv.THRESH_BINARY | cv.THRESH_OTSU)
                                              #cv.THRESH_BINARY_INV和上面閾值一樣,但是效果相反

    cv.imshow("all_threshold", binary)

在這裏插入圖片描述
threshold_type:閾值類型小demo

def part_threshold(image):#thread_different_type
    img = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
    ret, thresh1 = cv.threshold(img, 127, 255, cv.THRESH_BINARY)
    ret, thresh2 = cv.threshold(img, 127, 255, cv.THRESH_BINARY_INV)
    ret, thresh3 = cv.threshold(img, 127, 255, cv.THRESH_TRUNC)
    ret, thresh4 = cv.threshold(img, 127, 255, cv.THRESH_TOZERO)
    ret, thresh5 = cv.threshold(img, 127, 255, cv.THRESH_TOZERO_INV)
    titles = ['Original Image', 'BINARY', 'BINARY_INV', 'TRUNC', 'TOZERO', 'TOZERO_INV']
    images = [img, thresh1, thresh2, thresh3, thresh4, thresh5]

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

    plt.show()

在這裏插入圖片描述

3.2 部分閾值:自適應閾值

def threshold_adaptive(image):
    img = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
    # 中值濾波
    img = cv.medianBlur(img, 5)

    ret, th1 = cv.threshold(img, 127, 255, cv.THRESH_BINARY)
    # 11 爲 Block size, 2 爲 C 值
    th2 = cv.adaptiveThreshold(img, 255, cv.ADAPTIVE_THRESH_MEAN_C, cv.THRESH_BINARY, 11, 2)
    th3 = cv.adaptiveThreshold(img,255,cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.THRESH_BINARY, 11, 2)

    titles = ['Original Image', 'Global Threshold (v = 127)', 'Adaptive Mean Threshold', 'Adaptive Gaussian Threshold']
    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()

在這裏插入圖片描述

3.3 自定義閾值

def threshold_custom(image):
    gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
    h, w = gray.shape[:2]
    m = np.reshape(gray, [1, w*h]) #降維
    mean = m.sum() / (w*h)  # 求出整個灰度圖像的平均值
    ret, binary = cv.threshold(gray, mean, 255, cv.THRESH_BINARY)#利用均值將圖像二值化
    cv.imshow("threshold_custom", binary)

3.4 超大圖像二值化

def big_image_demo(image):
    print(image.shape)
    cv.imshow("sourcePic",image)
    cw = 256
    ch = 256
    h, w = image.shape[:2]
    gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
    cv.imshow("big_image_demo_gray", gray)

    # 將一張圖片每隔ch * cw分成一份
    for row in range(0, h, ch):
        for col in range(0, w, cw):
            roi = gray[row:row+ch, col:col+cw]
            dst = cv.adaptiveThreshold(roi, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.THRESH_BINARY, 127, 80)#均值+80才變成黑色
            gray[row:row + ch, col:col + cw] = dst
            print(np.std(dst), np.mean(dst))

    cv.imshow("-",gray)

在這裏插入圖片描述
轉載請註明轉自:https://leejason.blog.csdn.net/article/details/106417184

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章