线程内部线程用于使用OpenCV保存图像

时间:2017-09-07 07:53:13

标签: python multithreading python-3.x opencv python-multithreading

我的情景: 当我在新线程中运行程序时,视频流从网络摄像头打开,每10秒我需要将图像保存到数据库。在数据库中保存图像我在新线程中工作。但是当我从网络摄像头中保存图像视频时,会冻结2-3秒。 2-3秒后视频流正常工作。我需要从视频流中删除冻结。

main.py

import sys
import os
from program import Program

def main():
    pro = Program()

if __name__ == "__main__":
    main()

program.py

import threading
import datetime
from mydb import MyDB
import time
import cv2
import os
import sys

class Program():
    def __init__(self):
        self.threadVideo =  None
        self.webcam = None
        self.frame = None
        self.rval = None
        self.saveImageToDB = MyDB()
        self.video()

    def video(self):
        self.threadVideo = threading.Thread(target=self.playVideo, args=())
        self.threadVideo.start()

    def playVideo(self):
        timeout = time.time() + 10
        self.webcam = cv2.VideoCapture(0)

        while True: 
            (self.rval, self.frame) = self.webcam.read()
            if time.time() > timeout:
                timeout = time.time() + 10
                thredSaveImage = threading.Thread(target=self.take())
                thredSaveImage.start()
            cv2.imshow('OpenCV', self.frame)
            key = cv2.waitKey(10)

    def take(self):
        ts = datetime.datetime.now()
        filename = "{}.jpg".format(ts.strftime("%Y-%m-%d_%H-%M-%S"))
        p = os.path.sep.join(("out", filename))
        cv2.imwrite(p, self.frame.copy())
        print("Image save local")
        self.saveImageToDB(p)

0 个答案:

没有答案