python图片二值化

  • 导入相关库
import os
import cv2
import numpy as np
  • stdfilt函数(详见:链接一、链接二)
def stdfilt(img, mask):
    n = mask.sum()
    n1 = n - 1
    c1 = cv2.filter2D(img**2, -1, mask / n1, borderType=cv2.BORDER_REFLECT)
    c2 = cv2.filter2D(img, -1, mask, borderType=cv2.BORDER_REFLECT)**2 / (n * n1)
    sig = np.sqrt(np.maximum(c1 - c2, 0))

    return sig
  • localmean函数
def localmean(img, mask):
    lm = cv2.filter2D(
        img, -1, mask / mask.sum(),
        borderType=cv2.BORDER_REPLICATE)

    return lm
  • 二值化函数
def img_binary(img, w_size=3, w_sig=0.9, w_lm=0.9):
    if len(img.shape) != 2:
        img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
    img = img / 255.0
    mask = np.ones(w_size)

    sig = stdfilt(img, mask)
    if w_lm == 0:
        w_lm = 1
        lm = np.mean(img)
    else:
        lm = localmean(img, mask)

    img = 255 * ((img > sig * w_sig) & (img > w_lm * lm))

    return img
  • 二值化
if __name__ == '__main__':
    #False表示读取为灰度图...
    img = cv2.imread(filepath, False)
    img = img_binary(img, w_size=3, w_sig=0.9, w_lm=0.9)

你可能感兴趣的:(python)