Pillow模块之Image包的使用

1、PIL.Image.open(fp, mode=‘r’)

参数:
file – A filename (string) or a file object. The file object must implement read(), seek(), and tell() methods, and be opened in binary mode.
mode – The mode. If given, this argument must be “r”.
返回:
An Image object.

from PIL import Image
im = Image.open("0.jpg")

2、PIL.Image.fromarray(obj, mode=None)

从导出阵列接口的对象创建一个图像存储器(使用缓冲区协议)。如果obj不连续,则调用tobytes方法,并使用frombuffer()。
就是实现array到image的转换
np.asarray() 实现image到array的转换
参数:
obj – Object with array interface
mode – Mode to use (will be determined from type if None)
返回:
An image memory.用tobytes方法,并使用frombuffer()。

img = np.asarray(im)
type(img)
# numpy.ndarray

在这里插入图片描述

im = Image.fromarray(img)
im

在这里插入图片描述

3、Image.save(fp, format=None, **params)

将此图像保存在给定的文件名下。 如果未指定格式,则尽可能使用文件扩展名确定要使用的格式。
参数:
file – File name or file object.
format – 可选格式覆盖。 如果省略,则使用的格式由文件扩展名决定。 如果使用文件对象而不是文件名,则应始终使用此参数。
options – Extra parameters to the image writer.

返回: None

im.save("3.jpg",format="jpeg",quality = 95)

疑问: 发现保存之后的图片跟原图像的大小不一样了,但是查看属性发现长宽像素大小及DPI还是一样的,就很迷惑

4、Image.resize(size, resample=0)

返回此图像的调整大小的副本。注意这里不会改变原图的大小
参数:
size – 请求的大小(以像素为单位),为2元组:(宽度,高度)。

resample – 可选的重采样滤波器。
这可以是PIL.Image.NEAREST(使用最近的邻居)
PIL.Image.BILINEAR(在2x2环境中的线性插值)
PIL.Image.BICUBIC(在4x4环境中的三次样条插值)
PIL.Image. ANTIALIAS(高质量的下采样滤波器)。
如果省略,或者图像的模式为“ 1”或“ P”,则将其设置为PIL.Image.NEAREST。

返回: An Image object.

im_new = im.resize((416,416),resample=0)
num_new = np.asarray(im_new)
num_new.shape
# (416, 416, 3)

5、ImageDraw.Draw(image)

画矩形框

扫描二维码关注公众号,回复: 11938791 查看本文章
from PIL import ImageDraw
from PIL import Image, ImageFont
i = 7
image = Image.open(train_paths[i]) # 打开一张图片
draw = ImageDraw.Draw(image) # 在上面画画
labels = all_labels[i]
draw.rectangle([labels[0],labels[1],labels[2],labels[3]], outline=(255,0,0)) # [左上角x,左上角y,右下角x,右下角y],outline边框颜色
image.show() 

6、属性

1) PIL.Image.format

源文件的文件格式。 对于由库本身(通过工厂功能或通过在现有图像上运行方法)创建的图像,此属性设置为None。

im_new.format
# None

2) PIL.Image.mode

图像模式。 这是一个字符串,指定图像使用的像素格式。 典型值为“ 1”,“ L”,“ RGB”或“ CMYK”。

im_new.mode
# 'RGB'

3) PIL.Image.size

图片大小,以像素为单位。 大小以2元组(宽度,高度)给出。

im_new.size
# (416, 416)

猜你喜欢

转载自blog.csdn.net/Winds_Up/article/details/108760848