2.PIL的基本用法
一、PIL中Image的基本用法
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
class PILUsing:
def __init__(self, path):
pass
def show_Image_Size(self, image):
"""
查看图片的大小
:param image: 图片
:return: 返回图片的w和h的元组
"""
return image.size
if __name__ == '__main__':
path = r"./01.jpg"
img = Image.open(path)
' 查看图像的尺寸'
w, h = img.size
'图像转换numpy'
a = np.array(img)
print(a.shape)
print(a.size)
'numpy数组转换成图像'
image = Image.fromarray(a)
print(image)
image.show()
'返回像素直方图,统计每个像素值出现的次数'
his = img.histogram()
print(his)
print(len(his))
plt.hist(his)
plt.show()
'查看指定坐标位置的像素点的RGB值,返回的是一个元组'
pixes = img.getpixel((120, 80))
print(pixes)
'使用切片的方法裁剪图片'
print(np.array(img)[100:600, 500:1000, :])
img2 = Image.fromarray(np.array(img)[100:600, 500:1000, :])
plt.imshow(img2)
plt.xticks([])
plt.yticks([])
plt.axis('off')
plt.show()
'使用Image中裁剪工具裁剪图片'
img2 = img.crop((400, 500, 1000, 1000))
plt.imshow(img2)
plt.show()
'按指定大小缩放图片'
x = img.resize((100, 100))
x = img.resize((int(w / 2), int(h / 2)))
plt.imshow(x)
plt.show()
'thumbnail 按最大边等比例缩放,没有返回值'
img.thumbnail((1000, 800))
plt.imshow(img)
plt.show()
'将一张图片按指定位置粘贴到另一张图片上'
img02 = Image.open("02.jpg")
img.paste(img02, (10, 10))
plt.imshow(img)
plt.axis('off')
plt.show()
'保存图片'
img.save("03.jpg")
'生成一张空白图片'
image = Image.new("RGB", (100, 100), (0, 0, 0))
image.show()
二、Image、ImageFilter、ImageDraw、ImageFont的基本使用(结合plt)
from PIL import Image, ImageFilter, ImageDraw, ImageFont
import matplotlib.pyplot as plt
image = Image.open("./01.jpg")
'加入模糊'
img1 = image.filter(ImageFilter.BLUR)
img2 = image.filter(ImageFilter.DETAIL)
img3 = image.filter(ImageFilter.CONTOUR)
img4 = image.filter(ImageFilter.EMBOSS)
'ImageDraw的使用'
draw = ImageDraw.Draw(image)
draw.point(xy=(200, 300), fill="red")
draw.line(xy=(300, 300, 1000, 1000), fill='blue', width=3)
draw.rectangle((30, 50, 80, 100), fill="blue", outline="red", width=4)
draw.rectangle((60, 80, 180, 200), outline="red", width=4)
draw.rectangle((100, 100, 400, 400), outline="red",width=4)
draw.ellipse((100, 100, 400, 400), fill="red", outline="yellow", width=4)
draw.rectangle((400, 400, 700, 900), outline="red", width=4)
draw.arc((400, 400, 700, 900), start=0, end=270, fill="blue", width=4)
draw.chord((400, 400, 700, 900), start=0, end=180, outline="red", width=4)
font_path = "../msyh.ttc"
font = ImageFont.truetype(font_path, size=20)
draw.text(xy=(30, 60), text="这是中文字符", fill="red", font=font)
plt.imshow(image)
plt.show()
三、PIL总结
- PIL中工具包用在打开图片,后面dataset中
- 可以进行数据增强,如:加入模糊