将cv2图像转换为PySDL2曲面以使其闪烁到屏幕 [英] Converting cv2 images to PySDL2 surfaces for blitting to screen

查看:126
本文介绍了将cv2图像转换为PySDL2曲面以使其闪烁到屏幕的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用新的PySDL2软件包,尝试将其与我现有的OpenCV代码连接.我想通过cv2 python界面从摄像头捕获图像到OpenCV,并使用PySDL2在屏幕上的窗口中显示它.我想我想出了如何将cv2图像格式正确转换为PySDL2表面,但是在下面的代码结尾,我得到的只是一个黑色窗口.任何关于我走到哪里的指示都将不胜感激!

I'm using the new PySDL2 package, trying to interface it with my existing OpenCV code. I want to take an image captured from a webcam via the cv2 python interface to OpenCV and use PySDL2 to show it in a window on screen. I think I figured out how to convert the cv2 image format to a PySDL2 surface properly, but at the end of the code below, all I get is a black window. Any pointers on where I have gone awry would be greatly appreciated!

#grab a frame from a webcam
import cv2
vc = cv2.VideoCapture(0)
junk,image = vc.read()

#convert image to sdl format (?)
import sdl2
sbuf = image.tostring()
simage = sdl2.SDL_CreateRGBSurfaceFrom(sbuf,image.shape[0],image.shape[1],24,3*image.shape[0],sdl2.SDL_PIXELFORMAT_BGRA8888,0xff0000, 0x00ff00, 0x0000ff, 0)

#create a window
sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO)
windowSize = (640,480)
window = sdl2.SDL_CreateWindow(b"Hello World",sdl2.SDL_WINDOWPOS_CENTERED, sdl2.SDL_WINDOWPOS_CENTERED,windowSize[0], windowSize[1], sdl2.SDL_WINDOW_SHOWN)
windowSurface = sdl2.SDL_GetWindowSurface(window)

#try to blit the sdl-formatted image to the window
sdl2.SDL_BlitSurface(simage,None,windowSurface,None)
sdl2.SDL_UpdateWindowSurface(window)
sdl2.SDL_FreeSurface(simage)

# pump events to get the window to show and update
while True:
    sdl2.SDL_PumpEvents()

推荐答案

解决了!

#import necessary modules
import cv2
import sdl2
import sdl2.ext
import numpy

windowSize = (640,480)

#initialize the camera
vc = cv2.VideoCapture(0)
vc.set(cv2.cv.CV_CAP_PROP_FRAME_WIDTH, windowSize[0])
vc.set(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT, windowSize[1])

#grab and show a first frame from the camera
junk,image = vc.read()
cv2.imshow('0',image)

#initialize sdl2
sdl2.ext.init()
window = sdl2.ext.Window("test", size=windowSize)
window.show()
windowSurf = sdl2.SDL_GetWindowSurface(window.window)
windowArray = sdl2.ext.pixels3d(windowSurf.contents)

while True: #keep reading to have a live feed from the cam
    junk,image = vc.read()
    image = numpy.insert(image,3,255,axis=2) #add alpha
    image = numpy.rot90(image) #rotate dims
    numpy.copyto(windowArray, image)
    window.refresh()

我不确定为什么必须使用cv2.imshow从摄像机显示第一帧,但是如果没有这一部分,则不会出现sdl2窗口.

I'm not sure why showing a first frame from the camera using cv2.imshow is necessary, but without that part, the sdl2 window never appears.

这篇关于将cv2图像转换为PySDL2曲面以使其闪烁到屏幕的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆