从文本文件读取坐标点并判断是否在多边形内的技术求助
Let's break down the issues in your current script and walk through a corrected solution that handles your batch coordinate files properly.
1. Root Cause of the IndexError
Your script assumes each line in your text files holds exactly one (x,y) coordinate pair. But based on your description, both files likely have all coordinates in a single line (or contain empty lines). When you loop through lines and split them, empty lines result in an empty row list, leading to row[0] being out of range. Even if all coordinates are in one line, your code would only capture the first two values and fail on subsequent empty lines.
2. Incorrect Geometry Object Setup
- You tried creating a single
Pointfrom lists of all x/y values—this doesn't work;Pointexpects a single (x,y) pair. - The
Polygonwas built incorrectly: it requires a list of (x,y) tuples, not two separate lists of x and y coordinates.
Corrected Script
Here's a revised script that fixes these issues and outputs control points inside the polygon:
from shapely.geometry import Point, Polygon def read_coordinate_pairs(file_path): """Read all (x,y) pairs from a text file, handling any line structure.""" coords = [] with open(file_path, 'r') as file: for line in file: # Split line into individual values, ignoring extra whitespace/empty strings values = [val.strip() for val in line.split() if val.strip()] # Group values into (x,y) tuples and convert to floats for i in range(0, len(values), 2): if i + 1 < len(values): x = float(values[i]) y = float(values[i+1]) coords.append((x, y)) return coords # Read and process polygon coordinates polygon_coords = read_coordinate_pairs("polygon.txt") polygon = Polygon(polygon_coords) # Read and process control points control_points = read_coordinate_pairs("controlPoints.txt") # Check each control point and collect those inside the polygon points_inside = [] for x, y in control_points: point = Point(x, y) if point.within(polygon): points_inside.append((x, y)) # Print the results print("Control points inside the polygon:") for coord in points_inside: print(f"{coord[0]:.3f} {coord[1]:.3f}")
Key Improvements Explained
- Flexible Coordinate Reading: The
read_coordinate_pairsfunction handles any line structure (all coords in one line, multiple lines, etc.). It skips empty lines and extra whitespace, then groups values into valid (x,y) pairs, eliminating theIndexError. - Correct Geometry Creation: The polygon is built from a list of (x,y) tuples, which is the required format for
shapely.geometry.Polygon. - Batch Point Checking: We loop through each control point, create a
Pointobject for each, and usepoint.within(polygon)to check if it lies inside the polygon. - Readable Output: Results are printed with 3 decimal places to match your input format.
How to Use
- Ensure
polygon.txtcontains all 24 numbers (12 vertices) in any line structure. - Ensure
controlPoints.txtcontains all your control point coordinates (each pair as two numbers, in any line structure). - Run the script—you'll see all control points inside the polygon printed to your terminal.
内容的提问来源于stack exchange,提问作者kwak

