import cv2
import math
################ PROGRAM SETTINGS ####################
label_1 = "Class 1"
label_2 = "Class 2"
pixel_to_mm_conversion = 0.078 # Example conversion factor (adjust as needed)
############### END PROGRAM SETTINGS #################
def main(context):
rectangle_1 = find_rectangle(context, label_1)
rectangle_2 = find_rectangle(context, label_2)
if rectangle_1 is not None and rectangle_2 is not None:
x1, y1, w1, h1 = rectangle_1['x'], rectangle_1['y'], rectangle_1['width'], rectangle_1['height']
x2, y2, w2, h2 = rectangle_2['x'], rectangle_2['y'], rectangle_2['width'], rectangle_2['height']
center_x1 = x1 + w1 / 2
center_y1 = y1 + h1 / 2
center_x2 = x2 + w2 / 2
center_y2 = y2 + h2 / 2
distance_pixels = math.sqrt((center_x2 - center_x1)**2 + (center_y2 - center_y1)**2)
print("Distance between {} and {} in pixels: {:.2f}".format(label_1, label_2, distance_pixels))
# Convert distance from pixels to millimeters
distance_mm = distance_pixels * pixel_to_mm_conversion
print("Distance between {} and {} in millimeters: {:.2f}".format(label_1, label_2, distance_mm))
# Draw line between centers of rectangles on the original image in context
draw_line_on_image(context, (int(center_x1), int(center_y1)), (int(center_x2), int(center_y2)))
# Display distance on the original image in context
cv2.putText(context['image'], "Distance: {:.2f} mm".format(distance_mm), (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2)
else:
print("One or both rectangles not found.")
def find_rectangle(context, label):
for rectangle in context['detectedRectangles']:
for class_name_item in rectangle['classNames']:
if label == class_name_item['label']:
return rectangle
return None
def draw_line_on_image(context, start_point, end_point):
image = context['image']
# Convert image to BGR format (if not already in BGR)
if len(image.shape) == 2:
image = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR)
# Draw line on the image
cv2.line(image, start_point, end_point, (0, 0, 255), 2)
# Update the image in the context
context['image'] = image
|