Python+OpenCV图像处理之图像二值化

在数字图像处理中,二值图像占有非常重要的地位,图像的二值化使图像中数据量大为减少,从而能凸显出目标的轮廓。

该函数的阈值操作属于像素级的操作,在灰度图中,每个像素都对应一个灰度值(0~255,0黑、255白),我们将阈值函数 threshold() 应用于图像,图像的灰度值与阈值进行比较,从而实现二值化处理,目的是滤除太大或太小值像素、消除噪声,从而从灰度图中获取二值图像(将图像的灰度值设置为0或255),实现增强整个图像呈现更为明显的黑白效果,同时也大大减少了数据量。

python实现

import cv2
import numpy as np


# 全局阈值
def threshold_demo(image):
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    # ret, binary = cv2.threshold(gray,0,255,cv2.THRESH_BINARY | cv2.THRESH_OTSU)
    # ret, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_TRIANGLE)
    # ret, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_TRUNC)
    ret, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
    print("阈值:", ret)
    cv2.imshow("binary", binary)


# 局部阈值
def local_threshold(image):
    gray = cv2.cvtColor(image,cv2.COLOR_BGRA2GRAY)
    # binary = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,25,10)
    binary = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 25, 10)
    cv2.imshow("binary ", binary)


def custom_threshold(image):
    gray = cv2.cvtColor(image,cv2.COLOR_BGRA2GRAY)
    h, w = gray.shape[:2]
    m = np.reshape(gray, [1, w*h])
    mean = m.sum()/(w*h)
    # binary = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,25,10)
    ret, binary = cv2.threshold(gray, mean, 255, cv2.THRESH_BINARY)
    cv2.imshow("binary ", binary)


if __name__ == "__main__":
    img = cv2.imread("image/img1.jpg")
    cv2.namedWindow("input image", cv2.WINDOW_AUTOSIZE)
    cv2.imshow("input image", img)
    custom_threshold(img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

全局阈值函数运行结果

局部阈值函数运行结果

(一)全局阈值函数cv2.threshold(src, thresh, maxval, type[, dst]) -> retval, dst

参数: src - 输入数组/图像(多通道,8位或32位浮点)

     thresh - 阈值

     maxval - 最大值,与#THRESH_BINARY和#THRESH_BINARY_INV阈值类型一起使用的最大值(maximum value)

     type - 阈值类型

     dst - 输出数组/图像(与src相同大小和类型以及相同通道数的数组/图像)。

此外,特殊值#THRESH_OTSU或#THRESH_TRIANGLE可以与上述值之一组合。 在这些情况下,函数使用Otsu或Triangle算法确定最佳阈值,并使用它而不是指定的阈值。

返回值:retval - 阈值 thresh    

              dst - 经函数处理后的图像 image

阈值类型

1)二进制阈值化   THRESH_BINARY

2) 反二进制阈值化THRESH_BINARY_INV 

3)截断阈值化 THRESH_TRUNC

4) 阈值化为0  THRESH_TOZERO

5) 反阈值化为0 THRESH_TOZERO_INV

  

(二)局部阈值函数cv2.adaptiveThreshold(src, maxValue, adaptiveMethod, thresholdType, blockSize, C[, dst]) -> dst

参数:src-输入图像(8位单通道图像)

     maxValue-使用 THRESH_BINARY 和 THRESH_BINARY_INV 的最大值.

     adaptiveMethod-自适应阈值算法,平均 (ADAPTIVE_THRESH_MEAN_C)或高斯(ADAPTIVE_THRESH_GAUSSIAN_C)

     thresholdType-阈值类型,必须为THRESH_BINARY或THRESH_BINARY_INV的阈值类型

     blockSize-块大小(奇数且大于1 )

     C-常数,从平均值或加权平均值中减去的数。 通常情况下,这是正值,但也可能为零或负值

返回值:dst-经函数处理过的图像

 

posted on 2019-06-27 11:17  九块九毛九  阅读(27952)  评论(0编辑  收藏  举报