PIL Image

本文介绍如何使用Python的PIL库读取、分割、变换图像,并与NumPy数组进行转换。涵盖Image.open读取图像,im.crop进行图片分割,im.transpose实现图形变换,以及Image.fromarray和np.asarray用于图像与矩阵间的转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

from PIL import Image
import numpy as np


1. Image.open(fp, mode='r')

根据路径 fp 读取图片,这里默认是只读格式。

>>> p = '/home/hushch/图片/th.jpeg'
>>> im = Image.open(p)
>>> type(im)
<class 'PIL.JpegImagePlugin.JpegImageFile'>
>>> img = (np.asarray(im))
>>> img.shape
(168, 300, 3)

2. 对于Image obj的调用

1.im.crop(box=None)

图片分割,和torchvision.transforms类似:

>>> subim = im.crop(box=[0, 0, 128, 128])  # 设定图片分割的范围
>>> subim.show()  # 显示图片

2.im.save(fp)

保存图片到路径fp.

>>> subim.save(fp='/home/hushch/图片/screenshot/sub.jpeg')

3.im.transpose(method)

对图形变换,如flip, rotate, etc.

im.transpose(method=Image.FLIP_LEFT_RIGHT)  # 左右翻转

3.格式变化,img <--> numpy

参看 https://mp.youkuaiyun.com/postedit/86089514

Image.fromarray(obj, mode=None) 从矩阵到图片

np.asarray(im)  图片到矩阵

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值