数字图像二值化的几种实现方式

第一种:手动方式,分别用plt实现(注意我用的图是4通道的,因此这种方式需要先转成3通道,再来灰度化,没有直接的rgba2gray);opencv实现;以及Image实现。

from skimage.color import rgb2gray, rgba2rgb
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import cv2

#手动二值化
def hand_binary():
    """使用plt读图处理图,"""
    img = plt.imread("./data/cat.jpg")
    """此处plt.imread()读的图时四通道,需要先转成三通道,再转成灰度图"""
    img = rgba2rgb(img)  # 转成三通道图片
    img_gray = rgb2gray(img)  # 再来灰度化
    rows, cols = img_gray.shape  # 获取行数,列数
    for i in range(rows):
        for j in range(cols):
            if (img_gray[i, j] >= 0.5):  # 大于0.5给白色
                img_gray[i, j] = 1
            else:  # 小于0.5给黑色
                img_gray[i, j] = 0
    plt.imshow(img_gray, cmap="gray")
    plt.show()



    """opencv方式"""
    img = cv2.imread('./data/cat.jpg')
    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)  # 转为灰度图
    rows, cols = img_gray.shape[0:2]
    thresh = 60  # 设置阈值
    for row in range(rows):
        for col in range(cols):
            gray = img_gray[row, col]  # 获取到灰度值
            if gray > thresh:
                img_gray[row, col] = 255  # 如果灰度值高于阈值 就等于255最大值
            elif gray < thresh:
                img_gray[row, col] = 0  # 如果小于阈值,就直接改为0
    cv2.imshow('opencv_img', img_gray)
    cv2.waitKey()

    """使用Image读图处理图"""
    img = Image.open("./data/cat.jpg")
    Img = img.convert('L') #L表示灰度
    Img.show() #展示图象
    threshold = 150 #设置一个阈值,
    table = []
    for i in range(256):
        if i < threshold: #小于150给0
            table.append(0)
        else:              #大于150给1
            table.append(1)
    img1 = Img.point(table, '1') #1表示二值图
    img1.show()

if __name__ == '__main__':
    hand_binary() #手动二值化

plt实现结果:

 opencv实现结果

 

 Image实现结果:

 第二种:调用相关库实现二值化

 

# 调用库函数实现二值化
def auto_binary():
    """plt实现"""
    img = plt.imread("./data/cat.jpg")
    img_gray = rgb2gray(img)  # 灰度化
    img_binary = np.where(img_gray >= 0.5, 1, 0)
    plt.imshow(img_binary, cmap='gray')
    plt.show()

    """"opencv实现"""
    img = cv2.imread("./data/cat.jpg")
    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    cv2.threshold(img_gray, 127, 255, 0, img_gray)
    cv2.imshow('img_binary', img_gray)
    cv2.waitKey(0)
if __name__ == '__main__':
  
    #hand_binary()  # 手动二值化
     auto_binary()  # 调用库函数实现二值化

opencv库实现结果

plt库实现结果

 

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值