使用wxPython显示OpenCV iplimage数据结构
这是我现在的代码(语言是Python):
newFrameImage = cv.QueryFrame(webcam)
newFrameImageFile = cv.SaveImage("temp.jpg",newFrameImage)
wxImage = wx.Image("temp.jpg", wx.BITMAP_TYPE_ANY).ConvertToBitmap()
wx.StaticBitmap(self, -1, wxImage, (0,0), (wxImage.GetWidth(), wxImage.GetHeight()))
我想在一个wxPython窗口中显示从我的摄像头捕获的iplimage图像。问题是我不想先把图像存储到硬盘上。有没有办法把iplimage转换成其他图像格式,并且直接在内存中处理?有没有其他的解决办法?
我在其他语言中找到了一些“解决方案”,但我还是在这个问题上遇到了困难。
谢谢。
3 个回答
3
是的,这个问题虽然老旧,但我和大家一样,都是来这里寻找答案的。在尝试了多个版本的wx、numpy和opencv之后,我决定分享一个快速的解决方案,使用cv2和numpy图像。
下面是如何将OpenCV2中使用的NumPy数组风格的图像转换为位图,这样你就可以将其设置为wxPython中的显示元素(截至今天):
import wx, cv2
import numpy as np
# Start with a numpy array style image I'll call "source"
# convert the colorspace to RGB from cv2 standard BGR, ensure input is uint8
img = cv2.cvtColor(np.uint8(source), cv2.cv.CV_BGR2RGB)
# get the height and width of the source image for buffer construction
h, w = img.shape[:2]
# make a wx style bitmap using the buffer converter
wxbmp = wx.BitmapFromBuffer(w, h, img)
# Example of how to use this to set a static bitmap element called "bitmap_1"
self.bitmap_1.SetBitmap(wxbmp)
刚刚测试过,效果不错 :)
这个方法使用了wx自带的一个函数 BitmapFromBuffer,并利用了NumPy的缓冲区接口,所以我们只需要交换颜色,就能得到预期的顺序。
6
你需要做的事情是:
frame = cv.QueryFrame(self.cam) # Get the frame from the camera
cv.CvtColor(frame, frame, cv.CV_BGR2RGB) # Color correction
# if you don't do this your image will be greenish
wxImage = wx.EmptyImage(frame.width, frame.height) # If your camera doesn't give
# you the stream size, you might have to use (640, 480)
wxImage.SetData(frame.tostring()) # convert from cv.iplimage to wxImage
wx.StaticBitmap(self, -1, wxImage, (0,0),
(wxImage.GetWidth(), wxImage.GetHeight()))
我是通过查看Python OpenCV 食谱和wxPython 维基来搞明白怎么做的。
1
你可以使用 StringIO。
stream = cStringIO.StringIO(data)
wxImage = wx.ImageFromStream(stream)
你可以在 \wx\lib\embeddedimage.py 里查看更多细节。
这只是我个人的一点建议。