2013-08-25 51 views
1

我正在使用新的PySDL2軟件包,試圖將其與我現有的OpenCV代碼連接起來。我想將通過cv2 python接口從網絡攝像頭捕獲的圖像傳輸到OpenCV,並使用PySDL2將其顯示在屏幕上的窗口中。我想我想出瞭如何正確地將cv2圖像格式轉換爲PySDL2表面,但是在下面的代碼結尾處,我得到的只是一個黑色窗口。任何指向我錯誤的地方將不勝感激!將cv2圖像轉換爲PySDL2表面以進行blitting到屏幕

#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() 

回答

2

解決了!

#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窗口。

相關問題