2013-10-08 334 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 一切正常。

對不起英文不好。