下面是一個使用python Thread 實現多線程的例子,圖像的獲取和特徵點提取是獨立的線程。
import cv2
from threading import Thread
import copy
import numpy as np
class VideoGet:
"""
Class that continuously gets frames from a VideoCapture object
with a dedicated thread.
"""
def __init__(self, src=0):
self.stream = cv2.VideoCapture(src)
(self.grabbed, self.frame) = self.stream.read()
self.stopped = False
def start(self):
Thread(target=self.get, args=()).start()
return self
def get(self):
while not self.stopped:
if not self.grabbed:
self.stop()
else:
(self.grabbed, self.frame) = self.stream.read()
def stop(self):
self.stopped = True
class VideoShow:
"""
Class that continuously shows a frame using a dedicated thread.
"""
def __init__(self, frame=None):
self.frame = frame
self.stopped = False
def start(self):
Thread(target=self.show, args=()).start()
return self
def show(self):
out = self.frame
cv2.namedWindow("Fast Feature",cv2.WINDOW_NORMAL)
while not self.stopped:
gray = cv2.cvtColor(self.frame, cv2.COLOR_BGR2GRAY)
fast = cv2.FastFeatureDetector_create()
kps3 = fast.detect(gray, None)
cv2.drawKeypoints(gray, kps3, out, flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)
cv2.imshow("Fast Feature", out)
if cv2.waitKey(1) == ord("q"):
self.stopped = True
def stop(self):
self.stopped = True
def threadBoth(source=0):
video_getter = VideoGet(source).start()
video_shower = VideoShow(video_getter.frame).start()
while True:
if video_getter.stopped or video_shower.stopped:
video_shower.stop()
video_getter.stop()
break
frame = video_getter.frame
video_shower.frame = frame
if __name__ == "__main__":
threadBoth(0)
參考:https://github.com/nrsyed/computer-vision/tree/master/multithread