Python-彩色图像的灰度化

效果

img_gray

理论部分

  • 灰度:表示图像像素明暗程度的数值,也就是黑白图像中点的颜色深度。范围一般为0-255。白色为255,黑色为0。
  • 通道:把图像分解成一个或多个颜色成分:
    • 单通道:一个像素点只需一个数值表示,只能表示灰度,0为黑色
    • 三通道:把图像分为红绿蓝三个通道,可以表示彩色(RGB模式)
    • 四通道:在RGB基础上加上alpha(透明度)通道,alpha=0表示全透明
  • RGB转化为Gray
    • 浮点算法:Gray = R0.3 +G0.59 + B0.11
    • 整数算法:Gray = (R30 + G59 + B11) / 100
  • 将RGB值转化为[0,1]浮点数:x/255即可

代码部分

  • 使用库
    • 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
import cv2

#读取原图片,创建空白单通道图片
img = cv2.imread("shangri-la.jpg")
h,w,c = img.shape[:3]   #获取图片的high,wide和channel
img_gray = np.zeros([h,w],img.dtype) #创建一张和当前图片大小一样的单通道图片

#二维循环,取出当前high和wide中的RGB坐标
for i in range(h):
    for j in range(w):
        m = img[i,j]
        img_gray[i,j] = int(m[0]*0.11 + m[1]*0.59 + m[2]*0.3)

#输出原始图片像素参数
print("---image shangri-la---")
#输出灰度化图片像素参数
print(m)
print("---image gray----")
print(img_gray)
print("image show gray: %s"%img_gray)
cv2.imshow("image show gray",img_gray)

#显示原始图片在画布上方
img = plt.imread("shangri-la.jpg")
plt.subplot(211) #高2宽1的画布,图片放置在位置1(画布上方)
plt.imshow(img)

#显示灰度化图片在画布下方
#img_gray = rgb2gray(img)  #也可以直接使用rgb2gray方法灰度化
plt.subplot(212)
plt.imshow(img_gray, cmap='gray')


plt.show()
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Hanley_Yeung

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

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

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

打赏作者

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

抵扣说明:

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

余额充值