Python图像读取

#图像读取
<图像预处理Python的初学笔记>

  • 实现图像的缩放,灰度变换
  • 使用PIL和skimage

使用两种方法对图像进行处理,开始的时候不知道应该用哪个库对图像进行处理,所以先使用这两种库进行处理,实现一幅图像的读取旋转和缩放。


#一幅图像的预处理方法:
import numpy as np
import matplotlib.pyplot as plt

#方法一: 使用PIL库
from PIL import Image
path = '/home/2092.jpg'  #图像所在的路径
f = Image.open(path)    #open图像的路径
img = f.convert('P')    #对图像进行灰度变换
img1 = img.transpose(Image.FLIP_LEFT_RIGHT) #左右镜像旋转
img2 = img.transpose(Image.FLIP_TOP_BOTTOM) #图像上下镜像旋转
img = np.asarray(img, dtype=np.float32)     #0-255灰度范围
img[np.newaxis]
img.shape   #图像的大小
plt.imshow(img)  #显示图像
plt.show() 
#读取的图像的灰度范为是0-255,图像显示如下:

和真实的图像比较,发现PIL读取的图像有很多瑕疵
这里写图片描述对于显示出来的图像和原来的图像不太一样,所以,可以将图像的形式转化为‘L’形式,即f.convert(‘L’).

#方法二:使用skimage库
from skimage import io, transform, color
data_path = '/home/2092.jpg'
image = io.imread(data_path)  #读取图像
image = color.rgb2gray(image)  #0-1灰度范围
import matplotlib.pyplot as plt
plt.imshow(image)
plt.show()
image.shape

使用skimage显示出的图像是0-1灰度范围,显示结果如下:
这里写图片描述


#实现图像的缩放:
image1 = transform.resize(image, (256, 256))
plt.imshow(image1)
plt.show()

#实现图像的旋转
image2 = transform.rotate(image1, 90)
plt.imshow(image2, 'gray')  #gray表示显示的颜色
plt.show()

图像的大小缩放:
这里写图片描述

图像的旋转:
这里写图片描述

猜你喜欢

转载自blog.csdn.net/Jingnian_destiny/article/details/81534065