如何在Python中将face_recognition的人脸编码从字符串转回原始编码
如何将字符串形式的face_encoding转回原始编码格式?
嘿,我来帮你搞定这个问题!你已经把face_encoding转成字符串存在数据库里了,现在要转回face_recognition库需要的原始格式——也就是128维的numpy float数组,其实很简单,下面分两种常见情况给你解决方案:
情况1:你直接用str()把数组转成了字符串
如果你的字符串是像[0.1234 0.5678 ... -0.9012]这种(可能带换行),可以用numpy的fromstring方法配合字符串清理来还原:
import numpy as np # 假设从数据库取出的字符串是这个 unknown_encoding_string = "[0.123 0.456 -0.789 ... 0.321]" # 清理字符串:去掉首尾的[],替换换行和多余空格,然后转成numpy数组 cleaned_str = unknown_encoding_string.strip('[]').replace('\n', '').replace(' ', ' ').strip() restored_encoding = np.fromstring(cleaned_str, sep=' ', dtype=np.float64)
情况2:你用np.array2string()生成的字符串
如果是用numpy官方的数组转字符串方法生成的,也可以用ast.literal_eval来解析成列表,再转成numpy数组:
import numpy as np import ast unknown_encoding_string = np.array2string(unknown_encoding) # 假设是这么存的 # 清理后转成列表,再转numpy数组 cleaned_str = unknown_encoding_string.replace('\n', '').replace(' ', ' ') encoding_list = ast.literal_eval(cleaned_str) restored_encoding = np.array(encoding_list, dtype=np.float64)
验证还原是否正确
转回去之后,你可以用face_recognition.compare_faces()来测试是否和原始编码匹配:
# 假设restored_encoding是从数据库字符串转回的数组 matches = face_recognition.compare_faces([restored_encoding], unknown_encoding) if matches[0]: print("编码还原正确,匹配成功!")
小建议
其实后续存储face_encoding时,更推荐用JSON格式(把数组转成列表再存JSON)或者直接用numpy的np.savez存二进制,这样还原的时候更省心,也不容易出错~
内容的提问来源于stack exchange,提问作者Axil
相关产品推荐
相关产品推荐

