Python+OpenCV(八)——图像二值化

Python+OpenCV(八)——图像二值化

学习视频:python+opencv3.3视频教学 基础入门
其他学习记录:
Python+OpenCV(一)——基础操作
Python+OpenCV(二)——Numpy模块
Python+OpenCV(三)——色彩空间
Python+OpenCV(四)——像素运算
Python+OpenCV(五)——ROI和泛洪填充
Python+OpenCV(六)——均值/中值/自定义/高斯模糊、高斯噪声处理、高斯双边滤波
Python+OpenCV(七)——直方图及其应用
Python+OpenCV(九)——图像金字塔、图像梯度
Python+OpenCV(十)——Canny边缘提取
Python+OpenCV(十一)——直线检测、圆检测
Python+OpenCV(十二)——轮廓发现
Python+OpenCV(十三)——对象测量
Python+OpenCV(十四)——膨胀与腐蚀
Python+OpenCV(十五)——开闭操作
Python+OpenCV(十六)——顶帽、黑帽
Python+OpenCV(十七)——人脸识别
Python+OpenCV(十八)——数字/字母验证码识别

源码如下:

# -*- coding = utf-8 -*-
# @Time : 2021/8/2 21:20
# @Author : 西兰花
# @File : OpenCV08.py
# @Software : PyCharm


import cv2 as cv    # 引入OpenCV模块
import numpy as np


def threshold_demo(image):      # 全局阈值二值化
    gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
    ret, binary = cv.threshold(gray, 127, 255, cv.THRESH_BINARY | cv.THRESH_OTSU)
    print("threshold value %s" % ret)
    cv.imshow("binary_all", binary)


def local_threshold_demo(image):      # 局部阈值二值化
    gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
    binary = cv.adaptiveThreshold(gray, 255, cv.ADAPTIVE_THRESH_MEAN_C , cv.THRESH_BINARY, 25, 10)
    cv.imshow("binary_local", binary)


def custom_threshold_demo(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)
    print("mean : ", mean)
    ret, binary = cv.threshold(gray, mean, 255, cv.THRESH_BINARY)
    cv.imshow("custom", binary)


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:col + cw]
            dst = cv.adaptiveThreshold(roi, 255, cv.ADAPTIVE_THRESH_MEAN_C, cv.THRESH_BINARY, 127, 20)
            # 利用adaptiveThreshold_C消除一些的噪声
            gray[row:row + ch, col:col + cw] = dst
            print(np.std(dst), np.mean(dst))    # 计算每个分块的均值,标准差
    cv.imwrite("C:/Users/Administrator/Pictures/PS/big_image_binary.jpg", gray)


print("------ Hello OpenCV ------")
src = cv.imread("C:/Users/Administrator/Pictures/PS/5.jpg")     # 读取图像
# cv.imshow("input image_5.jpg", src)    # 显示图像
# threshold_demo(src)
# local_threshold_demo(src)
# custom_threshold_demo(src)
big_image_binary(src)
cv.waitKey(0)

cv.destroyAllWindows()  # 销毁/关闭所有窗口


输出结果:
1.全局阈值二值化、局部阈值二值化
Python+OpenCV(八)——图像二值化_第1张图片
2.均值二值化
Python+OpenCV(八)——图像二值化_第2张图片
3.超大图像二值化
Python+OpenCV(八)——图像二值化_第3张图片

你可能感兴趣的:(python+OpenCV,opencv,python,计算机视觉)