I am using cv2 to compute the line withing the object present in the mask image attached. The orientation/shape of the object might vary (horizontal, vertical) from the other mask images in my dataset. But the problem is, the method I have used to compute the line is not reliable.
It works for the few images but failed to draw a line accurately for other mask images. Could anyone suggest an alternative approach?
this is the raw mask image
This is how a line shall be drawn (considering objects orientation)
Here is the code which represents my approach. I will highly appreciate any help from your side.
`import numpy as np
import cv2
import matplotlib.pyplot as plt
image_bgr = cv2.imread(IMAGE_PATH)
mask = masks[1]
Convert boolean mask to uint8
mask_uint8 = mask.astype(np.uint8) * 255
Find contours in the binary mask
contours, _ = cv2.findContours(mask_uint8, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
Draw contours and their centroids on the image
for c in contours:
# Calculate the centroid (center point) of the contour
M = cv2.moments(c)
cx = int(M[‘m10’] / M[‘m00’])
cy = int(M[‘m01’] / M[‘m00’])
# Draw contour and its centroid
cv2.drawContours(image_bgr, [c], -1, (255, 0, 0), 3)
cv2.circle(image_bgr, (cx, cy), 5, (0, 255, 0), -1)
# Find the leftmost, rightmost, and center points
left_side_point = tuple(c[c[:, :, 0].argmin()][0])
right_side_point = tuple(c[c[:, :, 0].argmax()][0])
center_point = (cx, cy)
# Calculate additional center points
left_center_point = ((left_side_point[0] + center_point[0]) // 2, (left_side_point[1] + center_point[1]) // 2)
right_center_point = ((right_side_point[0] + center_point[0]) // 2, (right_side_point[1] + center_point[1]) // 2)
# Draw lines
cv2.line(image_bgr, left_side_point, left_center_point, (0, 0, 255), 2)
cv2.line(image_bgr, left_center_point, center_point, (0, 0, 255), 2)
cv2.line(image_bgr, center_point, right_center_point, (0, 0, 255), 2)
cv2.line(image_bgr, right_center_point, right_side_point, (0, 0, 255), 2)
plt.imshow(image_bgr)
plt.show()`