报错ValueError: invalid literal for int() with base 10,求坐标提取修正方案
Hey there! Let's break down why you're hitting that ValueError: invalid literal for int() with base 10 error and fix your coordinate extraction code.
What's Causing the Error?
Your input data has a file path as the first column (e.g., data/processed/10/blueprint-0.png), but your original code tries to convert every element in the row to an integer. That string path can't be parsed as an integer—hence the crash.
On top of that, your coordinate values are stored as strings with a .0 suffix (like "1915.0"), which also can't be directly converted to an integer without first handling the decimal part.
Corrected Code to Extract Coordinates
Here's a revised version of your code that addresses both issues:
import csv with open('data', newline='') as csvfile: results = csv.reader(csvfile, delimiter=',') for row in results: # Skip the first column (file path) and process only coordinate values coordinate_strings = row[1:] # Convert decimal strings (like "1915.0") to integers # First convert to float, then to int (this safely handles the .0 suffix) int_coords = [int(float(coord)) for coord in coordinate_strings] # Extract x and y coordinates (every 2nd element starting at index 0 for x, 1 for y) x_coords = int_coords[::2] y_coords = int_coords[1::2] # Calculate boundary values as you started to do top = min(y_coords) bottom = max(y_coords) left = min(x_coords) right = max(x_coords) # Optional: Print results to verify output print(f"File: {row[0]}") print(f"Extracted coordinate pairs: {list(zip(x_coords, y_coords))}") print(f"Boundary box: Left={left}, Right={right}, Top={top}, Bottom={bottom}\n")
Key Fixes Explained
- Skip the file path: We start processing from
row[1:]to avoid trying to convert the first column (a string path) to an integer. - Handle decimal coordinates: Using
int(float(coord))safely converts strings like"1915.0"to the integer1915. If you're certain all values end with.0, you could also useint(coord.split('.')[0]), but the float-to-int method is more robust for unexpected decimal values. - Clean coordinate slicing:
int_coords[::2]grabs every 2nd element starting at index 0 (x-values), andint_coords[1::2]grabs every 2nd element starting at index 1 (y-values).
Adding Error Handling (Optional)
If your input file might have malformed rows (missing values, non-numeric entries), add error handling to avoid crashes:
import csv with open('data', newline='') as csvfile: results = csv.reader(csvfile, delimiter=',') for row_num, row in enumerate(results, start=1): try: # Skip rows that don't have at least a file path + 1 set of coordinates if len(row) < 5: print(f"Warning: Row {row_num} has insufficient data. Skipping.") continue coordinate_strings = row[1:] int_coords = [int(float(coord)) for coord in coordinate_strings] # Ensure x and y counts match (each coordinate pair needs an x and y) if len(int_coords) % 2 != 0: print(f"Warning: Row {row_num} has an odd number of coordinate values. Skipping.") continue x_coords = int_coords[::2] y_coords = int_coords[1::2] top = min(y_coords) bottom = max(y_coords) left = min(x_coords) right = max(x_coords) print(f"Row {row_num} - File: {row[0]}") print(f"Coordinates: {list(zip(x_coords, y_coords))}") print(f"Bounds: Left={left}, Right={right}, Top={top}, Bottom={bottom}\n") except ValueError as e: print(f"Error processing row {row_num}: {str(e)}. Skipping this row.")
内容的提问来源于stack exchange,提问作者Jess

