当前位置:首页 » python教程 » 正文

Python生态圈图像格式转换问题(推荐)

看: 622次  时间:2021-01-28  分类 : python教程

在Python生态圈里,最常用的图像库是PIL——尽管已经被后来的pillow取代,但因为pillow的API几乎完全继承了PIL,所以大家还是约定俗成地称其为PIL。除PIL之外,越来越多的程序员习惯使用openCV来处理图像。另外,在GUI库中,也有各自定义的图像处理机制,比如wxPyton,定义了wx.Image做为图像处理类,定义了wx.Bitmap做为图像显示类。

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

在这里插入图片描述

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)
True

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)
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')

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数组转存图像

下面的代码,生成了一张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生态圈图像格式转换问题,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对python博客网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

标签:numpy  

<< 上一篇 下一篇 >>

搜索

推荐资源

  Powered By python教程网   鲁ICP备18013710号
python博客 - 小白学python最友好的网站!