图像处理杂谈(rgb图像转灰度并获取该图像灰度数组)
提示:注意环境配置
一、RGB图片转灰度
提示:该功能可以由多种方法实现,本文列举一种常见方法
步骤:
打开目标图片=>建立对象=>使用convert转化
from PIL import Image
img = Image.open(path)
img = img.convert('L')
补充:convert方法
提示:还有其他更好的方法,欢迎补充
二、获取图像信息(PIL)
·步骤:
打开图像并建立Image对象=>获取图像尺寸=>设置初始数组=>获取灰度值信息
from PIL import Image
img = Image.open(path)
img = img.convert('L')
cols, rows = img.size #获取图片尺寸
temp_array = np.array(img) #获取数组信息
temp = [[0]*cols for i in range(rows)] #建立数组
print(temp_array) #A输出
for x in range(0, rows):
for y in range(0, cols):
temp[x][y] = temp_array[x, y]
print(temp) #B输出
注意:获取图像数组可以用numpy.array函数,为了便于观察完整,此处设置了额外的初始数组
输出样式:
A:(也可以添加"np.set_printoptions(threshold = np.inf)"使得数组不折叠)
B:
总结
提示:这里对文章进行总结:
源代码展示:
import numpy as np
from PIL import Image
class imgop:
def __init__(self,temp_path):
self.temp_path = temp_path
#获取图像灰度值
def grey_get(self):
img = Image.open(self.temp_path)
img = img.convert('L')
cols, rows = img.size #获取图片尺寸
temp_array = np.array(img) #获取数组信息
temp = [[0]*cols for i in range(rows)] #建立数组
#print(temp_array) #简略输出
for x in range(0, rows):
for y in range(0, cols):
temp[x][y] = temp_array[x, y]
print(temp) #详细输出
return temp_array
#主函数
if __name__ == '__main__':
path1 = 'test.png'
#查看mat文件数组中的参数并统计维度
mat_data = imgop(path1)
mat_data.grey_get()
print("运行结束")