pillow使用小技巧

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")

后续更新…

评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值