- PIL库是一个具有强大图像处理能力的第三方库
- 在命令行下的安装方法:pip install pillow
- 在使用过程中的引入方法:from PIL import Image
- Image 是 PIL 库中代表一个图像的类(对象)
- 图像是一个由像素组成的二维矩阵,每个元素是一个RGB值
# 读取图片
from PIL import Image
import numpy as np
from matplotlib import pyplot as plt
img = Image.open('D:/Users/xuyf2/Desktop/jier/photo.jpg')
print('img',img)
arr = np.array(img) # 获取图片的数组
print('shape',arr.shape) # 获取数组的状态
print(arr)
# img.show()
plt.imshow(img)
plt.show()
- img.convert(mode=None, matrix=None, dither=None, palette=0, colors=256)
- PIL有九种不同模式: 1,L,P,RGB,RGBA,CMYK,YCbCr,I,F
- 模式1 :二值图像 每个像素用8个bit表示,0表示黑,255表示白
- 模式L: 灰度图像 每个像素用8个bit表示,0为黑,255为白,其他数字表示不同的灰度
- 转换公式:L = R * 299/1000 + G * 587/1000+ B * 114/1000
# 读取图片
from PIL import Image
from matplotlib import pyplot as plt
img = Image.open('D:/Users/xuyf2/Desktop/jier/company.jpg')
#图片灰度处理
gray_img = img.convert('L')
plt.imshow(gray_img)
plt.show()
from PIL import Image
img = Image.open('D:/Users/xuyf2/Desktop/jier/company.jpg')
# 获取图片的基本信息
bands = img.getbands() # 显示该图片的所有通道
print(bands)
bbox = img.getbbox() # 获取图片左上角和右下角的坐标
print(bbox)
width, height = img.width, img.height # 获取图片宽度和高度
print(width, height)
from PIL import Image
import matplotlib.pyplot as plt
img = Image.open('D:/Users/xuyf2/Desktop/jier/company.jpg') # 读取图片
img_rotate = img.rotate(45) # 将图片旋转45度
plt.imshow(img_rotate) # 显示旋转后的图片
plt.show()
from PIL import Image
import matplotlib.pyplot as plt
img = Image.open('D:/Users/xuyf2/Desktop/jier/company.jpg') # 读取图片
img1 = img.crop((126,111,381,249))
# 剪切 crop()四个参数分别是:(左上角点的x坐标,左上角点的y坐标,右下角点的x坐标,右下角点的y坐标)
img1.save('D:/Users/xuyf2/Desktop/jier/company_1.jpg') # 保存图片
plt.imshow(img1) # 展示图片
plt.show()
from PIL import Image
import matplotlib.pyplot as plt
img = Image.open('D:/Users/xuyf2/Desktop/jier/company.jpg') # 读取图片
print(img.size)
width,height = img.size
img1 = img.resize((int(width*0.6),int(height*0.4)),Image.ANTIALIAS) # 缩放
print(img1.size)
#展示图片
plt.imshow(img1)
plt.show()