本文介绍了使用BitmapBufferFormat_RGBA(Python)将wx位图转换为numpy的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用wxPython捕获窗口并使用cv2处理结果.由于wx具有将位图对象转换为简单RGB数组的内置函数,因此这似乎很简单.

I'm trying to capture a window with wxPython and process the result with cv2. This seems fairly straight forward as wx has a built in function to convert a bitmap object to a simple RGB array.

问题是我无法弄清楚语法.文档很少,我可以找到的一些示例已过时或不完整.

The problem is that I can't figure out the syntax. The documentation is sparse and the few examples I can find are either deprecated or incomplete.

基本上就是我想要的

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

为简单起见,这里没有指定窗口,只处理一个通道,但是应该让我了解我要做什么.

For simplicity this doesn't specify a window and only processes one channel but it should give an idea of what I'm attempting to do.

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

Whenever I try to run it like that using CopyFromBuffer it tells me that the bitmap stored in "b" isn't a readable buffer object yet if I pass it to SaveFile it writes out the image as expected.

不知道我在做什么错.

Not sure what I'm doing wrong here.

原来我做错了,试图使用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

推荐答案

一段时间没有这样做:但是OpenCV位图.为了从通用数组创建wx.Bitmap,您必须采用wx.Image路由.有关转换numpy数组的信息,请参见来自wxPython Wiki的条目(在中间).

Haven't done this for some while: But an OpenCV bitmap is essentially a numpy array. And for creating a wx.Bitmap from a generic array you'll have to take the wx.Image route. See the entry from the wxPython wiki (somewhere in the middle) regarding converting numpy arrays:

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

这篇关于使用BitmapBufferFormat_RGBA(Python)将wx位图转换为numpy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 20:16