目录
前言
本次实验是计算机视觉第一次实验,旨在用python编程实现图像处理的基本操作。
编程工具:Pycharm
一、灰度变换
1.1 灰度图
把白色与黑色之间按对数关系分为若干等级,称为灰度。灰度分为256阶。
任何颜色都有红、绿、蓝三原色组成,即三通道,而灰度图只有一个通道,他有256个灰度等级,255代表全白,0表示全黑。灰度图像是指用灰度表示的图像,即一个像元用1个Byte(bits)表示辐射值。
1.2 彩色图像转灰度图像的方法
1.浮点法:Gray=R*0.3+G*0.59+B*0.11
2.整数法:Gray=(R*30+G*59+B*11)/100
3.移位法:Gray =(R*77+G*151+B*28)>>8;
4.平均值法:Gray=(R+G+B)/3;
5.仅取绿色:Gray=G;
1.3 采用convert()方法转换
PIL中convert()方法原理:
(1)img = img.convert()
convert()函数,用于不同模式图像之间的转换,PIL中有九种不同模式,分别为1,L,P,RGB,RGBA,CMYK,YCbCr,I,F。
(2)img = img.convert(‘1’)
转化为为二值图像,非黑即白。每个像素用8个bit表示,0表示黑,255表示白。
(3)img = img.convert(‘L’)
转换为为灰度图像,每个像素用8个bit表示,0表示黑,255表示白,其他数字表示不同的灰度。
转换公式:L = R * 299/1000 + G * 587/1000+ B * 114/1000。
1.4 代码展示
# 利用PIL库读取图像
from PIL import Image
import matplotlib.pyplot as plt
import numpy as np
img = Image.open('./image/JMU_2.jpg')
# 调用操作系统自带的图片浏览器打开图片,不太方便
# img.show()
# 使用matplotlib的库绘制图片进行显示
# plt.figure('JMU')
# plt.imshow(img)
# plt.axis('off') # 不显示坐标轴
# plt.show()
# 灰度变换
img_er =img.convert('1') # 1位像素,黑白,每字节一个像素存储
# 第一种方式:convert()函数
img_gray = np.array(img.convert('L')) # 8位像素,黑白
# img_gray = np.array(img_gray)
# 第二种方式:
im2 = 255 - img_gray # 对图像进行反相处理
# 第三种方式
im3 = (100.0/255) * img_gray +100 # 将图像像素值变换到100到200之间
# 第四种方式
im4 = 255.0 * (img_gray/255.0)**2 # 对图像像素值求平方后得到的图像
# 使其标题可以显示中文
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus'] = False
plt.figure('灰度变换')
plt.subplot(2,4,2)
plt.imshow(img)
plt.title('原图')
plt.axis('off')
plt.subplot(2,4,3)
plt.imshow(img_er,plt.cm.gray)
plt.title('二值图像')
plt.axis('off')
plt.subplot(2,4,5)
plt.imshow(img_gray,plt.cm.gray) # plt 是用于显示三通道的,而灰度图是单通道的,所以用plt.cm.gray
plt.axis('off')
plt.subplot(2,4,6)
plt.imshow(im2,plt.cm.gray)
plt.axis('off')
plt.subplot(2,4,7)
plt.imshow(im3,plt.cm.gray)
plt.axis('off')
plt.subplot(2,4,8)
plt.imshow(im4,plt.cm.gray)
plt.axis('off')
plt.show()