Score:0

Opencv crashes on startup

cn flag

Trying to use face recognition on real time on my webcam but opencv crashes just after opening camera. here is the code:

import face_recognition
import cv2
import os
import re


fileIndex = {
    '#png_files'
}

video_capture = cv2.VideoCapture(0)


known_face_encodings = []
known_face_names = []
for n in os.listdir('#path'):
    sp = os.path.splitext(n)
    if re.match(r'^\.(png|jpe?g|gif)$', sp[1]):
        if fileIndex.get(n):
            img = face_recognition.load_image_file("#path" + n)
            encoding = face_recognition.face_encodings(img)[0]
            known_face_encodings.append(encoding)
            known_face_names.append(n)

face_locations = []
face_encodings = []
face_names = []
process_this_frame = True

while True:
    # Grab a single frame of video
    ret, frame = video_capture.read()

    # Resize frame of video to 1/4 size for faster face recognition processing
    small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)

    # Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses)
    rgb_small_frame = small_frame[:, :, ::-1]

    # Only process every other frame of video to save time
    if process_this_frame:
        # Find all the faces and face encodings in the current frame of video
        face_locations = face_recognition.face_locations(rgb_small_frame)
        face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)

        face_names = []
        for face_encoding in face_encodings:
            # See if the face is a match for the known face(s)
            matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
            name = "Unknown"

            # If a match was found in known_face_encodings, just use the first one.
            if True in matches:
                first_match_index = matches.index(True)
                name = known_face_names[first_match_index]
                name = fileIndex.get(name, 'Unknown')

            face_names.append(os.path.splitext(name)[0])

    process_this_frame = not process_this_frame
    

    # Display the results
    for (top, right, bottom, left), name in zip(face_locations, face_names):
        # Scale back up face locations since the frame we detected in was scaled to 1/4 size
        top *= 4
        right *= 4
        bottom *= 4
        left *= 4

        # Draw a box around the face
        cv2.rectangle(frame, (left, top), (right, bottom), (3, 168, 124), 2)

        # Draw a label with a name below the face
        cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (3, 168, 124), cv2.FILLED)
        font = cv2.FONT_HERSHEY_DUPLEX
        cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)

    # Display the resulting image
    cv2.imshow('user-cam', frame)
    
    # Hit 'q' on the keyboard to quit!
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

video_capture.release()
cv2.destroyAllWindows()

And here is the python error:

Traceback (most recent call last):
  File "/home/s3idani/Scripts/security/face_recognition/py/facerec_from_webcam_more_faster.py", line 60, in <module>
    face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)
  File "/home/s3idani/.local/lib/python3.8/site-packages/face_recognition/api.py", line 214, in face_encodings
    return [np.array(face_encoder.compute_face_descriptor(face_image, raw_landmark_set, num_jitters)) for raw_landmark_set in raw_landmarks]
  File "/home/s3idani/.local/lib/python3.8/site-packages/face_recognition/api.py", line 214, in <listcomp>
    return [np.array(face_encoder.compute_face_descriptor(face_image, raw_landmark_set, num_jitters)) for raw_landmark_set in raw_landmarks]
TypeError: compute_face_descriptor(): incompatible function arguments. The following argument types are supported:
    1. (self: _dlib_pybind11.face_recognition_model_v1, img: numpy.ndarray[(rows,cols,3),numpy.uint8], face: _dlib_pybind11.full_object_detection, num_jitters: int = 0, padding: float = 0.25) -> _dlib_pybind11.vector
    2. (self: _dlib_pybind11.face_recognition_model_v1, img: numpy.ndarray[(rows,cols,3),numpy.uint8], num_jitters: int = 0) -> _dlib_pybind11.vector
    3. (self: _dlib_pybind11.face_recognition_model_v1, img: numpy.ndarray[(rows,cols,3),numpy.uint8], faces: _dlib_pybind11.full_object_detections, num_jitters: int = 0, padding: float = 0.25) -> _dlib_pybind11.vectors
    4. (self: _dlib_pybind11.face_recognition_model_v1, batch_img: List[numpy.ndarray[(rows,cols,3),numpy.uint8]], batch_faces: List[_dlib_pybind11.full_object_detections], num_jitters: int = 0, padding: float = 0.25) -> _dlib_pybind11.vectorss
    5. (self: _dlib_pybind11.face_recognition_model_v1, batch_img: List[numpy.ndarray[(rows,cols,3),numpy.uint8]], num_jitters: int = 0) -> _dlib_pybind11.vectors

Invoked with: <_dlib_pybind11.face_recognition_model_v1 object at 0x7f906a226830>, array([[[252, 248, 200],
        [255, 252, 205],
        [252, 248, 203],
        ...,
        [188, 210, 189],
        [181, 201, 177],
        [163, 186, 170]],

       [[252, 251, 205],
        [253, 255, 208],
        [252, 254, 205],
        ...,
        [189, 211, 187],
        [187, 207, 183],
        [171, 187, 172]],

       [[251, 250, 206],
        [253, 255, 216],
        [253, 255, 217],
        ...,
        [184, 207, 189],
        [202, 223, 197],
        [166, 192, 166]],

       ...,

       [[182, 162, 117],
        [201, 189, 146],
        [181, 166, 125],
        ...,
        [211, 240, 227],
        [209, 237, 225],
        [203, 237, 220]],

       [[166, 150, 119],
        [174, 156, 122],
        [162, 148, 112],
        ...,
        [206, 242, 223],
        [207, 237, 219],
        [205, 232, 216]],

       [[136, 128, 110],
        [150, 143, 112],
        [155, 148, 113],
        ...,
        [208, 239, 222],
        [207, 236, 220],
        [205, 231, 211]]], dtype=uint8), <_dlib_pybind11.full_object_detection object at 0x7f906a226370>, 1

python 3.8

opencv 4.7

dlib 19.24

How to fix this issue ?

us flag
Please run the python file on terminal, and post the error message.
ru flag
What is the Python error output? Without your error codes and traceback we can't help you.
kanehekili avatar
zw flag
opencv runs on several on my devices (including raspberry) without any problems. Do as @ Archisman Panigrahi and @Thomas Ward suggest.
ru flag
Are you sure you're on Python 3.8? This error behaves more like you're on a version of Python (3.10+) that is hyper-strict with typing.
s3idani avatar
cn flag
Question edited.
s3idani avatar
cn flag
@Thomas `python3 -V` = python 3.8.10
Score:1
mq flag

I was having the same issue, I found it helpful to replace

rgb_frame = cv2.cvtColor(small_frame, cv2.COLOR_BGR2RGB)

with

rgb_frame = small_frame[:, :, ::-1]

This issue might be more helpful https://github.com/ageitgey/face_recognition/issues/1497

s3idani avatar
cn flag
Yes it works. Thank you. And to draw the label-box under faces i changed `rgb_frame = small_frame[:, :, ::-1]` to `rgb_frame = cv2.cvtColor(small_frame, cv2.COLOR_BGR2RGB)` with `rgb_small_frame` to `rgb_frame`.
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.