第一章:基本的图像操作和处理
1.1 PIL:Python图像处理类库
PIL(Python Imaging Library Python,图像处理类库)提供了通用的图像处理功能,以及大量有用的基本图像操作,比如图像缩放、裁剪、旋转、颜色转换等。
图像的读取和显示
from PIL import Image
import matplotlib.pyplot as plt #使用 matplotlib 来显示图片,可以让图片显示到jupyter的页面
pil_im = Image.open('123.jpg')
plt.axis('off') #取消显示横纵坐标
plt.imshow(pil_im)
plt.show() #显示打开的图片
图像的灰度图显示
使用 convert() 方法来实现。
from PIL import Image
import matplotlib.pyplot as plt #使用 matplotlib 来显示图片,可以让图片显示到jupyter的页面
pil_im = Image.open('123.jpg').convert('L')
plt.axis('off') #取消显示横纵坐标
plt.imshow(pil_im)
plt.show() #显示打开的图片
1.1.1转换图像格式
1.1.2创建缩略图
创建最长边为 50(横)40(纵)像素的缩略图
ps:为了方便看像素所以加上了横纵坐标
pil_im.thumbnail((50,40))
1.1.3复制和粘贴图像区域
crop() 方法:从一幅图像中裁剪指定区域:
box = (100,100,400,400)
region = pil_im.crop(box)
该区域用四元组来指定。四元组的坐标依次是(左,上,右,下)。PIL 中指定坐标系的左上角坐标为(0,0)。可以旋转上面代码中获取的区域。
paste() 方法:将该区域放回去。
具体实现如下:
from PIL import Image
import matplotlib.pyplot as plt #使用 matplotlib 来显示图片,可以让图片显示到jupyter的页面
pil_im = Image.open('123.jpg').convert('L')
box = (100,100,400,400)
region = pil_im.crop(box)
region = region.transpose(Image.ROTATE_180)
pil_im.paste(region,box)
plt.imshow(pil_im)
plt.show() #显示打开的图片
1.1.4调整尺寸和旋转
resize() 方法:该方法的参数是一个元组,用来指定新图像的大小
rotate() 方法:逆时针方式表示旋转角度
out = pil_im.resize((128,128))
out = pil_im.rotate(45)
1.2 Matplotlib
处理数学运算、绘制图表,或者在图像上绘制点、直线和曲线时,Matplotlib是个很好的类库,具有比 PIL 更强大的绘图功能。
1.2.1绘制图像、点和线
from PIL import Image
from pylab import *
# 读取图像到数组中
im = array(Image.open('123.jpg'))
# 绘制图像
imshow(im)
# 一些点
x = [