pillow比较实用的参考网站
中文参考:https://www.osgeo.cn/pillow/index.html
中文参考:https://pillow-cn.readthedocs.io/zh_CN/latest/
英文参考:https://pillow.readthedocs.io/en/stable/index.html
查看图像模式、尺寸和通道数
img = Image.open("./0001.png")
print("模式:", img.mode)
print("尺寸:", img.size)
print("通道数:", len(img.split()))
常用函数总结
image = Image.open("0024.jpg")
image.resize((100, 100)) # 缩放
image = image.convert("L") # 转灰度
b, g, r = image.split() # 通道分离
image = Image.merge("RGB", (g, b, r)) # 通道合并
PIL格式与numpy格式转换
image = Image.open("0024.jpg")
print(type(image))
image_arr = np.array(image)
print("image_arr: ", type(image_arr))
image_pil = Image.fromarray(image_arr)
print("image_pil: ", type(image_pil))
PIL读入图片格式是(宽,高,通道),cv读入图片的格式(高,宽,通道)
img_path = "1.jpg"
img1 = Image.open(img_path)
img2 = cv.imread(img_path , cv.IMREAD_UNCHANGED)
print(img1.size, img2.shape)
图像裁剪
def img_crop(image, location, height=100, width=100):
box = (location[0], location[1], height, width)
return image.crop(box)
image = Image.open("0024.jpg")
image = img_crop(image, (20, 10))
image.save("1111.jpg")
在图片中绘制矩形框
def draw_rectangle(image, location, width, height, color="red"):
draw = ImageDraw.Draw(image)
draw.rectangle([(location[0], location[1]), (location[0]+width, location[1]+height)], outline=color, width=2)
return image
img_path = "./JPEGImages/0001.jpg"
image = Image.open(img_path)
image = draw_rectangle(image, [50, 50], 500, 500, color="green")
image.save("./img.jpg")
window下使用PIL在图片上添加汉字
在windows系统下,字体文件位于C:\Windows\Fonts\文件夹下
from PIL import Image, ImageDraw, ImageFont
img = Image.open("0024.jpg")
draw = ImageDraw.Draw(img)
content = "小耳朵音乐!"
font = ImageFont.truetype('C:/Windows/Fonts/kaiu.ttf', 130)
draw.text((100, 300), content, font=font, fill="black")
img.save("imgimg.jpg")
后续更新…