2013-10-08 331 views
6

我试图使用opencv(cv2)将网络摄像头馈送流式传输到pygame表面对象。问题是颜色显示不正确。我认为这是类型转换,但是我很难理解pygame表面文档以了解它的期望。在pygame表面显示cv2.VideoCapture图像

此代码演示了什么我谈论

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

最终目标我已经是创造了DIY婚纱照一张小照片展位申请明年。我是编程新手,但是我已经设法将它们拼凑在一起。我也试图用VideoCapture完成这项工作,该工具输出一个PIL,我也无法使用表面对象。我想使用pygame表面,所以我可以动画和叠加倒计数文本,边框等。

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

frame=cv2.cvtColor(frame,cv2.COLOR_BGR2RGB) 

此外,转换为灰度时,下面的代码工作:

frame=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY) 
frame=cv2.cvtColor(frame,cv2.COLOR_GRAY2RGB) 

因此,功能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 
+3

我打算进来这里回答你的问题,因为它被列在未解答的问题上。发布并接受您的解决方案作为自我回答可能会更好,而不是在问题中提出。 – KobeJohn

回答

1

没有颜色错误在这里

frame=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY) 

所以对于普通屏幕颜色U简单的改变,要

frame=cv2.cvtColor(frame,cv2.COLOR_BGR2RGB) 

这会做,因为它为我的作品

0

我想你的代码,但我只得到一个图片不是电影,所以我复制

frame=getCamFrame(color,camera) 
screen=blitCamFrame(frame,screen) 
pygame.display.flip() 

成while循环,它的工作但随后的视频被翻转,修复它我getcamFrame功能,现在前夕 frame=numpy.rot90(frame)前加入cv2.flip(frame,1,frame) # mirror the image 一切正常。

对不起英文不好。