Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

openCV: Error when Acessing IP Camera using rtsp in Python

Imports

import face_recognition
import os
import cv2
import pickle
import time
import smtplib
import dotenv

from datetime import date

Program Varribles and print statments

dotenv.load_dotenv()
KNOWN_FACES_DIR = 'known_faces'
FACES_DIR = "Faces"
# UNKNOWN_FACES_DIR = 'unknown_faces'
TOLERANCE = 0.7
FRAME_THICKNESS = 3
FONT_THICKNESS = 2
MODEL = 'cnn' 
print("Getting Video Feed...")
video_stream = cv2.VideoCapture(f"rtsp://{os.getenv('USERNAME')}: 
{os.getenv('PASSWORD_')}@{os.getenv('IP')}:{os.getenv('PORT')}/{os.getenv('NUM')}")
print("Video Feed Accessed...")

Loading Known Face Encodings

print('Loading known faces...')
known_faces = []
known_names = []


t = time.localtime()
system_time = time.strftime("%I:%M:%S", t)

try:
   os.mkdir(f"Logs/{str(date.today())}")
except FileExistsError:
    pass

for name in os.listdir(KNOWN_FACES_DIR):

# Next we load every file of faces of known person
for filename in os.listdir(f'{KNOWN_FACES_DIR}/{name}'):
    encoding = pickle.load(open(f'{KNOWN_FACES_DIR}/{name}/{filename}', 'rb'))
    known_faces.append(encoding)
    known_names.append(int(name))

Creating ID

if len(known_names) > 0:
next_id = max(known_names) + 1

else:
next_id = 0

 counter = 0

Looking for Unknown Faces

print('Processing unknown faces...')
while True:

ret, image = video_stream.read()
counter = counter + 1
locations = face_recognition.face_locations(image, model=MODEL)

encodings = face_recognition.face_encodings(image, locations)



print(f'found {len(encodings)} face(s)')
for face_encoding, face_location in zip(encodings, locations):

    # We use compare_faces (but might use face_distance as well)
    # Returns array of True/False values in order of passed known_faces
    results = face_recognition.compare_faces(known_faces, face_encoding, TOLERANCE)

    # Since order is being preserved, we check if any face was found then grab index
    # then label (name) of first matching known face withing a tolerance
    match = None
    if True in results:  # If at least one is true, get a name of first of found labels
        match = known_names[results.index(True)]
        print(f'Located ID {match} - {results}')
        pickle.dump(face_encoding, open(f"{KNOWN_FACES_DIR}/{match}/{match}-{system_time.replace(':', '_')}.pkl",
                                        'wb'))
        server.sendmail(str(os.getenv('EMAIL')), str(os.getenv('TO')), f"ID {match} is at the front door")
        print("Sent Alert.")
        with open(f"Logs/{str(date.today())}/{str(date.today())}.log", 'a') as f:
            f.write(f'Located ID {match}')
            f.write("
")
            f.close()
        cv2.imwrite(f"Captures/ID_{match}_{str(date.today())}_{str(counter)}.png", image)
    else:
        match = str(next_id)
        next_id += 1
        known_names.append(match)
        known_faces.append(face_encoding)
        os.mkdir(f"{KNOWN_FACES_DIR}/{match}")
        pickle.dump(face_encoding, open(f"{KNOWN_FACES_DIR}/{match}/{match}-{int(time.time())}.pkl", 'wb'))
    print("Sent Alert.")
        with open(f"Logs/{str(date.today())}/{str(date.today())}.log", 'a') as f:
            f.write(f"New ID detected ID {match}")
            f.write("
")
            f.close()
        cv2.imwrite(f"Captures/ID_{match}_{str(date.today())}_{str(counter)}", image)

cv2.imshow("Archer", image)

if cv2.waitKey(1) & 0xFF == ord('q'):
    break
cv2.waitKey(0)

This is the Error I get

Traceback (most recent call last):
File "C:/Users/smith/Desktop/ArcherSurvalince/Montitor.py", line 79, in <module>
locations = face_recognition.face_locations(image, model=MODEL)
File "C:UserssmithDesktopArcherSurvalincevenvlibsite-packagesface_recognitionapi.py", line 
119, in face_locations
return [_trim_css_to_bounds(_rect_to_css(face.rect), img.shape) for face in _raw_face_locations(img, 
number_of_times_to_upsample, "cnn")]
File "C:UserssmithDesktopArcherSurvalincevenvlibsite-packagesface_recognitionapi.py", line 
103, in _raw_face_locations
return cnn_face_detector(img, number_of_times_to_upsample)
TypeError: __call__(): incompatible function arguments. The following argument types are supported:
1. (self: _dlib_pybind11.cnn_face_detection_model_v1, imgs: list, upsample_num_times: int=0, 
batch_size: int=128) -> std::vector<std::vector<dlib::mmod_rect,std::allocator<dlib::mmod_rect> 
>,std::allocator<std::vector<dlib::mmod_rect,std::allocator<dlib::mmod_rect> > > >
2. (self: _dlib_pybind11.cnn_face_detection_model_v1, img: array, upsample_num_times: int=0) -> 
std::vector<dlib::mmod_rect,std::allocator<dlib::mmod_rect> >

Invoked with: <_dlib_pybind11.cnn_face_detection_model_v1 object at 0x0000026F4F29ADB0>, None, 1

Did you forget to #include <pybind11/stl.h>? Or <pybind11/complex.h>, <pybind11/functional.h>, <pybind11/chrono.h>, etc. Some automatic conversions are optional and require extra headers to be included when compiling your pybind11 module.

I Have Pybind11 installed but I don't know how to fix it.

It seems to only happen when I try to access my IP camera and I can access my computers camera just fine and I have all of the dependcies installed


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

1 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...