Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Error loading images or encoding faces: Unsupported image type, must be 8bit gray or RGB image. #1612

Open
nhattym opened this issue Sep 26, 2024 · 8 comments

Comments

@nhattym
Copy link

nhattym commented Sep 26, 2024

  • face_recognition version:
  • Python version:
  • Operating System:

Description

Describe what you were trying to get done.
Tell us what happened, what went wrong, and what you expected to happen.
IMPORTANT: If your issue is related to a specific picture, include it so others can reproduce the issue.

What I Did

Paste the command(s) you ran and the output.
If there was a crash, please include the traceback here.
@mWhrerttttt
Copy link

import face_recognition
import cv2

video_capture = cv2.VideoCapture(0)

Load a sample picture and learn how to recognize it.

obama_image = face_recognition.load_image_file('picther\elonmask.jpg')
obama_face_encoding = face_recognition.face_encodings(obama_image)[0]

Load a second sample picture and learn how to recognize it.

biden_image = face_recognition.load_image_file("picther/mohamm.jpg")
biden_face_encoding = face_recognition.face_encodings(biden_image)[0]

Create arrays of known face encodings and their names

known_face_encodings = [
obama_face_encoding,
biden_face_encoding
]
known_face_names = [
"omar",
"Mohamed"
]

Initialize some variables

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

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

# Only process every other frame of video to save time
if process_this_frame:
    # Resize frame of video to 1/4 size for faster face recognition processing

    # Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses)
    rgb_small_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    
    # 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(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,0.6)
        name = "Unknown"

        print(matches)
        # # 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]

        # # Or instead, use the known face with the smallest distance to the new face
        # face_distances = face_recognition.face_distance(known_face_encodings, face_encoding)
        # best_match_index = np.argmin(face_distances)
        # if matches[best_match_index]:
        #     name = known_face_names[best_match_index]
        #     print(name)

        face_names.append(name)

process_this_frame = not process_this_frame
clr=(0, 0, 255)
if True in matches:
    clr=(0, 255, 0)

# Display the results
for (top, right, bottom, left), name in zip(face_locations, face_names):
    # Draw a box around the face
    cv2.rectangle(frame, (left, top), (right, bottom),clr , 2)

Draw a label with a name below the face

    cv2.rectangle(frame, (left, bottom - 35), (right, bottom), clr, 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('Video', frame)

# Hit 'q' on the keyboard to quit!
if cv2.waitKey(1) & 0xFF == ord('q'):
    break

Release handle to the webcam

video_capture.release()
cv2.destroyAllWindows()

@mWhrerttttt
Copy link

Traceback (most recent call last):
File "c:\Users\User\Desktop\FACERECORGING\rect.py", line 10, in
obama_face_encoding = face_recognition.face_encodings(obama_image)[0]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\User\AppData\Local\Programs\Python\Python312\Lib\site-packages\face_recognition\api.py", line 213, in face_encodings
raw_landmarks = _raw_face_landmarks(face_image, known_face_locations, model)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\User\AppData\Local\Programs\Python\Python312\Lib\site-packages\face_recognition\api.py", line 156, in _raw_face_landmarks
face_locations = _raw_face_locations(face_image)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\User\AppData\Local\Programs\Python\Python312\Lib\site-packages\face_recognition\api.py", line 105, in _raw_face_locations
return face_detector(img, number_of_times_to_upsample)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
RuntimeError: Unsupported image type, must be 8bit gray or RGB image.

@mWhrerttttt
Copy link

is there a solution to this error message that appears

@olimattison
Copy link

I think downgrading numpy is what got rid of that for me.

@flerken42
Copy link

Downgrading Numpy version did the trick for me. I used:

pip install numpy==1.26.4

@lailakarbash
Copy link

التتبع (آخر مكالمة أخيرة): ملف "c:\Users\User\Desktop\FACERECORGING\rect.py"، السطر 10، في obama_face_encoding = face_recognition.face_encodings(obama_image)[0] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ الملف "C:\Users\User\AppData\Local\Programs\Python312\Lib\site-packages\face_recognition\api.py"، السطر 213، في face_encodings raw_landmarks = _raw_face_landmarks(face_image، known_face_locations، نموذج) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ملف "C: \ المستخدمون \ المستخدم \ AppData \ المحلية \ البرامج \ Python \ Python \ Python312 \ Lib \ site-packages \ face_recognition \ api.py" ، السطر 156 ، في _raw_face_landmarks face_locations = _raw_face_locations (face_image) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^ ملف "C: \ Users \ User \ AppData \ Local \ Programs \ Python \ Python312 \ Lib \ site-packages \ face_recognition \ api.py" ، السطر 105 ، في raw_face ترجع المواقع face_detector (img، number_of_times_to_upsample) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ RuntimeError: نوع الصورة غير المدعوم، يجب أن يكون 8 بت رمادي أو صورة RGB.

مساء الخير

@Md-Sabbir-al-shafi
Copy link

Downgrading Numpy version did the trick for me. I used:

pip install numpy==1.26.4

it worked

@MrITACHI008
Copy link

🚀 Fix: Unsupported image type, must be 8-bit gray or RGB image

🔍 Issue

The error occurs when the image is not in a proper format that face_recognition can process.

Unsupported image type, must be 8bit gray or RGB image.

✅ Possible Fixes

1️⃣ Check Image Path

Your image path might be incorrect. Instead of:

obama_image = face_recognition.load_image_file('picther\elonmask.jpg')

✅ Use either:

obama_image = face_recognition.load_image_file(r'picther\elonmask.jpg')  # Raw string

or

obama_image = face_recognition.load_image_file('picther/elonmask.jpg')  # Forward slash

2️⃣ Verify Image Format

Ensure your image is either JPEG, PNG, or BMP.

  • Try opening the image manually in an image viewer to check for corruption.
  • Convert the image to RGB using OpenCV:
import cv2

image = cv2.imread('picther/elonmask.jpg')  # Load image
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)  # Convert to RGB
cv2.imwrite('picther/elonmask_fixed.jpg', image)  # Save fixed image

3️⃣ Check Image Depth (Must Be 8-bit)

Your image may be 16-bit. Convert it to 8-bit RGB using PIL:

from PIL import Image

image = Image.open("picther/elonmask.jpg")
image = image.convert("RGB")  # Convert to 8-bit RGB
image.save("picther/elonmask_fixed.jpg")

Then use elonmask_fixed.jpg in face_recognition.load_image_file().


4️⃣ Reinstall face_recognition & Dependencies

If the issue persists, reinstall face_recognition and its dependencies:

pip uninstall face_recognition dlib opencv-python numpy -y
pip install numpy==1.26.4
pip install face_recognition opencv-python dlib

🛑 Why downgrade NumPy?
Some versions of face_recognition are incompatible with newer numpy releases.


5️⃣ Check If Image Contains a Face

Some images may not be detected correctly. Try this:

import face_recognition

image = face_recognition.load_image_file("picther/elonmask.jpg")
face_locations = face_recognition.face_locations(image)

if len(face_locations) == 0:
    print("⚠️ No face detected! Try another image.")

📌 Summary of Fixes

  • Check file path formatting
  • Convert the image to RGB (8-bit)
  • Ensure image is JPEG/PNG/BMP
  • Downgrade NumPy (numpy==1.26.4)
  • Verify that the image contains a face

Let me know if you need further assistance! 🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

7 participants