OpenCV3 컴퓨터 시각Python 구현--cameo 프로젝트
managers.py
cameo.py
import cv2
import numpy
import time
class CaptureManager(object):
def __init__(self, capture, previewWindowManager = None, shouldMirrorPreview = False):
self.previewWindowManager = previewWindowManager
self.shouldMirrorPreview = shouldMirrorPreview
self._capture = capture
self._channel = 0
self._enteredFrame = False
self._frame = None
self._imageFilename = None
self._videoFilename = None
self._videoEncoding = None
self._viseoWriter = None
self._startTime = None
self._framesElapsed = float(0)
self._fpsEstimate = None
@property
def channel(self):
return self._channel
@channel.setter
def channel(self, value):
if self._channel != value:
self._channel = value
self._frame = None
@property
def frame(self):
if self._enteredFrame and self._frame is None:
_, self._frame = self._capture.retrieve()
return self._frame
@property
def isWritingImage(self):
return self._imageFilename is not None
@property
def isWritingVideo(self):
return self._videoFilename is not None
def enterFrame(self):
"""Caputure the next frame, if any"""
#But frist,check that any previous frame was exited
assert not self._enteredFrame, 'previous enterFrame() had no matching exitFrame()'
if self._capture is not None:
self._enteredFrame = self._capture.grab()
def exitFrame(self):
"""Draw to the window.Write to files.Release the frame"""
#Check whether any grabbed frame is retrievable
#the getter may retrieve and cache the frame
if self.frame is None:
self._enteredFrame = False
return
#Update the FPS estimate and related variable
if self._framesElapsed == 0:
self._startTime = time.time()
else:
timeElapsed = time.time() - self._startTime
self._fpsEstimate = self._framesElapsed / timeElapsed
self._framesElapsed += 1
#Draw to the window, if any
if self.previewWindowManager is not None:
if self.shouldMirrorPreview:
mirroredFrame = numpy.fliplr(self._frame).copy()
self.previewWindowManager.show(mirroredFrame)
else:
self.previewWindowManager.show(self._frame)
#Write to the image file, if any
if self.isWritingImage:
cv2.imwrite(self._imageFilename, self._frame)
self._imageFilename = None
#Write to video file ,if any
self._writeVideoFrame()
#Release the frame
self._frame = None
self._enteredFrame = False
def writeImage(self, filename):
"""Write the next exited frame to an image file"""
self._imageFilename = filename
def startWriteVideo(self, filename ,encoding = cv2.VideoWriter_fourcc('I','4','2','0')):
"""Start writing exited frame to a video file """
self._videoFilename = filename
self._videoEncoding = encoding
def stopWritingVideo(self):
"""Stop writing exited frames to a video file"""
self._videoFilename = None
self._videoEncoding = None
self._viseoWriter = None
def _writeVideoFrame(self):
if not self.isWritingVideo:
return
if self._viseoWriter is None:
fps = self._capture.get(cv2.CAP_PROP_FPS)
if fps == 0.0:
#The capture's FPS is unkown so use an estimate
if self._framesElapsed < 20:
#Wait until more frames elapse so that the eatimate is more stable
return
else:
fps = self._fpsEstimate
size = (int(self._capture.get(cv2.CAP_PROP_FRAME_WIDTH)),
int(self._capture.get(cv2.CAP_PROP_FRAME_HEIGHT)))
self._videoWriter = cv2.VideoWriter(self._videoFilename, self._videoEncoding, fps, size)
self._videoWriter.write(self._frame)
"""
,
"""
class WindowManager(object):
def __init__(self, windowName, keypressCallback = None):
self.keypressCallback = keypressCallback
self._windowName = windowName
self._isWindowCreated = False
@property
def isWindowCreated(self):
return self._isWindowCreated
def createWindow(self):
cv2.namedWindow(self._windowName)
self._iswindowCreated = True
def show(self, frame):
cv2.imshow(self._windowName, frame)
def destroyWindow(self):
cv2.destroyWindow(self._windowName)
self._isWindowCreated = False
def processEvents(self):
keycode = cv2.waitKey(1)
if self.keypressCallback is not None and keycode != -1:
#Discard any non-ASCII info encoded by GTK
keycode &= 0xFF
self.keypressCallback(keycode)
import cv2
from managers import WindowManager,CaptureManager
class Cameo(object):
def __init__(self):
self._windowManager = WindowManager('Cameo',self.onKeypress)
self._captureManager = CaptureManager(cv2.VideoCapture(0), self._windowManager, True)
def run(self):
"""Run the main loop"""
self._windowManager.createWindow()
while self._windowManager.isWindowCreated:
self._captureManager.enterFrame()
frame = self._captureManager.frame
#TODO: Filter the frame(Chapter 3)
self._captureManager.exitFrame()
self._windowManager.processEvents()
def onKeypress(self,keycode):
"""Handle a keypress
space -> Take a screenshot.
tab -> Start/stop recording a screencast.
escape-> Quit.
"""
if keycode == 32: #space
self._captureManager.writeImage('screenshot.png')
elif keycode == 9:#tab
if not self._captureManager.isWritingVideo:
self._captureManager.startWriteVideo('screencast.avi')
else:
self._captureManager.stopWritingVideo()
elif keycode == 27:#escape
self._windowManager.destroyWindow()
if __name__ == "__main__":
Cameo().run()
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.