当前位置:网站首页>Chapter 2 processing files, cameras and GUI Cameo applications
Chapter 2 processing files, cameras and GUI Cameo applications
2022-06-28 18:27:00 【So come on】
managers02.py
""" *_* coding: UTF-8 *_* @author: xiaohao @time: 2022/6/25 0:06 @Site: Qinhuangdao, China @file:managers02.py @software: PyCharm @CSDN: So come on """
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._videoWriter = None
self._startTime = None
self._framesElapsed = int(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):
''' Determine whether the image is captured successfully , If it works , Import the data of the successful picture into _frame In this variable , The way to do it is retrieve(). :return: '''
if self._enteredFrame and self._frame is None:
# As of OpenCV 3.0, VideoCapture.retrieve() no longer supports the channel argument.
# _, self._frame = self._capture.retrieve(channel = self.channel)
_, 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
# If _capture Not empty words , Capture a frame in the camera .
# _capture refer to CaptureManager Class instance _captureManager Open the camera capture.
def enterFrame(self):
"""Capture the next frame, if any."""
# But first, check that any previous frame was exited.
# assert An assertion is a statement that its Boolean value must be true , If an exception occurs, the expression is false
assert not self._enteredFrame, \
'previous enterFrame() had no matching exitFrame()'
if self._capture is not None:
self._enteredFrame = self._capture.grab()
# Calculate the number of frames per second of the camera , And put the frames captured by the camera into the window cameo It shows that .
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 variables.
# Calculation FPS( Frames per second ), And estimates are updated in real time . This time is recorded to _fpsEstimate in .
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.
# Display the captured frame image on the screen window , If you choose mirror , First flip the picture , Then it will be displayed on the window .
# Every time the loop updates the window , In this way, we put pictures frame by frame , It's going to be fast , Fast words will achieve the effect of video .
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.
# Determine whether the space bar is pressed , Just press it just _enterFrame The captured frame data is saved to the hard disk .
# If there is no screenshot , Just skip. .
if self.isWritingImage:
cv2.imwrite(self._imageFilename, self._frame)
self._imageFilename = None
# Write to the video file, if any.
# Judge if it is pressed TAB, Just press it just _enterFrame The captured frame data is saved to the hard disk ,
# And then every time we cycle, we put _enterFrame Save up , Until you press TAB key , No longer save .
# In this way, many frames of pictures will be put into one for avi File format , To put it bluntly, it is a video .
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 startWritingVideo(
self, filename,
encoding=cv2.VideoWriter_fourcc('M', 'J', 'P', 'G')):
"""Start writing exited frames 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._videoWriter = None
def _writeVideoFrame(self):
if not self.isWritingVideo:
return
if self._videoWriter is None:
fps = self._capture.get(cv2.CAP_PROP_FPS)
if fps <= 0.0:
# The capture's FPS is unknown so use an estimate.
if self._framesElapsed < 20:
# Wait until more frames elapse so that the
# estimate 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
# First determine whether the window has been created .
def createWindow(self):
# hold _windowName Name passed in , Namely cameo write in ,
# And then put _isWindowCreated Attribute to True.
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
# Monitor the keyboard , Let's see if it presses the buttons it said before ,
# If you press , Just do the right thing .
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)
cameo02.py
""" *_* coding: UTF-8 *_* @author: xiaohao @time: 2022/6/25 1:06 @Site: Qinhuangdao, China @file:cameo02.py @software: PyCharm @CSDN: So come on """
import cv2
from managers02 import WindowManager, CaptureManager
class Cameo(object):
def __init__(self):
# Create a WindowManager Example , The name of the window is Cameo,
# Accept keyboard keys ( That is video or screenshot ) The monitoring function of is called onKeypress
self._windowManager = WindowManager('Cameo',
self.onKeypress)
# Create a CaptureManager Example .
# The first parameter is to acquire the camera , Only one camera bracket is 0, If more than one , Enter the label number of the camera .
# The second parameter is to put WindowsManager example _windowManager Pass to CaptureManager Example _captureManager.
# The third parameter is whether to mirror ,True It's a mirror image , Because we look in the mirror , The people in the mirror are the opposite , So it should be flipped horizontally , Straighten it .
self._captureManager = CaptureManager(
cv2.VideoCapture(0), self._windowManager, True)
def run(self):
"""Run the main loop."""
# If you don't have a good window , Just exit the program
self._windowManager.createWindow()
# Every cycle updates the window , It is equivalent to putting pictures frame by frame , fast , Video effect will be achieved if it is fast .
while self._windowManager.isWindowCreated:
# Grab
self._captureManager.enterFrame()
# Pass the image of the above captured frame into the variable frame in .
frame = self._captureManager.frame
if frame is not None:
# TODO: Filter the frame (Chapter 3).
pass
self._captureManager.exitFrame()
self._windowManager.processEvents()
# Monitor the keyboard at the last sentence of the loop statement , When executing this sentence ,
# If the keyboard presses the key or does not press the key , Will generate a data ,
# No press yes - 1, When you press it, it is a ASCII code , Then convert this code into GTK Format ,
# Then incoming keypressCallback in , That is to say, the introduction of Windowsmanager Functions in class
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.startWritingVideo(
'screencast.avi')
else:
self._captureManager.stopWritingVideo()
elif keycode == 27: # escape
self._windowManager.destroyWindow()
if __name__ == "__main__":
# Initialize first Cameo This class , And then execute run Method .
Cameo().run()

边栏推荐
- 问下 flink sql cdc. 能同步多张表然后sink到一份表中么 同步的表通过 joi
- GCC getting started manual
- Does DMS SQL result set export support parameter transfer?
- 想请教股票开户找人办比较方便么?网上开户安全么?
- The MySQL installed in Alibaba cloud server is version 8. Is it because the MySQL driver version of dataworks does not support it? Now mention
- Learning notes: how to time 10ms for 51 single chip microcomputer (STC89C52)
- 数据源只能连阿里云的云数据库吗?阿里云服务器里装的数据库连不上嘛?
- moco挡板制作及运行成功
- Analysis of response parsing process of SAP ui5 batch request
- OneFlow源码解析:算子签名的自动推断
猜你喜欢

Unity about oculus quest2 basic development based on XR interaction toolkit 003- capture function - making a VR bowling game

halcon知识:矩阵专题【01】

Nuc980 heartbeat light

Kubeadm create kubernetes cluster
![抓包整理外篇fiddler————了解工具栏[一]](/img/f4/fa909f30c0097fb77cea10eb0d3109.png)
抓包整理外篇fiddler————了解工具栏[一]

Mycat+ sub database and sub table

Small program graduation design based on wechat real estate intermediary house viewing appointment small program graduation design opening report function reference

Redis6笔记04 主从复制,集群,应用问题,Redis6新功能

第2章 处理文件、摄像头和图形用户界面cameo应用

OneFlow源码解析:算子签名的自动推断
随机推荐
请教大佬们,oracle cdc的NUMBER类型,打印出来为什么变成字符串了呢,怎么转换回去?
Nuc980 heartbeat light
数字化转型中,企业设备管理会出现什么问题?JNPF或将是“最优解”
Does the dataworks SQL script support if else judgment of statement blocks
【软件测试】2022年普通高等学校招生全国统一考试
Analysis of response parsing process of SAP ui5 batch request
The fourth largest operator cannot be a "catfish"
Common DOS commands
【译】clickhouse 22.4和22.5核心特性一览
使用Pega进行一个简单的RPA程序开发
Unity about oculus quest2 basic development based on XR interaction toolkit 003- capture function - making a VR bowling game
Unity about oculus quest2 developing 002-ui interaction based on XR interaction Toolkit
Finally quit, full-time UE
你们采集oracle数据,数据延迟大约有多少啊?我这边就维持在3秒了,降不下去了。有没有个业内参考啊
PCB线路板布局和布线都有哪些设计要求?
DNSLog注入
select/poll/epoll
use. NETCORE's own background job, which simply simulates producers and consumers' processing of request response data in and out of the queue
2022 chemical automation control instrument test simulation 100 questions simulation test platform operation
EasyExcel 学习笔记