0
点赞
收藏
分享

微信扫一扫

Python读写图像


Python有很多库可以进行图像文件的读写,比如图像处理包pillow,科学绘图库matplotlib等。
Pylibtiff用于tiff文件的读写,matplotlib本身不支持tiff图像。
下面简单给出使用的示例:

# _*_ coding: utf-8 _*

import numpy as np
from matplotlib import pyplot as plt
from PIL import Image
from libtiff import TIFFimage

# 使用PIL包的Image打开图像
# convert('L')用于将原始RGB图像转为灰度图像
im = Image.open('tree.jpg').convert('L').save('tree_0.png')

# 使用matplotlib读取图像然后保存为numpy中的数组
colorimg = np.array(plt.imread('tree.jpg'))
shape = colorimg.shape
# 循环遍历数组进行RGB图像的灰度合成
grayimg = np.zeros((shape[0], shape[1]))
for i in range(shape[0]):
for j in range(shape[1]):
grayimg[i, j] = colorimg[i, j, 0] * 0.299 + colorimg[i, j, 1] * 0.587 + colorimg[i, j, 2] * 0.114

# 使用matplotlib写入图像
plt.imsave('tree_1.png', grayimg)

# 查看matplotlib支持的数据格式
# plt.gcf().canvas.get_supported_filetypes()

# 使用libtiff写入tiff图像
TIFFimage(grayimg).write_file('tree_2.tiff')


举报

相关推荐

0 条评论