python读写图像的几种方式,PIL,imageio,pylibtiff

scikit-image提供了丰富的图像读写,处理操作

参考

【Tensorflow】辅助工具篇——scikit-image介绍

直接支持读写浮点TIFF图像

from skimage import io

img = io.imread('testimg.tif')


import numpy as np

data=np.random.random([100,100])

io.imsave('rand_data.tif',np.float32(data))

 

pillow/PIL库

https://pillow.readthedocs.io/en/5.1.x/index.html

imageio库

http://imageio.readthedocs.io/en/latest/index.html

http://imageio.github.io/

 结合pillowimageio给出一个我测试的例子

 

import numpy as np
import imageio
from PIL import Image #PIL pakage name is Pillow 


img=imageio.imread(r'G:\leopard.jpg')
high,width,ichannel=img.shape
print(type(img))
print(img.shape)
imageio.imwrite(r'G:\leopard_i1.jpg',img)
imageio.imwrite(r'G:\leopard_i2.jpg',np.float32(img/10)) # automatic brightness adjust
imageio.imwrite(r'G:\leopard_i3.jpg',np.uint8(img/10))


im = Image.open(r'G:\leopard.jpg')
print(type(im)) 
in_data = np.asarray(im, dtype=np.uint8)
print(type(in_data))
print(in_data.shape) 


new_im = Image.fromarray(in_data) # np.uint8, or TypeError: Cannot handle this data type

# new_im.show()
new_im.save(r'G:\leopard_p1.jpg')

我发现一些奇怪的现象:

1,如果RGB三个通道灰度值都特别相似,保存为jpg时会自动变成只有一个通道的灰度图。保存为png和bmp则没有了这个问题

2,imageio浮点图像会自动亮度调节,手动先转换为uint8会没有问题

 

读写MATLAB mat文件

import scipy.io as sio

# load mean and std

matfile = sio.loadmat(meanstd_file)

test_mean = np.array(matfile['mean_test'])

test_std = np.array(matfile['std_test'])



# Save predictions to a matfile to open later in matlab

mdict = {"Recovery": Recovery}

sio.savemat(savename, mdict)

io.imsave('Recovery.tif', np.float32(Recovery))

 

TIFF图像,pylibtiff库

https://github.com/pearu/pylibtiff

Usage example (libtiff wrapper)

from libtiff import TIFF

# to open a tiff file for reading:

tif = TIFF.open('filename.tif', mode='r')

# to read an image in the currect TIFFdirectory and return it as numpy array:

image = tif.read_image()

# to read all images in a TIFF file:

for image in tif.iter_images(): # do stuffwith image

 

# to open a tiff file for writing:

tif = TIFF.open('filename.tif', mode='w')

# to write a image to tiff file

tif.write_image(image)

Usage example (pure Python module)

from libtiff import TIFFfile, TIFFimage

# to open a tiff file for reading

tif = TIFFfile('filename.tif')

# to return memmaps of images and sample names (eg channel names,SamplesPerPixel>=1)

samples, sample_names = tiff.get_samples()

 

# to create a tiff structure from image data

tiff = TIFFimage(data, description='')

# to write tiff structure to file

tiff.write_file('filename.tif', compression='none') # or 'lzw'

del tiff # flushes data to disk

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Luchang-Li

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

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

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

打赏作者

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

抵扣说明:

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

余额充值