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

Python3中人脸编码数值的正确数据类型及CSV读取问题

Fixing Face Encoding Conversion from CSV in Python 3

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, and float() can still parse the quoted string directly (or use val.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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 06:58:09