not
unknown
python
a year ago
1.7 kB
5
Indexable
import cv2 import numpy as np # Function to calculate the midpoint of a line segment def midpoint(p1, p2): return ((p1[0] + p2[0]) // 2, (p1[1] + p2[1]) // 2) # Load the image image = cv2.imread('tray_image.jpg') # Convert to grayscale gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Apply GaussianBlur to reduce noise blurred = cv2.GaussianBlur(gray, (5, 5), 0) # Apply thresholding to get a binary image _, binary = cv2.threshold(blurred, 60, 255, cv2.THRESH_BINARY_INV) # Find contours in the binary image contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # Iterate through contours and extract midpoints of each edge for contour in contours: # Approximate the contour to get polygonal curves epsilon = 0.01 * cv2.arcLength(contour, True) approx = cv2.approxPolyDP(contour, epsilon, True) # Draw the contour on the original image (for visualization) cv2.drawContours(image, [approx], -1, (0, 255, 0), 2) # Iterate through the vertices of the polygon for i in range(len(approx)): # Get the current point and the next point (looping around) p1 = tuple(approx[i][0]) p2 = tuple(approx[(i + 1) % len(approx)][0]) # Calculate the midpoint mid = midpoint(p1, p2) # Draw the midpoint on the image cv2.circle(image, mid, 5, (255, 0, 0), -1) # Print the coordinates of the midpoint print(f"Midpoint between {p1} and {p2}: {mid}") # Display the result cv2.imshow('Detected Objects with Midpoints', image) cv2.waitKey(0) cv2.destroyAllWindows()
Editor is loading...
Leave a Comment