Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
152 views
in Technique[技术] by (71.8m points)

python - frame not responding with face_recognition library

I'm using anaconda environment with python 3.7.7 everything was working properly, but I had to format my laptop and I installed the following libraries the same way I did before and they were installed, but when i run my code it's showing that the frame is not responding when the camera starts, opencv imshow is working, i think the problem is with the face recognition library.

the libraries i installed

conda install -c conda-forge opencv
conda install -c conda-forge dlib
pip install face_recognition
pip install imutils

and my code is:

from imutils.video import VideoStream
import face_recognition
import argparse
import imutils
import pickle
import time
import cv2
import numpy as np
import os

args = {
    "encodings": "models/encodings/encodings.pickle",
    "output": "output/"+outputFileName(),
    "display": 1,
    "detection_method": "cnn",
    "confidence": 0.5,
    "prototxt": "models/ssd/MobileNetSSD_deploy.prototxt",
    "model": 'models/ssd/MobileNetSSD_deploy.caffemodel',
    "use_gpu": 0
}


# load the known faces and embeddings
data = pickle.loads(open(args["encodings"], "rb").read())

vs = VideoStream(src=0).start()

writer = None
time.sleep(2.0)

fps = FPS().start()

names2=[]
t11=[]

no_names_pf=10



i1=10
vidsave=False


# loop over frames from the video file stream
while True:
    frame = vs.read()
    
    rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    rgb = imutils.resize(frame, width=750)
    r = frame.shape[1] / float(rgb.shape[1])

    # detect the (x, y)-coordinates of the bounding boxes
    # corresponding to each face in the input frame, then compute
    # the facial embeddings for each face
    boxes = face_recognition.face_locations(rgb,
        model=args["detection_method"])
    encodings = face_recognition.face_encodings(rgb, boxes)
    names = []

    # loop over the facial embeddings
    for encoding in encodings:
        # attempt to match each face in the input image to our known
        # encodings
        matches = face_recognition.compare_faces(data["encodings"],
            encoding)
        name = "Unknown"

        # check to see if we have found a match
        if True in matches:
            # find the indexes of all matched faces then initialize a
            # dictionary to count the total number of times each face
            # was matched
            matchedIdxs = [i for (i, b) in enumerate(matches) if b]
            counts = {}

            # loop over the matched indexes and maintain a count for
            # each recognized face face
            for i in matchedIdxs:
                name = data["names"][i]
                counts[name] = counts.get(name, 0) + 1

            # determine the recognized face with the largest number
            # of votes (note: in the event of an unlikely tie Python
            # will select first entry in the dictionary)
            name = max(counts, key=counts.get)
        
        # update the list of names
        names.append(name)
        print(names)
        
        #___new code_____
        names2.append(name)
    
    #need to mod (capable of r of 1 person at the same time)
    if len(names2)>no_names_pf:
        
        confbool1=False
        for i in range(no_names_pf):
            i+=1
            i=i*-1
            if names2[-1] == names2[i-1]:
                confbool1=True
            else:
                confbool1=False
                break
        if confbool1==True:
            t11.append(name+'$$'+
            str(datetime.datetime.now().strftime("%d-%m-%Y %H:%M:%S")))
                
            if t11:
                print(t11[-1])
                
      

    
    
    #td01=frame[0:-2]
    frameCopy=frame.copy()
    
    # loop over the recognized faces
    for ((top, right, bottom, left), name) in zip(boxes, names):
        # rescale the face coordinates
        top = int(top * r)
        right = int(right * r)
        bottom = int(bottom * r)
        left = int(left * r)

        # draw the predicted face name on the image
        cv2.rectangle(frame, (left, top), (right, bottom),
            (0, 255, 0), 2)
        y0 = top - 15 if top - 15 > 15 else top + 15
        cv2.putText(frame, name, (left, y0), cv2.FONT_HERSHEY_SIMPLEX,
            0.75, (0, 255, 0), 2)
        
    

    # if the video writer is None *AND* we are supposed to write
    # the output video to disk initialize the writer
    
    
    
    if writer is None and args["output"] is not None:
        fourcc = cv2.VideoWriter_fourcc(*"MJPG")
        writer = cv2.VideoWriter(args["output"], fourcc, 20,
            (frame.shape[1], frame.shape[0]), True)

  
    
   # if i1%10 == 0 :
    # print(vidsave)
    # print(label)
    # print('person' in label)
    

    #i1=i1+1
    vidsave=False

    # check to see if we are supposed to display the output frame to
    # the screen
    if args["display"] > 0:
        cv2.imshow("Frame", frame)
        key = cv2.waitKey(1) & 0xFF

        # if the `q` key was pressed, break from the loop
        if key == ord("q"):
            break

    #__________________________________________
    
    fps.update()

# stop the timer and display FPS information
fps.stop()
print("[INFO] elasped time: {:.2f}".format(fps.elapsed()))
print("[INFO] approx. FPS: {:.2f}".format(fps.fps()))



cv2.destroyAllWindows()
vs.stop()

if writer is not None:
    writer.release()
    
#___________________________________________________________________

# report handeling







appendtxt("output/"+datetime.datetime.now()
          .strftime("%d-%m-%Y")+" report.txt",'a
')

    
    
    
this_year=datetime.datetime.now().strftime("%Y")
this_month=datetime.datetime.now().strftime("%m")
this_day=datetime.datetime.now().strftime("%d")

# if not os.path.exists('output/'+this_year):
#     os.makedirs('output/'+this_year)

# if not os.path.exists('output/'+this_year+'/'+this_month):
#     os.makedirs('output/'+this_year+'/'+this_month)

# if not os.path.exists('output/'+this_year+'/'+this_month+'/'+this_day):
#     os.makedirs('output/'+this_year+'/'+this_month+'/'+this_day)





#image = cv2.imread("C:/Users/anwar/Desktop/lllsky.png")

# cv2.imshow("Image", frame)
# cv2.imwrite('output/aa.jpg', frame)
# cv2.waitKey(0)

# fc = frameCopy[top-50:bottom+50 , left-50:right+50 ]
# cv2.imshow("fc", fc)
# cv2.waitKey(0)

# cv2.destroyAllWindows()


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...