Python之PIL工具的Image笔记

本文介绍了Python中最流行的图片处理库PIL的基本使用方法,包括图片的打开、显示、转换、裁剪、旋转等常见操作,并提供了如何将PIL.Image数据转换为numpy.array数据的示例。

PIL应该算是Python下最流行的图片处理工具了

安装:

conda install Pillow

Image常用函数:

from PIL import Image       #导入

filename = '000002.jpg'

img = Image.open(filename)                         #打开图像
width,height = img.size                            #查看图像分辨率
if img.mode != 'RGB':
    img = img.convert('RGB')                       # size (H x W x 3) in RGB
img.load()                                         #读入图像

img_rsz = img.resize((256,256), Image.BICUBIC)     #缩放图像
img_new = Image.new('RGB',(512,512), (128,128,128))#创建分辨率512x512的图像,初始值为128,128,128
img_new.paste(img_rsz,(256,256))         #从坐标(256,256)处粘贴图像
img_crop = img_new.crop((0,0,384,384))   #剪切384x384图像
img_rotate = img_new.transpose(Image.FLIP_LEFT_RIGHT) #水平反转图像 FLIP_LEFT_RIGHT,FLIP_TOP_BOTTOM,ROTATE_90,ROTATE_180,ROTATE_270
img_rotate.show()    #显示图像  windows环境下bmp格式图像默认打开方式为画图工具,否则show图像会出现诡异的错误
img_rotate.save('test.bmp', 'bmp')                    #保存图像

在做深度学习模型时,经常用到Image读取图像数据,再在numpy的array数据方式进行训练模型,则会碰到PIL.Image数据转换到numpy.array数据格式

image_data = []
for file_name in os.listdir(dir_image):
    image = PIL.Image.open(file_name)
    image = image.convert('RGB')  #转换成RGB
    #image = image.convert('L')   #转换成luma
    image.load()  #将数据load到内存中
    image_data.append(np.asarray(image)#此操作将Image数据转换为np array数据
image_data = np.asarray(image_data)         #此操作将list数据转换为np array数据
#image = PIL.Image.fromarray(image)   #此操作将np array数据转换为Image数据
#image.save('aa.bmp')

重点参考:https://blog.csdn.net/qq_37816453/article/details/80434987
其它功能函数参考:https://blog.csdn.net/qunxingvip/article/details/45457745

参考:https://blog.csdn.net/icamera0/article/details/50843172
图像当前支持如下模式:

  • 1:1位像素,表示黑和白,但是存储的时候每个像素存储为8bit。
  • L:8位像素,表示黑和白。
  • P:8位像素,使用调色板映射到其他模式。
  • RGB:3x8位像素,为真彩色。
  • RGBA:4x8位像素,有透明通道的真彩色。
  • CMYK:4x8位像素,颜色分离。
  • YCbCr:3x8位像素,彩色视频格式。
  • I:32位整型像素。 F:32位浮点型像素。

split to RGB

from PIL import Image
pil_image = Image.fromarray(some_image)
red, green, blue = pil_image.split()
red.show()

transpose和transforms函数

参考:https://www.cnblogs.com/huipengbo/p/9774747.html

transpose有这么几种模式

  • FLIP_LEFT_RIGHT
  • FLIP_TOP_BOTTOM
  • ROTATE_90
  • ROTATE_180
  • ROTATE_270
  • TRANSPOSE
  • TRANSVERSE

其它参考

https://www.cnblogs.com/jyxbk/p/8535161.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阿尔发go

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值