在Pygame表面内显示cv2.VideoCapture图像

Ada*_*lly 6 python webcam opencv pygame

我正在尝试使用opencv(cv2)将网络摄像头源流式传输到pygame表面对象中.问题是颜色没有正确显示.我认为这是类型转换,但我无法理解pygame表面文档以了解它的期望.

这段代码演示了我在说什么

import pygame
from pygame.locals import *
import cv2
import numpy

color=False#True#False
camera_index = 0
camera=cv2.VideoCapture(camera_index)
camera.set(3,640)
camera.set(4,480)

#This shows an image the way it should be
cv2.namedWindow("w1",cv2.CV_WINDOW_AUTOSIZE)
retval,frame=camera.read()
if not color:
    frame=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
cv2.flip(frame,1,frame)#mirror the image
cv2.imshow("w1",frame)

#This shows an image weirdly...
screen_width, screen_height = 640, 480
screen=pygame.display.set_mode((screen_width,screen_height))

def getCamFrame(color,camera):
    retval,frame=camera.read()
    if not color:
        frame=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
    frame=numpy.rot90(frame)
    frame=pygame.surfarray.make_surface(frame) #I think the color error lies in this line?
    return frame

def blitCamFrame(frame,screen):
    screen.blit(frame,(0,0))
    return screen

screen.fill(0) #set pygame screen to black
frame=getCamFrame(color,camera)
screen=blitCamFrame(frame,screen)
pygame.display.flip()

running=True
while running:
    for event in pygame.event.get(): #process events since last loop cycle
        if event.type == KEYDOWN:
            running=False
pygame.quit()
cv2.destroyAllWindows()
Run Code Online (Sandbox Code Playgroud)

我的最终目标是为明年的DIY婚礼创建一个小型照相亭应用程序.我是编程新手,但我已经设法将它拼凑在一起.我也试图用VideoCapture来完成这个,它输出一个PIL,我也无法使用表面对象.我想使用pygame表面,所以我可以设置动画和叠加倒计时文本,边框等.

更新:问题是cv2函数camera.read()返回一个BGR图像,但pygame.surfarray需要一个RGB图像.这是用线固定的

frame=cv2.cvtColor(frame,cv2.COLOR_BGR2RGB)
Run Code Online (Sandbox Code Playgroud)

此外,转换为灰度时,以下代码有效:

frame=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
frame=cv2.cvtColor(frame,cv2.COLOR_GRAY2RGB)
Run Code Online (Sandbox Code Playgroud)

所以,函数getCamFrame现在应该是

def getCamFrame(color,camera):
    retval,frame=camera.read()
    frame=cv2.cvtColor(frame,cv2.COLOR_BGR2RGB)
    if not color:
        frame=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
        frame=cv2.cvtColor(frame,cv2.COLOR_GRAY2RGB)
    frame=numpy.rot90(frame)
    frame=pygame.surfarray.make_surface(frame)
return frame
Run Code Online (Sandbox Code Playgroud)

Tra*_*mer 2

不,颜色错误就在这里

frame=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
Run Code Online (Sandbox Code Playgroud)

所以对于正常的屏幕颜色你只需将其更改为

frame=cv2.cvtColor(frame,cv2.COLOR_BGR2RGB)
Run Code Online (Sandbox Code Playgroud)

那就行了,因为它对我有用