python3调用oepncv检测人脸

python3调用oepncv检测人脸,检测结果发送后台服务器,可使用多线程
 
# -*- coding: utf-8 -*-
import cv2

 

import time
import multiprocessing as mp
import numpy as np
import os
import requests

 

respNum = 1
# showVideo = True
showVideo = False
camera_ips = [
"saveImg",
"xxx",
]

 

path = './opencvImg'

 

# 获取画面
def image_put(q, ip):
    cap = cv2.VideoCapture(ip)
    while True:
        q.put(cap.read()[1])
        q.get() if q.qsize() > 1 else time.sleep(0.01)

 

# 检测并显示画面
def image_get(q, window_name,lock,outImgList,showVideo):
    FONT = cv2.FONT_HERSHEY_PLAIN
    frame_id = 0
    time_start = time.time()

 

    frame_jum = 5
    frame_now = 0
    #告诉OpenCV使用人脸识别分类器
    classfier = cv2.CascadeClassifier("./haarcascade_frontalface_alt.xml")
    #识别出人脸后要画的边框的颜色,RGB格式
    color = (0, 255, 0)
    while True:
        frame = q.get()
        frame_now+=1
        if(frame_now>=frame_jum):
            frame_now = 0
        else:
            continue
        frame_id += frame_jum

 

        #将当前帧转换成灰度图像
        grey = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)                 
        
        #人脸检测,1.2和2分别为图片缩放比例和需要检测的有效点数
        faceRects = classfier.detectMultiScale(grey, scaleFactor = 1.2, minNeighbors = 3, minSize = (32, 32))
        if len(faceRects) > 0:            #大于0则检测到人脸                                   
            for faceRect in faceRects:  #单独框出每一张人脸
                x, y, w, h = faceRect
                names = str(time.time()).replace('.','')+'.jpg'
                path_img = os.path.join(path, names)
                outImg = frame[y:y+h,x:x+w]
                if(outImg is None):
                    continue
                cv2.imwrite(path_img,outImg)
                print('imwrite')        
                lock.acquire()
                outImgList.append(path_img)
                lock.release()
        if showVideo:
            cv2.namedWindow(window_name, flags=cv2.WINDOW_FREERATIO)
            if len(faceRects) > 0:            #大于0则检测到人脸                                   
                for faceRect in faceRects:  #单独框出每一张人脸
                    x, y, w, h = faceRect        
                    cv2.rectangle(frame, (x - 10, y - 10), (x + w + 10, y + h + 10), color, 2)
                    
            elapsed_time = time.time() - time_start
            fps = frame_id/elapsed_time
            cv2.putText(frame, "FPS: " + str(round(fps, 2)), (8, 30), FONT, 2, (0, 0, 0), 2)
            cv2.imshow(window_name, frame)
        cv2.waitKey(10)

 

# 保存检测出的人物
def saveImg(q,lock,outImgList,http):
    while True:
        lock.acquire()
        if outImgList:
            try:
                path_img=outImgList.pop()
                lock.release()
                imgs = open(path_img, 'rb')
                files = {'img': ('img.jpg', imgs)}
                r = requests.post(http, files=files)
                imgs.close()
                os.remove(path_img)
            except EOFError:
                print(EOFError)
                continue
        else:
            lock.release()
        time.sleep(0.5)

 

def run_multi_camera():
    h=''
    video=''
    with open("http.txt","r",encoding='utf-8') as f:
        h=f.readline()
    with open("video.txt","r",encoding='utf-8') as f:
        video=f.readline()
    camera_ip_l = camera_ips[0:respNum+1]
    mp.set_start_method(method='spawn')  # init
    queues = [mp.Queue(maxsize=4) for _ in camera_ip_l]

 

    processes = []
    lock = mp.Lock()
    outImgList=mp.Manager().list()
    for queue, camera_ip in zip(queues, camera_ip_l):
        if camera_ip=='saveImg':
            processes.append(mp.Process(target=saveImg, args=(queue,lock,outImgList,h)))
        else:
            processes.append(mp.Process(target=image_put, args=(queue, video)))
            processes.append(mp.Process(target=image_get, args=(queue, video,lock,outImgList,showVideo)))

 

    for process in processes:
        process.daemon = True
        process.start()
    for process in processes:
        process.join()

 

if __name__ == '__main__':
    # mp.freeze_support()
    run_multi_camera()
posted @ 2020-09-21 17:44  闪光123  阅读(216)  评论(0编辑  收藏  举报