温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

一图看懂Python生态圈图像格式转换

发布时间:2020-07-30 14:21:31 来源:网络 阅读:342 作者:乐趣码农 栏目:编程语言

在Python生态圈里,最常用的图像库是PIL——尽管已经被后来的pillow取代,但因为pillow的API几乎完全继承了PIL,所以大家还是约定俗成地称其为PIL。除PIL之外,越来越多的程序员习惯使用openCV来处理图像。另外,在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')
  1. cv2读写图像文件

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

>>> import cv2
>>> im = cv2.imread(r'D:\CSDN\Python_Programming.png')
>>> cv2.imwrite(r'D:\CSDN\Python_Programming.jpg', im)
True
  1. 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)
True

下面的代码,用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')
  1. 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
  1. numpy数组转存图像

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

>>> 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生态圈图像格式转换

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI