Python-彩色图像的二值化

效果展示

image_binary

理论部分

  • 灰度:表示图像像素明暗程度的数值,也就是黑白图像中点的颜色深度。范围一般为0-255。白色为255,黑色为0。

  • 通道:把图像分解成一个或多个颜色成分:

  • 单通道:一个像素点只需一个数值表示,只能表示灰度,0为黑色(灰度化和二值化)

  • 三通道:把图像分为红绿蓝三个通道,可以表示彩色(RGB模式)

  • 四通道:在RGB基础上加上alpha(透明度)通道,alpha=0表示全透明

  • RGB转化为灰度图

    • 浮点算法:Gray = R0.3 +G0.59 + B0.11
    • 整数算法:Gray = (R30 + G59 + B11) / 100
  • 二值化

    • Step1:灰度化:img_gray = rgb2gray(img)
    • Step2:二值化(阈值随意设置,这里设置为0.5):
    rows, cols = img_gray.shape
    img_binary = np.zeros([h,w],img.dtype)
    for i in range(rows):
    	for j in range(cols):
        	img_binary[i,j] = int(img_gray[i,j]+0.5)
    

代码部分

  • 使用库
    • opencv:安装使用pip install opencv-python,使用时用 import cv2
    • matplotlib:安装使用pip install matplotlib,使用时用 import matplotlib.pyplot as plt
    • skimage:安装使用pip install scikit-image,使用时用 import skimage
"""
@author: Hanley-Yang

彩色图像的二值化
"""
from skimage.color import rgb2gray
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import cv2

#灰度化处理
img = cv2.imread("shangri-la.jpg")
h,w = img.shape[:2]
img_gray = np.zeros([h,w],img.dtype)
# 遍历灰度化每个像素值
# for i in range(h):
#     for j in range(w):
#         init = img[i,j]
#         img_gray[i,j] = int((init[0]*0.11 + init[1]*0.59 + init[2]*0.3) / 255)
img_gray = rgb2gray(img)

#二值化
rows, cols = img_gray.shape
img_binary = np.zeros([h,w],img.dtype)
for i in range(rows):
    for j in range(cols):
        img_binary[i,j] = int(img_gray[i,j]+0.5)
print("---image gray----")
print(img_gray)

#img_binary = np.where(img_gray >= 0.5, 1, 0) #也可使用该方法二值化

print("---image binary---")
print(img_binary)
print(img_binary.shape)

#显示原始图片在画布上方
plt.subplot(211)
img = plt.imread("shangri-la.jpg")
plt.imshow(img)

#显示二值化图片在画布下方
plt.subplot(212)
plt.imshow(img_binary, cmap='gray')
plt.show()
  • 7
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Hanley_Yeung

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值