【问题标题】:Converting wx bitmap to numpy using BitmapBufferFormat_RGBA (python)使用 BitmapBufferFormat_RGBA (python) 将 wx 位图转换为 numpy
【发布时间】:2016-01-04 21:19:31
【问题描述】:

我正在尝试使用 wxPython 捕获一个窗口并使用 cv2 处理结果。这看起来相当简单,因为 wx 有一个内置函数可以将位图对象转换为简单的 RGB 数组。

问题是我无法弄清楚语法。文档很少,我能找到的几个例子要么已弃用,要么不完整。

这基本上就是我想要的

app = wx.App(False)
img = some_RGBA_array #e.g. cv2.imread('some.jpg')
s = wx.ScreenDC()
w, h = s.Size.Get()
b = wx.EmptyBitmap(w, h)
m = wx.MemoryDCFromDC(s)
m.SelectObject(b)
m.Blit(0, 0, w, h, s, 0, 0)
m.SelectObject(wx.NullBitmap)
b.CopyFromBuffer(m, format=wx.BitmapBufferFormat_RGBA, stride=-1)#<----problem is here
img.matchSizeAndChannels(b)#<----placeholder psuedo
img[:,:,0] = np.where(img[:,:,0] >= 0, b[:,:,0], img[:,:,0])#<---copy a channel

为简单起见,这并没有指定一个窗口,只处理一个通道,但它应该让我知道我正在尝试做什么。

每当我尝试使用 CopyFromBuffer 像那样运行它时,它会告诉我存储在“b”中的位图不是可读的缓冲区对象,如果我将它传递给 SaveFile,它会按预期写出图像。

不知道我在这里做错了什么。

编辑:原来我做错的是尝试使用 BitmapBufferFormat_RGBA 将 wxBitmaps 转换为 cv2 rgb。根据下面的答案,我应该使用以下内容(其中“b”是位图):

wxB = wx.ImageFromBitmap(b)#input bitmap 
buf = wxB.GetDataBuffer() 
arr = np.frombuffer(buf, dtype='uint8',count=-1, offset=0)
img2 = np.reshape(arr, (h,w,3))#convert to classic rgb
img2 = cv2.cvtColor(img2, cv2.COLOR_RGB2BGR)#match colors to original image

【问题讨论】:

    标签: python arrays numpy bitmap wxpython


    【解决方案1】:

    已经有一段时间没有这样做了:但是一个 OpenCV 位图is essentially a numpy array。要从通用数组创建wx.Bitmap,您必须采用wx.Image 路线。关于转换 numpy 数组,请参阅 the entry from the wxPython wiki(中间某处):

    array = ... # the OpenCV image
    image = ... # wx.Image
    image.SetData(array.tostring())
    wxBitmap = image.ConvertToBitmap()       # OR:  wx.BitmapFromImage(image)
    

    编辑:反过来:

    import numpy
    img = wx.ImageFromBitmap(wxBitmap)
    buf = img.GetDataBuffer() # use img.GetAlphaBuffer() for alpha data
    arr = numpy.frombuffer(buf, dtype='uint8')
    
    # example numpy transformation
    arr[0::3] = 0 # turn off red
    arr[1::3] = 255 # turn on green
    

    【讨论】:

    • 这很好,但它倒退了。我需要将 wxBitmap 放入一个 numpy 数组中。
    • 查看编辑以将Bitmap 转换为数组,您的问题并不完全清楚。
    • 对于第二部分,'np.frombuffer...' 对我不起作用。我不得不使用'np.fromstring(...,dtype=np.uint8)'
    【解决方案2】:

    对于那些获得:

    wxpython AttributeError: 'memoryview' object has no attribute '__buffer__'
    

    解决方案是使用:

    arr = np.asarray(img.GetDataBuffer())
    img_data = np.copy(np.reshape(arr, (img.GetHeight(),img.GetWidth(),3)))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-18
      • 1970-01-01
      • 1970-01-01
      • 2016-02-10
      • 2018-09-05
      • 2018-12-19
      • 1970-01-01
      • 2016-12-24
      相关资源
      最近更新 更多