彩色图像二值化

图像二值化是将图像用黑和白两种颜色表示

(彩色图像)——>灰度图像——>二值图像

我们将灰度阈值设置为128来进行二值化


算法公式

源码:

import cv2

import numpy as np

# BGR转化为灰度图像

def BGR2GRAY(img):

    b = img[:, :, 0].copy()

    g = img[:, :, 1].copy()

    r = img[:, :, 2].copy()

    # Gray scale

    out = 0.2126 * r + 0.7152 * g + 0.0722 * b

    out = out.astype(np.uint8)

    return out

# 二值化灰度图像

def binarization(img, th=128):

    img[img < th] = 0

    img[img >= th] = 255

    return img

# Read image

img = cv2.imread("../paojie.jpg").astype(np.float32)

# Grayscale

out = BGR2GRAY(img)

# Binarization

out = binarization(out)

# Save result

cv2.imwrite("out.jpg", out)

cv2.imshow("result", out)

cv2.waitKey(0)

cv2.destroyAllWindows()


原图

二值化后图像

参考:https://www.jianshu.com/p/6784fb2e4c67

原文地址:https://www.cnblogs.com/wojianxin/p/12492366.html