Тест распознавания лиц не удался с правильным изображением [дубликат]Python

Программы на Python
Anonymous
 Тест распознавания лиц не удался с правильным изображением [дубликат]

Сообщение Anonymous »

Я начинаю изучать распознавание лиц, но даже мое простое «привет, мир» взрывается у меня на лице.
Вот код:

Код: Выделить всё

import face_recognition
from PIL import Image
import numpy as np
import base64
from io import BytesIO

def test_face_recognition(image_path):
# Open the image and ensure it's in RGB format
img = Image.open(image_path).convert('RGB')

# Convert image to numpy array
img_np = np.array(img)

# Check face detection
face_locations = face_recognition.face_locations(img_np)
print(f"Faces detected: {len(face_locations)}")

if len(face_locations) > 0:
face_encodings = face_recognition.face_encodings(img_np, known_face_locations=face_locations)
print(f"Encodings found: {len(face_encodings)}")
else:
print("No faces detected.")

# Replace with the path to a local image file
test_face_recognition("test_image.jpg")
test_image.jpg может быть любым файлом JPEG с лицом.
При запуске приведенный выше код выводится следующее сообщение об ошибке:

Код: Выделить всё

Traceback (most recent call last):
File "C:\Users\User\source\repos\ballot-box\flask\test_face_recognition.py", line 25, in 
test_face_recognition("test_image.jpg")
File "C:\Users\User\source\repos\ballot-box\flask\test_face_recognition.py", line 15, in test_face_recognition
face_locations = face_recognition.face_locations(img_np)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\User\source\repos\ballot-box\flask\venv\Lib\site-packages\face_recognition\api.py", line 121, in face_locations
return [_trim_css_to_bounds(_rect_to_css(face), img.shape) for face in _raw_face_locations(img, number_of_times_to_upsample, model)]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\User\source\repos\ballot-box\flask\venv\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.
Согласно сообщению об ошибке, изображение имеет недопустимый формат, но перед передачей функции распознавания лиц я конвертирую в соответствующий формат: img = Image.open(image_path).convert('RGB')
Отредактировано:
Я изменил с img_np на img безрезультатно. Теперь он вылетает со следующей ошибкой:

Код: Выделить всё

Traceback (most recent call last):
File "C:\Users\PauloSantos\source\repos\ballot-box\flask\test_face.py", line 25, in 
test_face_recognition("test_image.jpg")
File "C:\Users\PauloSantos\source\repos\ballot-box\flask\test_face.py", line 15, in test_face_recognition
face_locations = face_recognition.face_locations(img)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\PauloSantos\source\repos\ballot-box\flask\venv\Lib\site-packages\face_recognition\api.py", line 121, in face_locations
return [_trim_css_to_bounds(_rect_to_css(face), img.shape) for face in _raw_face_locations(img, number_of_times_to_upsample, model)]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\PauloSantos\source\repos\ballot-box\flask\venv\Lib\site-packages\face_recognition\api.py", line 105, in _raw_face_locations
return face_detector(img, number_of_times_to_upsample)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: __call__(): incompatible function arguments. The following argument types are supported:
1. (self: _dlib_pybind11.fhog_object_detector, image: numpy.ndarray, upsample_num_times: int = 0) -> _dlib_pybind11.rectangles

Invoked with: , 
, 1
Решено
Проблема — numpy версии 2.0. Согласно этому ответу, проблема возникает из-за критического изменения в numpy. Возврат к numpy 1.26.4 решил проблему.

Подробнее здесь: https://stackoverflow.com/questions/789 ... rect-image

Вернуться в «Python»