gpt4 book ai didi

python - 将 cv2 图像转换为 PySDL2 表面以传输到屏幕

转载 作者:太空宇宙 更新时间:2023-11-03 22:14:42 25 4
gpt4 key购买 nike

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

#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 窗口永远不会出现。

关于python - 将 cv2 图像转换为 PySDL2 表面以传输到屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18434348/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com