同时从摄像头传入四个视频流并识别视频人脸(使用多线程)

import numpy as np
import cv2
import multiprocessing
from multiprocessing import Queue
import time

CAMERA_COUNT = 4  # 摄像头个数
url = "rtsp://admin:[email protected]/Streaming/Channels/1"  # 外置摄像头地址及密码
url1 = "rtsp://admin:[email protected]/Streaming/Channels/1"
url2 = "rtsp://admin:[email protected]/Streaming/Channels/1"
url3 = "rtsp://admin:[email protected]/Streaming/Channels/1"
# 不同进程不能共享内存,定义队列进行进程通信
q = Queue()


def video_read(id):
    camera_id = id
    # 使用笔记本自带的摄像头
    if camera_id == 0:
        cap = cv2.VideoCapture(url)
    # 使用外置的摄像头
    if camera_id == 1:
        cap = cv2.VideoCapture(url1)
    # 使用外置的摄像头1
    if camera_id == 2:
        cap = cv2.VideoCapture(url2)
    # 使用外置的摄像头2
    if camera_id == 3:
        cap = cv2.VideoCapture("1.mp4")

    # 获取每一个视频的尺寸
    width = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)))
    height = (int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
    print(width, height)
    faceCascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
    while (cap.isOpened()):
        ret, frame = cap.read()
        if ret == True:
            gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)  # 将每一帧图片转为灰色以便接下来处理
            faces = faceCascade.detectMultiScale(
                gray,
                scaleFactor=1.1,
                minNeighbors=5,
                minSize=(30, 30),
                flags=cv2.CASCADE_SCALE_IMAGE
            )
            for (x, y, w, h) in faces:
                cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)

            frame = cv2.resize(frame, (640, 480), interpolation=cv2.INTER_CUBIC)
            isEmpty = q.empty()
            # print(isEmpty)
            if isEmpty == True:
                # print('队列中无数据!')
                # q.put(frame)
                time.sleep(0.001)
            else:
                time.sleep(0.002)

            cv2.imshow('videoprossing' + str(id), frame)
            key = cv2.waitKey(10)
            if int(key) == 113:
                break
        else:
            video_read(id)
    cap.release()
    cv2.destroyAllWindows()


# ---------------------------------------------------------------------------------
if __name__ == '__main__':
    print("主进程开始启动!")
    for index in range(CAMERA_COUNT):
        print('摄像头的索引号是:', index)
        p = multiprocessing.Process(target=video_read, args=(index,))
        p.start()
    print('程序结束!')

猜你喜欢

转载自blog.csdn.net/liaoqingjian/article/details/109110790