Python中PIL与skimage读取图片的差异对比
本文对比了Python中PIL库与skimage库读取图片后的数据差异。重点解析了Image返回的PIL类型与skimage返回的numpy数组在形状(height, width)与(height, width, channel)上的区别,并说明了Caffe框架中transpose设置的原因及像素获取方法。
Python PIL与skimage读取图片差异分析
进行CNN开发时,往往需要处理大量的图像数据。由于接手的项目时间较短且处于初期阶段,前期的代码编写工作较为紧迫。现在稍作整理,毕竟总结是一个良好的编程习惯。
环境安装与代码示例
第一步,需要安装python-Image、python-skimage以及python-matplotlib这三个库。
以下是简单的示例代码:
import Image as img
import os
from matplotlib import pyplot as plot
from skimage import io,transform
import argparse
def show_data(data):
fig = plot.figure()
ax = fig.add_subplot(121)
ax.imshow(data, cmap='gray')
ax2 = fig.add_subplot(122)
ax2.imshow(data)
plot.show()
if __name__ == "__main__":
parse = argparse.ArgumentParser()
parse.add_argument('--picpath', help = "the picture' path")
args = parse.parse_args()
img_file1 = img.open(args.picpath)#Image读图片
one_pixel = img_file1.getpixel((0,0))[0]
print "picture's first pixe: ",one_pixel
print "the picture's size: ", img_file1.size#Image读出来的size是高宽
show_data(img_file1)
img_file2 = io.imread(args.picpath)#skimage读图片
show_data(img_file2)
print "picture's first pixel: ", img_file2[0][0][0]
print "the picture's shape: ", img_file2.shape#skimage读出来的shape是高,宽, 通道
调用上述代码并查看输出结果:

实际上,Image库读取图片后返回的是PIL图像类型,而skimage.io读取的数据则是numpy格式。若要直观对比两者读取图片后的区别,可以直接输出它们返回的结果进行观察。
数据格式与Caffe适配
第二步,对比Image和skimage读取图片的方式:
img_file1 = img.open(args.picpath)
img_file2 = io.imread(args.picpath)
第三步,查看读取图片后数据的大小差异:
print "the picture's size: ", img_file1.size
print "the picture's shape: ", img_file2.shape
第四步,获取图片中的像素值:
one_pixel = img_file1.getpixel((0,0))[0]
img_file2[0][0][0]
像素获取与数据维度详解
分析如下:
从第3点的输出可以看出,img读取图片后得到的是图片的(height, width)尺寸信息;
而skimage读取的是(height, width, channel)格式的数据。这也是为什么在使用Caffe进行单独测试时,需要在代码中设置transformer.set_transpose('data',(2,0,1)),因为Caffe处理的数据格式要求为(channel, height, width),所以必须进行数据转换。
对于img读取的图片,获取某一点像素值可以使用getpixel((h,w))直接返回该点三个通道的像素值。
对于skimage读取的图片,可以直接通过img_file2[0][0][0]获取,但务必注意其数据格式,它并非直观的(channel, height, width)排列。
关于matplotlib的简单绘图功能,请关注后续文章。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本站。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









