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

 

你可能感兴趣的:(深度学习)