Python3.7 中 wxImage 到 PIL 图像的转换,反之亦然

问题描述 投票:0回答:3

从Python2.7切换到Python3.7后,我在网上找到的转换方法不再起作用了。

我尝试了几个建议。每次PIL图像库都会出错:

...site-pacakges\PIL\Image.py",第 812 行,在 frombytes s=d.decode(data) 中 类型错误:参数 1 必须是只读字节类对象,而不是字节数组

def WxImageToPilImage1( myWxImage ):  
    """Convert wx.Image to PIL Image."""
    width, height = myWxImage.GetSize()
    data = myWxImage.GetData()

    red_image = Image.new("L", (width, height))
    red_image.frombytes(data[0::3])
    green_image = Image.new("L", (width, height))
    green_image.frombytes(data[1::3])
    blue_image = Image.new("L", (width, height))
    blue_image.frombytes(data[2::3])

    if myWxImage.HasAlpha():
        alpha_image = Image.new("L", (width, height))
        alpha_image.frombytes(myWxImage.GetAlphaData())
        myPilImage = Image.merge('RGBA', (red_image, green_image,    blue_image, alpha_image))
    else:
        myPilImage = Image.merge('RGB', (red_image, green_image, blue_image))
    return myPilImage

def WxImageToPilImage2( myWxImage ):
    myPilImage = Image.new( 'RGB', (myWxImage.GetWidth(), myWxImage.GetHeight()) )
    myPilImage.frombytes( myWxImage.GetData() )
    return myPilImage
wxpython python-imaging-library
3个回答
1
投票

我根本不使用

wxPython
,但这似乎有效:

import wx

app = wx.PySimpleApp()
wxim = wx.Image('start.png', wx.BITMAP_TYPE_ANY)

w = wxim.GetWidth()
h = wxim.GetHeight()
data = wxim.GetData()

red_image   = Image.frombuffer('L',(w,h),data[0::3])
green_image = Image.frombuffer('L',(w,h),data[1::3])
blue_image  = Image.frombuffer('L',(w,h),data[2::3])
myPilImage = Image.merge('RGB', (red_image, green_image, blue_image))

0
投票

您必须使用

myWxImage.GetDataBuffer()
而不是
GetData()

>>> type(img.GetData())
<type 'str'>
>>> type(img.GetDataBuffer())
<type 'buffer'>

0
投票

为了补充 Mark 的答案,如果您还需要 Alpha 通道数据(例如来自 wx.Clipboard):

import wx

app = wx.PySimpleApp()
wxim = wx.Image('start.png', wx.BITMAP_TYPE_ANY)

w = wxim.GetWidth()
h = wxim.GetHeight()
data = wxim.GetData()

red_image   = Image.frombuffer('L',(w,h),data[0::3])
green_image = Image.frombuffer('L',(w,h),data[1::3])
blue_image  = Image.frombuffer('L',(w,h),data[2::3])
myPilImage  = Image.merge('RGB', (red_image, green_image, blue_image))

# Add alpha channel info:
if wxim.HasAlpha():
    alpha_image = bytes(wxim.GetAlpha())
    myPilImage  = Image.merge('RGBA', (red_image, green_image, blue_image, alpha_image))
© www.soinside.com 2019 - 2024. All rights reserved.