多进程截取海康相机视频帧存储(demo)

149 阅读1分钟

通过数据库查询ip,username, password 模块

import pymysql


class BaseSet():
    # 连接数据库基础参数
    def __init__(self):
        # 连接数据库
        self.conn = pymysql.connect(host='localhost'  # 连接名称,默认127.0.0.1
                                    , user='root'  ## 用户名
                                    , passwd='root'  # 密码
                                    , port=3306  # 端口,默认为3306
                                    , db='cam'  # 数据库名称
                                    , charset='utf8'  # 字符编码
                                    )
        self.cur = self.conn.cursor()  # 生成游标对象

        # Sql语句
        self.ConstructionSql = 'SELECT ip,username, password FROM cams'

    def GetCamIDInfo(self):
        try:
            self.cur.execute(self.ConstructionSql)  # 执行插入的sql语句
            return self.cur.fetchall()
        except:
            self.conn.commit()  # 提交到数据库执

多进程截取图像帧模块

import datetime
import multiprocessing
import time
from Config import BaseSet
import uuid
import cv2

def getInfolIST():
    Config = BaseSet()
    IPlIST = []
    usernamelIST = []
    passwordlIST = []
    for ip, username, password in Config.GetCamIDInfo():
        IPlIST.append(ip)
        usernamelIST.append(username)
        passwordlIST.append(password)
    return IPlIST, usernamelIST, passwordlIST


def SaveFrams(username, password, ip):
    save_imgs_path = "./imgs/"
    rtsp = "rtsp://%s:%s@%s:554/cam/realmonitor?channel=1&subtype=1" % (username, password, ip)
    cap = cv2.VideoCapture(rtsp)
    if cap.isOpened():
        ret, frame = cap.read()  # read_latest_frame() 替代 read()
        if ret:
            print("Can receive frame (stream start!). Starting ..")
            frame = cv2.resize(frame, (1920, 1080))  # 图像大小为1920, 1080
            cv2.imwrite(save_imgs_path + str(ip) +  str(uuid.uuid1()) + '.jpg', frame)
            cap.release()
        else:
            cap.release()


if __name__ == '__main__':
    IPlIST, usernamelIST, passwordlIST = getInfolIST()
    try:
        while True:
            time.sleep(1)
            p = multiprocessing.Pool(32)
            r_list = []
            for username, password, ip in zip(usernamelIST, passwordlIST, IPlIST):
                r_list.append(p.apply_async(SaveFrams, args=(username, password, ip)))
            p.close()
            for r in r_list:
                r.get()
    except KeyboardInterrupt:
        p.terminate()
        print('[-] main exit')
    p.join()