Skip to content Skip to sidebar Skip to footer

Converting Cv2 Images To Pysdl2 Surfaces For Blitting To Screen

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

Solution 1:

Solved it!

#import necessary modulesimport 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)

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

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.

Solution 2:

this line may help you :

windowArray[:,:,0:3] = img.swapaxes(0,1)


#!python3import cv2
import sdl2
import sdl2.ext

defprocess_frame(img):
    # --- initialize
    sdl2.ext.init()
    window = sdl2.ext.Window("sdl",size=('width','height'))
    window.show()
    events = sdl2.ext.get_events()
    for event in events:
        if event.type == sdl2.SDL_QUIT:
            exit(0)
    # --- initialize
    windowArray = sdl2.ext.pixels3d(window.get_surface()) 

    # --- convert cv2 frame to sdl windowArray
    windowArray[:,:,0:3] = img.swapaxes(0,1)


vc = cv2.VideoCapture(0)     
while vc.isOpened():
    ret,frame = cap.read()
    if ret == True:
        process_frame(frame)
    else:
        break

Solution 3:

i do not have enough reputation to add comment, though its been long time ago, hope this can help someone,

you can add a flag for the window creation

window = sdl2.ext.Window("test", size=windowSize, flag=sdl2.SDL_WINDOW_SHOWN)

Post a Comment for "Converting Cv2 Images To Pysdl2 Surfaces For Blitting To Screen"