如何修复Python中‘TypeError: cannot unpack non-iterable numpy.float64 object’错误
Got it, let's work through this error step by step.
What's causing the error?
Your code expects each line in the lines list to be an iterable of coordinate groups (like [[x1, y1, x2, y2]]), but right now each line is a 1D numpy array containing 8 floating-point values. When you try to run for x1, y1, x2, y2 in line, Python tries to unpack every single float in that array into four variables—which obviously doesn't work, hence the TypeError.
How to fix it
Since you mentioned each line has 8 floats, this likely means each entry represents two separate lane line segments (e.g., [x1, y1, x2, y2, x3, y3, x4, y4]). Here's how to adjust your draw_lines function to handle this structure:
def draw_lines(image, lines, color=[255, 0, 0], thickness=4): for line in lines: # Reshape the 8-value array into groups of 4 coordinates each line_segments = line.reshape(-1, 4) # Iterate over each 4-value segment to draw lines for coords in line_segments: # Convert float coordinates to integers (OpenCV requires integer pixel positions) x1, y1, x2, y2 = map(int, coords) cv2.line(image, (x1, y1), (x2, y2), color, thickness)
Key notes:
- The
reshape(-1, 4)call takes your 1D array of 8 floats and turns it into a 2D array with 2 rows (each holding 4 coordinate values). - We use
map(int, coords)to convert the float values to integers—OpenCV'scv2.lineexpects integer pixel coordinates, so this avoids potential warnings or unexpected behavior.
Quick check to confirm structure
If you're still unsure about the shape of your lines array, add a print statement at the start of draw_lines to debug:
def draw_lines(image, lines, color=[255, 0, 0], thickness=4): print("Lines shape:", lines.shape) print("First line shape:", lines[0].shape) # Rest of your code...
This will tell you exactly how your line data is structured, so you can tweak the reshape logic if needed.
内容的提问来源于stack exchange,提问作者Mahinsa Athree

