Python3中人脸编码数值的正确数据类型及CSV读取问题
Hey there! Let's sort out this face encoding issue you're having. First off, the correct data type for those values (like -0.02872239612042904) is Python's built-in float type—it natively supports negative decimals, so that's not the problem here. The issue lies in how you're extracting and converting the values from your CSV.
Why Your Current Approach Fails
Your regex r'\d+' only matches sequences of digits. That means it ignores the negative sign (-) and decimal point (.), so when you run re.findall(r'\d+', en) on a string like -0.02872239612042904, you get ['0', '02872239612042904']—completely losing the negative sign and decimal context. Converting those to floats gives you wrong values, which breaks your face distance calculation.
Correct Way to Read & Convert the CSV Data
You don't need regex here—just directly convert each string value from the CSV to a float. Here are two common scenarios based on how your CSV is structured:
Scenario 1: One Encoding Value Per Row
If your CSV has 128 rows, each with a single encoding value:
import csv face_encodings = [] csv_file_path = "your_face_encodings.csv" with open(csv_file_path, "r", newline="") as f: reader = csv.reader(f) for row in reader: # Strip any extra whitespace/quotes and convert to float try: encoding = float(row[0].strip()) face_encodings.append(encoding) except ValueError as e: print(f"Skipping invalid value: {row[0]} | Error: {e}") # Now face_encodings is a list of 128 float values matching your original data
Scenario 2: All 128 Encodings in a Single Row
If your CSV has one row with 128 comma-separated values:
import csv csv_file_path = "your_face_encodings.csv" with open(csv_file_path, "r", newline="") as f: reader = csv.reader(f) # Grab the first (and only) row of encodings face_encoding_row = next(reader) # Convert each value to float face_encodings = [float(val.strip()) for val in face_encoding_row] # face_encodings now contains your 128 original float values
Key Notes
- If your CSV values are wrapped in quotes (e.g.,
" -0.02872239612042904 "), the.strip()method will remove surrounding whitespace, andfloat()can still parse the quoted string directly (or useval.strip('" ')to be explicit). - Always add a try-except block to handle any invalid entries in the CSV—this prevents your code from crashing if there's a malformed value.
With this approach, you'll get the exact float values you stored in the CSV, and your face distance calculation should work as expected.
内容的提问来源于stack exchange,提问作者Asim

