我正在树莓派上编写一些 Python 代码,以使用 openCV 从 RPi 相机抓取图像帧。如果代码位于简单的 while 循环中,则它可以毫无问题地实时运行。但是,我想将相机的操作放在一个线程中,以便相机可以在后台运行,并在需要时抓取帧。结果,我做了相当于下面的简单相机类的事情。
import cv2
class cam:
def __init__(self):
self.cap = cv2.VideoCapture(0)
#Create an empty image frame in case camera is not started before frame is used
self.frame = np.zeros([cam_mode.width,cam_mode.height,3],dtype=np.uint8)
#Objects for threading
self.cam_thread = Thread(target=self.camera_thread,args=())
self._lock = Lock()
def start_camera(self):
self.cam_thread.daemon = True
self.cam_thread.start()
def camera_thread(self):
if not self.is_running:
raise Exception("Camera is not running")
while self.cont:
#Lock so getting image is protected
with self._lock:
# get the image
status, frame = self.cap.read()
if …Run Code Online (Sandbox Code Playgroud)