PIL库

PIL库

PIL库是一个具有强大图像处理能力的第三方库。

图像的组成:由RGB三原色组成,RGB图像中,一种彩色由R、G、B三原色按照比例混合而成。0-255区分不同亮度的颜色。

图像的数组表示:图像是一个由像素组成的矩阵,每个元素是一个RGB值

Image 是 PIL 库中代表一个图像的类(对象)

In [3]
#安装pillow
#!pip install pillow
In [ ]
展示图片,并获取图像的模式,长宽,
In [35]
from PIL import Image
import matplotlib.pyplot as plt
#显示matplotlib生成的图形
%matplotlib inline

#读取图片
img = Image.open('/home/aistudio/work/yushuxin.jpg') 

#显示图片
#img.show() #自动调用计算机上显示图片的工具

plt.imshow(img)  
plt.show(img)   

#获得图像的模式
img_mode = img.mode
print(img_mode)

width,height = img.size
print(width,height)

<Figure size 432x288 with 1 Axes>
RGB
533 300

图片旋转

In [19]
from PIL import Image
import matplotlib.pyplot as plt
#显示matplotlib生成的图形
%matplotlib inline

#读取图片
img = Image.open('/home/aistudio/work/yushuxin.jpg') 
#显示图片
plt.imshow(img)  
plt.show(img)  

#将图片旋转45度
img_rotate = img.rotate(45) 
#显示旋转后的图片
plt.imshow(img_rotate)  
plt.show(img_rotate)   
<Figure size 432x288 with 1 Axes>
<Figure size 432x288 with 1 Axes>

图片剪切

In [20]
from PIL import Image

#打开图片
img1 = Image.open('/home/aistudio/work/yushuxin.jpg') 

#剪切 crop()四个参数分别是:(左上角点的x坐标,左上角点的y坐标,右下角点的x坐标,右下角点的y坐标)
img1_crop_result = img1.crop((126,0,381,249))

#保存图片
img1_crop_result.save('/home/aistudio/work/yushuxin_crop_result.jpg')

#展示图片
plt.imshow(img1_crop_result)  
plt.show(img1_crop_result)   
<Figure size 432x288 with 1 Axes>

图片缩放

In [21]
from PIL import Image

#打开图片
img2 = Image.open('/home/aistudio/work/yushuxin.jpg') 

width,height = img2.size

#缩放
img2_resize_result = img2.resize((int(width*0.6),int(height*0.6)),Image.ANTIALIAS)

print(img2_resize_result.size)

#保存图片
img2_resize_result.save('/home/aistudio/work/yushuxin_resize_result.jpg')

#展示图片
plt.imshow(img2_resize_result)  
plt.show(img2_resize_result)   
(319, 180)
<Figure size 432x288 with 1 Axes>

镜像效果:左右旋转、上下旋转

In [22]
from PIL import Image

#打开图片
img3 = Image.open('/home/aistudio/work/yushuxin.jpg') 

#左右镜像
img3_lr = img3.transpose(Image.FLIP_LEFT_RIGHT)

#展示左右镜像图片
plt.imshow(img3_lr)  
plt.show(img3_lr)   

#上下镜像
img3_bt = img3.transpose(Image.FLIP_TOP_BOTTOM)

#展示上下镜像图片
plt.imshow(img3_bt)  
plt.show(img3_bt)  


<Figure size 432x288 with 1 Axes>
<Figure size 432x288 with 1 Axes>
posted @ 2021-03-18 11:28  华小电  阅读(148)  评论(0编辑  收藏  举报