Основная обработка прервалась при использовании многопроцессорной обработки в python - PullRequest
0 голосов
/ 17 апреля 2020

Привет, парень! Многопроцессорная обработка - совершенно новый для меня материал. Так что некоторые проблемы неизбежны. Я использую многопроцессорную обработку для выполнения своего проекта распознавания, но каким-то образом основной проект - это прорыв. Моя переменная «ret» - это «False», это означает, что мой поток не может взять следующий кадр в Cap.read (). Мой код ниже, я прошу прощения за не показывать чистые сценарии, потому что мой проект имеет много других сценариев :). Tks для вашего ответа.

from imutils.video import VideoStream
import face_recognition
import argparse
import imutils
import pickle
import time
import cv2
import requests
import numpy as np
import time
from multiprocessing import Pool,Queue
import multiprocessing
import concurrent.futures 


ap = argparse.ArgumentParser()
ap.add_argument("-e", "--encodings", required=True,
    help="path to serialized db of facial encodings")
ap.add_argument("-o", "--output", type=str,
    help="path to output video")
ap.add_argument("-y", "--display", type=int, default=1,
    help="whether or not to display output frame to screen")
ap.add_argument("-d", "--detection-method", type=str, default="cnn",
    help="face detection model to use: either `hog` or `cnn`")
args = vars(ap.parse_args())


def The_biggest_box(boxes,rgb):
    rulers = np.array([])
    for (t,r,b,l) in boxes:
        ruler = (b-t)*(b-t)+(l-r)*(l-r)
        rulers = np.concatenate((rulers,[ruler]),axis=0)
    face_Queue.put(boxes[np.argmax(rulers,axis=0)])
    rbg_Queue.put(rgb)
    pass

def resultFaceFrameRE(data,rbg,face,name_q):
    if (name_q.full() == True):
        return
    encodings = face_recognition.face_encodings(rbg, [face])
    for encoding in encodings:
        matches = face_recognition.compare_faces(data["encodings"],encoding,tolerance= 0.5)
        name = "Unknown"

        if True in matches:
            matchedIdxs = [i for (i, b) in enumerate(matches) if b]
            counts = {}
            for i in matchedIdxs:
                name = data["names"][i]
                counts[name] = counts.get(name,0) + 1

            name = max(counts, key=counts.get)
        name_q.put(name)
def resultFaceRE(name_queue):
    counts = {}
    for i in range(10):
        name = Queue.get()
        counts[name] = counts.get(name,0) + 1
    name = max(counts, key=counts.get)
    print("Nguoi tim duoc la" + str(name))
    pass

if __name__ == "__main__":
    cap = cv2.VideoCapture(0)
    print("[INFO] loading encodings...")
    data = pickle.loads(open(args["encodings"], "rb").read())

    print("[INFO] starting video stream...")
    writer = None
    time.sleep(2.0)

    manager = multiprocessing.Manager()
    face_Queue = Queue()
    rbg_Queue = Queue()
    name_Queue = Queue(maxsize= 10)
    Value = multiprocessing.Value("i",0)

    name = []
    number_frame_re = 10
    count_frame = 10
    while True:
        start = time.perf_counter()

        ret,frame = cap.read()

        if ret == False:
            break

        rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        rgb = imutils.resize(frame, width=300)
        r = frame.shape[1] / float(rgb.shape[1])


        boxes = face_recognition.face_locations(rgb,
            model=args["detection_method"])

        if (len(name) == 0 and len(boxes) > 0):
            print(boxes)
            The_biggest_box(boxes,rgb)
            p = multiprocessing.Process(target=resultFaceFrameRE,args=(data,rbg_Queue.get(),face_Queue.get(),name_Queue))
            p.start()

        elif len(name) > 0:
            resultFaceRE(name_Queue)

        end = time.perf_counter()
        fps = 1/ (end-start)

        if args["display"] > 0:

            cv2.putText(frame,str(int(fps)),(30,30),cv2.FONT_HERSHEY_COMPLEX,2,(0,255,0),2)
            cv2.imshow("Frame", frame)
            key = cv2.waitKey(1) & 0xFF

            if key == ord("q"):
                break


    cv2.destroyAllWindows()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...