如何将人脸检测代码封装为Python def函数及解决'TypeError: 'function' object is not subscriptable'错误
人脸检测代码封装问题与解决方法
嘿,这个问题我之前也碰到过,咱们一步步来拆解修复它!
问题回顾
你原本想把这段人脸检测逻辑封装成Python函数:
detected_faces1 = face_client.face.detect_with_url(IMAGE_BASE_URL + source_image_file_name1, detection_model='detection_03') source_image1_id = detected_faces1[0].face_id print('{} face(s) detected from image {}.'.format(len(detected_faces1), source_image_file_name1))
自己编写的函数运行时却抛出了TypeError: 'function' object is not subscriptable错误:
def detected_faces1(): face_client.face.detect_with_url(IMAGE_BASE_URL, detection_model='detection_03') source_image1_id = detected_faces1[0].face_id print('{} face(s) detected from image.'.format(len(detected_faces1)))
错误原因分析
核心问题有两个:
- 命名冲突:你把函数命名为
detected_faces1,和原代码里存储检测结果的变量名完全一样!在函数内部尝试detected_faces1[0]时,Python会认为你在访问这个函数对象,而不是API返回的人脸列表,函数是不能用下标访问的,这就是报错的直接原因。 - 逻辑缺失:你调用API时没有拼接图片文件名,也没有保存API返回的检测结果,等于白调用了,自然拿不到人脸数据。
正确的函数封装
这里给你一个更健壮的版本,解决了上述问题,还增加了异常处理:
def detect_face_from_url(image_file_name): # 调用人脸检测API并保存返回结果 detected_faces = face_client.face.detect_with_url( IMAGE_BASE_URL + image_file_name, detection_model='detection_03' ) # 处理未检测到人脸的情况,避免索引错误 if not detected_faces: print(f"No faces detected from image {image_file_name}.") return None, None # 获取第一张人脸的ID face_id = detected_faces[0].face_id print(f"{len(detected_faces)} face(s) detected from image {image_file_name}.") # 返回人脸ID和完整检测结果,方便后续业务使用 return face_id, detected_faces
函数使用示例
调用这个函数非常简单,只需要传入你的图片文件名即可:
# 调用封装好的函数 source_image1_id, detected_faces1 = detect_face_from_url(source_image_file_name1) # 如果需要使用检测结果,比如遍历所有人脸 if detected_faces1: for face in detected_faces1: print(f"Face ID: {face.face_id}")
关键修复点总结
- 给函数起了一个清晰且不冲突的名字
detect_face_from_url - 添加了
image_file_name参数,让函数可以灵活处理不同的图片 - 保存了API的返回结果,确保能拿到人脸数据
- 增加了空结果判断,避免后续代码出现索引越界错误
- 返回人脸ID和完整检测结果,让函数的复用性更强
内容的提问来源于stack exchange,提问作者Rifaye Ibrahim
相关产品推荐
相关产品推荐

