You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中修改图像以适配face_recognition的8位灰度/RGB格式要求

解决face_recognition图像类型不支持错误

你遇到的错误提示是RuntimeError: Unsupported image type, must be 8bit gray or RGB image.,尽管图像已经是uint8类型的RGB格式(形状(720,1080,3)),但仍触发该错误,大概率是numpy数组内存布局不连续,或是多余的转换步骤引入了隐性问题。以下是几种可行的解决方法:

方法1:确保数组内存连续

face_recognition底层可能要求输入的numpy数组为连续内存布局,用np.ascontiguousarray()转换后再传入即可:

import cv2
import numpy as np
import face_recognition

image = cv2.imread("myimage.jpeg")
print(f"原dtype: {image.dtype}, 形状: {image.shape}")
# 输出: 原dtype: uint8, 形状: (720, 1080, 3)

image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# 转为连续内存数组
image_rgb_contiguous = np.ascontiguousarray(image_rgb)

face_locations = face_recognition.face_locations(image_rgb_contiguous)
print(face_locations)

方法2:简化转换流程,跳过Pillow中转

当前代码中的Pillow转换步骤完全多余,直接使用cv2转换后的RGB数组即可:

import cv2
import face_recognition

image = cv2.imread("myimage.jpeg")
image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

face_locations = face_recognition.face_locations(image_rgb)
print(face_locations)

方法3:直接用Pillow读取图像

face_recognition对Pillow读取的图像兼容性更好,尝试直接用Pillow加载:

from PIL import Image
import face_recognition

# 直接传入Pillow图像对象(无需转numpy数组)
pil_image = Image.open("myimage.jpeg")
face_locations = face_recognition.face_locations(pil_image)
print(face_locations)

原问题代码(含输出)

import cv2
import numpy as np
from PIL import Image
import face_recognition

image = cv2.imread("myimage.jpeg")
print(f"原dtype: {image.dtype}, 形状: {image.shape}")
'''输出: 原dtype: uint8, 形状: (720, 1080, 3)'''

image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
print(f"转换后dtype: {image_rgb.dtype}, 形状: {image_rgb.shape}")
'''输出: 转换后dtype: uint8, 形状: (720, 1080, 3)'''

pil_image = Image.fromarray(image_rgb)
image_rgb = np.array(pil_image)

image_rgb = image_rgb.astype(np.uint8)
print(f"最终dtype: {image_rgb.dtype}, 形状: {image_rgb.shape}")
'''输出: 最终dtype: uint8, 形状: (720, 1080, 3)'''

face_locations = face_recognition.face_locations(image_rgb)
print(face_locations)
'''输出: RuntimeError: Unsupported image type, must be 8bit gray or RGB image.'''

内容的提问来源于stack exchange,提问作者ovoxojxy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 11:39:59