PIL(Python Image Library)是python的第三方图像处理库,但是由于其强大的功能与众多的使用人数,几乎已经被认为是python官方图像处理库了。 PIL历史悠久,原来是只支持python2.x的版本的,后来出现了移植到python3的库,pillow号称是`friendly fork for PIL`,其功能和PIL差不多,但是支持python3。另外,在GUI库中,也有各自定义的图像处理机制,比如wxPyton,定义了wx.Image做为图像处理类,定义了wx.Bitmap做为图像显示类。

下图梳理出了PIL读写图像文件、cv2读写图像文件、PIL对象和cv2对象互转、PIL对象和wx.Image对象互转、以及numpy数组转存图像的方法。掌握了这些方法,足可应对各种各样的图像处理需求了。

Python生态圈中图像格式的互相转换

1. PIL读写图像文件

下面的代码,演示了用PIL读取png格式的图像文件,剔除alpha通道后转存为jpg格式的图像文件。

from PIL import Image
im = Image.open(r'D:\CSDN\Python_Programming.png')
r,g,b,a = im.split()
im = Image.merge("RGB",(r,g,b))
im.save(r'D:\CSDN\Python_Programming.jpg')

2. cv2读写图像文件

下面的代码,演示了用cv2读取png格式的图像文件,转存为jpg格式的图像文件。

import cv2
im = cv2.imread(r'D:\CSDN\Python_Programming.png')
cv2.imwrite(r'D:\CSDN\Python_Programming.jpg', im)

3. PIL对象和cv2对象互转

cv2格式的对象,本质上就是numpy数组,也就是numpy.ndarray对象。只要能做到PIL对象和numpy数组互转,自然就实现了PIL对象和cv2对象互转。

下面的代码,演示了用PIL读取png格式的图像文件,转成numpy数组后保存为图像文件。

import cv2
from PIL import Image
import numpy as np
im_pil = Image.open(r'D:\CSDN\Python_Programming.png')
im_cv2 = np.array(im_pil)
cv2.imwrite(r'D:\CSDN\Python_Programming.jpg', im_cv2)

下面的代码,用cv2读取png格式的图像文件,转成PIL对象后保存为图像文件。

import cv2
from PIL import Image
im_cv2 = cv2.imread(r'D:\CSDN\Python_Programming.png')
im_pil = Image.fromarray(im_cv2)
im_pil.save(r'D:\CSDN\Python_Programming.jpg')

4. PIL对象和wx.Image对象互转

这是实现PIL对象和wx.Image对象互转的两个函数。

def PilImg2WxImg(pilImg):
    '''PIL的image转化为wxImage'''
    image = wx.EmptyImage(pilImg.size[0],pilImg.size[1])
    image.SetData(pilImg.convert("RGB").tostring())
    image.SetAlphaData(pilImg.convert("RGBA").tostring()[3::4])
    return image

def WxImg2PilImg(wxImg):
    '''wxImage转化为PIL的image'''
    pilImage = Image.new('RGB', (wxImg.GetWidth(), wxImg.GetHeight()))
    pilImage.fromstring(wxImg.GetData())

    if wxImg.HasAlpha():
        pilImage.convert( 'RGBA' )
        wxAlphaStr = wxImg.GetAlphaData()
        pilAlphaImage = Image.fromstring( 'L', (wxImg.GetWidth(), wxImg.GetHeight()), wxAlphaStr )
        pilImage.putalpha( pilAlphaImage )

    return pilImage

5. numpy数组转存图像

下面的代码,生成了一张515×512像素的随机图像。

from PIL import Image
import numpy as np
a = np.random.randint(0,256,((512,512,3)), dtype=np.uint8)
im_pil = Image.fromarray(a)
im_pil.save(r'D:\CSDN\random.jpg')
Python生态圈中图像格式的互相转换