- 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()
from PIL import Image
import cv2
from matplotlib import pyplot as plt
def join(png1, png2, flag='horizontal'):
img1, img2 = Image.open(png1), Image.open(png2)
# 统一图片尺寸,可以自定义设置(宽,高)
img1 = img1.resize((110, 124), Image.ANTIALIAS)
img2 = img2.resize((110, 124), Image.ANTIALIAS)
size1, size2 = img1.size, img2.size
if flag == 'horizontal':
joint = Image.new('RGB', (size1[0] + size2[0], size1[1]))
loc1, loc2 = (0, 0), (size1[0], 0)
joint.paste(img1, loc1)
joint.paste(img2, loc2)
plt.imshow(joint)
plt.show()
# cv2.imshow("joint", "joint")
# joint.save('horizontal.png')
elif flag == 'vertical':
joint = Image.new('RGB', (size1[0], size1[1] + size2[1]))
loc1, loc2 = (0, 0), (0, size1[1])
joint.paste(img1, loc1)
joint.paste(img2, loc2)
# joint.save('vertical.png')
if __name__ == '__main__':
# 两张图片地址:
png1 = r"D:/Users/xuyf2/Desktop/lego_jier/crop2/2cp1637243269.jpg"
png2 = r"D:/Users/xuyf2/Desktop/lego_jier/crop1/1cp1637243581.jpg"
# 横向拼接
join(png1, png2, flag='horizontal')
# 纵向拼接
# join(png1, png2, flag='vertical')