如何从DeepFace.analyze返回的JSON数组中提取dominant_gender值?
解决DeepFace.analyze提取dominant_gender的问题
问题原因
你看到的返回结果是包含单个字典的列表(外层用[]包裹),所以直接用result["dominant_gender"]会触发类型错误——列表只能用整数索引;而result[1]报错是因为列表只有1个元素,索引范围是0。
正确提取方式
先通过索引0获取列表里的字典元素,再提取dominant_gender字段:
from deepface import DeepFace def detect(image): result = DeepFace.analyze(image, actions=['gender']) # 提取第一张脸的主导性别 dominant_gender = result[0]['dominant_gender'] print(dominant_gender) detect("image.jpeg")
处理多张脸的情况
如果图片里有多张脸,DeepFace.analyze会返回包含多个字典的列表,此时可以用循环遍历所有结果:
from deepface import DeepFace def detect(image): results = DeepFace.analyze(image, actions=['gender']) for face_idx, face_data in enumerate(results): print(f"第{face_idx+1}张脸的主导性别:{face_data['dominant_gender']}") detect("image.jpeg")
内容的提问来源于stack exchange,提问作者A RAHMAN
相关产品推荐
相关产品推荐

