Calculating real-world distances from image points involves translating pixel measurements into actual measurements, accounting for factors like rotation, perspective distortion, and camera parameters. To achieve robust distance calculations regardless of the points' orientation or position in the image, you can use homography. Homography allows you to map points from the image plane to real-world coordinates, enabling accurate distance measurements.
Below, I'll outline the methods and provide a step-by-step guide to implement real-world distance calculations using homography in your existing OpenCV application.
Methods for Calculating Real-World Distances
-
Homography with Known Reference Points:
- Description: Utilize a set of corresponding points between the image and the real world to compute a homography matrix. This matrix transforms image coordinates to real-world coordinates.
- Use Case: When you have a planar scene (e.g., a floor or a wall) and can identify points with known real-world positions.
-
Single Reference Scale (Simpler but Less Robust):
- Description: Use a single reference measurement (e.g., the length of a known object) to calculate a scale factor that translates pixels to real-world units.
- Use Case: Suitable for simple scenarios with minimal perspective distortion.
-
Camera Calibration (Advanced):
- Description: Calibrate the camera to obtain intrinsic and extrinsic parameters, allowing for precise mapping from image to real-world coordinates.
- Use Case: When high precision is required, and multiple calibration images are available.
Step-by-Step Implementation Using Homography
Prerequisites:
- A planar scene where you can identify at least four points with known real-world coordinates.
- Corresponding points in the image and the real world.
Implementation Steps:
-
Select Reference Points:
- Identify at least four non-colinear points on the planar scene.
- Note their real-world coordinates (e.g., corners of a square with known side lengths).
-
Modify the Application to Input Reference Points:
- Allow the user to select these four points interactively on the image.
- Enter the corresponding real-world coordinates for each selected point.
-
Compute the Homography Matrix:
- Use the selected image points and their real-world counterparts to compute the homography matrix using OpenCV's
cv2.findHomography() function.
-
Map Image Points to Real-World Coordinates:
- Apply the homography matrix to transform all image points to real-world coordinates.
-
Calculate Euclidean Distances:
- With real-world coordinates, compute the Euclidean distance between any two points.
-
Integrate Real-World Distance Display:
- Display the calculated real-world distances alongside the pixel distances on the image.
Detailed Implementation Steps with Code
Let's extend your existing code to include real-world distance calculations using homography.
1. Modify the Toolbar to Include "Set Reference" Mode
Add a new mode to allow users to set reference points.
buttons = [
{"label": "Add", "color": (200, 200, 200)},
{"label": "Delete", "color": (200, 200, 200)},
{"label": "Move", "color": (200, 200, 200)},
{"label": "Line", "color": (200, 200, 200)},
{"label": "Remove Line", "color": (200, 200, 200)},
{"label": "Clear", "color": (200, 200, 200)},
{"label": "Set Reference", "color": (200, 200, 200)}, # New Button
{"label": "Quit", "color": (200, 200, 200)}
]
2. Initialize Variables for Homography
# Homography related variables
homography_matrix = None
ref_points_image = []
ref_points_real = [] # User should input real-world coordinates for these points
reference_mode = False
3. Update the Mouse Callback to Handle Reference Point Selection
def handle_mouse(event, x, y, flags, param):
global selected_point, points, mode, line_mode_selected_points
global current_mouse_position, lines
global homography_matrix, ref_points_image, ref_points_real, reference_mode
# Update current mouse position
if y > toolbar_height:
img_x, img_y = x, y - toolbar_height
current_mouse_position = (img_x, img_y)
else:
current_mouse_position = (-1, -1)
if y <= toolbar_height:
# Click is on the toolbar
if event == cv2.EVENT_LBUTTONDOWN:
for idx, button in enumerate(buttons):
x_start = button_margin + idx * (button_width + button_margin)
y_start = 5
x_end = x_start + button_width
y_end = y_start + button_height
if x_start <= x <= x_end and y_start <= y <= y_end:
label = button["label"].lower().replace(" ", "_")
if label == 'add':
mode = 'add'
reference_mode = False
elif label == 'delete':
mode = 'delete'
reference_mode = False
elif label == 'move':
mode = 'move'
reference_mode = False
elif label == 'line':
mode = 'line'
line_mode_selected_points = []
reference_mode = False
elif label == 'remove_line':
mode = 'remove_line'
reference_mode = False
elif label == 'clear':
points.clear()
lines.clear()
line_mode_selected_points = []
selected_point = -1
homography_matrix = None
ref_points_image = []
ref_points_real = []
print("All points, lines, and references cleared.")
reference_mode = False
elif label == 'set_reference':
mode = 'set_reference'
reference_mode = True
ref_points_image = []
ref_points_real = []
print("Reference mode activated. Please select four reference points.")
elif label == 'quit':
cv2.destroyAllWindows()
exit()
print(f"Mode: {mode.replace('_', ' ').capitalize()}")
redraw_image()
return # Exit after handling button click
else:
# Click is on the image
if img_x < 0 or img_y < 0 or img_y >= original_image.shape[0] or img_x >= original_image.shape[1]:
return # Click outside the image area
if reference_mode:
if event == cv2.EVENT_LBUTTONDOWN:
if len(ref_points_image) < 4:
ref_points_image.append((img_x, img_y))
print(f"Reference image point {len(ref_points_image)}: {ref_points_image[-1]}")
# Prompt user to input real-world coordinates
real_x = float(input(f"Enter real-world X for point {len(ref_points_real)+1}: "))
real_y = float(input(f"Enter real-world Y for point {len(ref_points_real)+1}: "))
ref_points_real.append((real_x, real_y))
if len(ref_points_image) == 4:
# Compute Homography
src_pts = np.array(ref_points_image, dtype=np.float32)
dst_pts = np.array(ref_points_real, dtype=np.float32)
homography_matrix, status = cv2.findHomography(src_pts, dst_pts)
if homography_matrix is not None:
print("Homography matrix computed successfully.")
else:
print("Error computing homography matrix.")
reference_mode = False
redraw_image()
else:
print("Already selected four reference points.")
return # Exit after handling reference point click
# Proceed with regular modes
if mode == 'add' and event == cv2.EVENT_LBUTTONDOWN:
# Add a new point
points.append((img_x, img_y))
print(f"Point added at: ({img_x}, {img_y})")
redraw_image()
elif mode == 'delete' and event == cv2.EVENT_LBUTTONDOWN:
# Delete point if close to it
for i, point in enumerate(points):
distance_sq = (img_x - point[0]) ** 2 + (img_y - point[1]) ** 2
if distance_sq <= (point_radius * 2) ** 2: # Increased area for better hit detection
print(f"Point deleted at: {points[i]}")
points.pop(i)
# Also remove any lines connected to this point
lines[:] = [line for line in lines if line['points'][0] != point and line['points'][1] != point]
break
redraw_image()
elif mode == 'move':
if event == cv2.EVENT_LBUTTONDOWN:
# Select the point if close to it
for i, point in enumerate(points):
distance_sq = (img_x - point[0]) ** 2 + (img_y - point[1]) ** 2
if distance_sq <= (point_radius * 2) ** 2:
selected_point = i
print(f"Selected point {i + 1} for moving.")
break
elif event == cv2.EVENT_MOUSEMOVE and selected_point != -1 and flags & cv2.EVENT_FLAG_LBUTTON:
# Update the position of the selected point
points[selected_point] = (img_x, img_y)
redraw_image()
elif event == cv2.EVENT_LBUTTONUP:
# Release the point
if selected_point != -1:
print(f"Point {selected_point + 1} moved to: {points[selected_point]}")
selected_point = -1
redraw_image()
elif mode == 'line':
if event == cv2.EVENT_LBUTTONDOWN:
# Select two points to draw a line
clicked_point = None
for point in points:
distance_sq = (img_x - point[0]) ** 2 + (img_y - point[1]) ** 2
if distance_sq <= (point_radius * 2) ** 2:
clicked_point = point
break
if clicked_point:
# Avoid selecting the same point twice
if clicked_point not in line_mode_selected_points:
line_mode_selected_points.append(clicked_point)
print(f"Point selected for line: {clicked_point}")
else:
print("Same point selected. Please select a different point.")
if len(line_mode_selected_points) == 2:
pt1, pt2 = line_mode_selected_points
if homography_matrix is not None:
# Map to real-world coordinates
real_pt1 = cv2.perspectiveTransform(np.array([[pt1]], dtype=np.float32), homography_matrix)[0][0]
real_pt2 = cv2.perspectiveTransform(np.array([[pt2]], dtype=np.float32), homography_matrix)[0][0]
distance = calculate_distance(real_pt1, real_pt2)
lines.append({'points': (pt1, pt2), 'distance': distance})
print(f"Line drawn between {pt1} and {pt2} with real-world distance {distance:.2f} units")
else:
# Fallback to pixel distance if homography not set
distance = calculate_distance(pt1, pt2)
lines.append({'points': (pt1, pt2), 'distance': distance})
print(f"Line drawn between {pt1} and {pt2} with pixel distance {distance:.2f}px")
line_mode_selected_points = [] # Reset after drawing
redraw_image()
else:
print("No point near the click to select for line.")
elif mode == 'remove_line' and event == cv2.EVENT_LBUTTONDOWN:
# Attempt to remove a line near the click
for idx, line in enumerate(lines):
pt1, pt2 = line['points']
if is_near_line((img_x, img_y), pt1, pt2):
print(f"Line removed between {pt1} and {pt2} with distance {line['distance']:.2f}")
lines.pop(idx)
redraw_image()
break
else:
print("No line found near the click to remove.")
4. Update the Toolbar Drawing Function to Include Reference Mode Indicator
def draw_toolbar(img):
for idx, button in enumerate(buttons):
x_start = button_margin + idx * (button_width + button_margin)
y_start = 5
# Draw button rectangle
cv2.rectangle(img, (x_start, y_start),
(x_start + button_width, y_start + button_height),
button["color"], -1)
# Highlight the selected mode button
if button["label"].lower().replace(" ", "_") == mode:
cv2.rectangle(img, (x_start, y_start),
(x_start + button_width, y_start + button_height),
(0, 255, 0), 3)
# Put button label
text_size = cv2.getTextSize(button["label"], cv2.FONT_HERSHEY_SIMPLEX, 0.6, 2)[0]
text_x = x_start + (button_width - text_size[0]) // 2
text_y = y_start + (button_height + text_size[1]) // 2
cv2.putText(img, button["label"], (text_x, text_y),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 0), 2)
# If in reference mode, display instruction
if reference_mode and len(ref_points_image) < 4:
cv2.putText(img, f"Select reference point {len(ref_points_image)+1}/4",
(original_image.shape[1] - 300, toolbar_height - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 255), 2)
5. Update the Redraw Function to Display Real-World Distances
def redraw_image():
display_img = window_image.copy()
draw_toolbar(display_img)
# Display current mouse position
if current_mouse_position != (-1, -1):
cv2.putText(display_img, f"Mouse: {current_mouse_position}", (10, toolbar_height - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 1)
# Draw all saved lines
for line in lines:
pt1, pt2, distance = line['points'][0], line['points'][1], line['distance']
adjusted_pt1 = (pt1[0], pt1[1] + toolbar_height)
adjusted_pt2 = (pt2[0], pt2[1] + toolbar_height)
cv2.line(display_img, adjusted_pt1, adjusted_pt2, (255, 0, 0), 2)
# Calculate midpoint for distance text
mid_point = ((pt1[0] + pt2[0]) // 2, (pt1[1] + pt2[1]) // 2)
adjusted_mid_point = (mid_point[0], mid_point[1] + toolbar_height)
if homography_matrix is not None:
cv2.putText(display_img, f"{distance:.2f} units", adjusted_mid_point,
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 255), 2)
else:
cv2.putText(display_img, f"{distance:.2f}px", adjusted_mid_point,
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 255), 2)
# If in line mode and two points are selected, draw temporary line
if mode == 'line' and len(line_mode_selected_points) == 2:
temp_pt1 = (line_mode_selected_points[0][0],
line_mode_selected_points[0][1] + toolbar_height)
temp_pt2 = (line_mode_selected_points[1][0],
line_mode_selected_points[1][1] + toolbar_height)
cv2.line(display_img, temp_pt1, temp_pt2, (0, 0, 255), 2)
# Draw points
for idx, point in enumerate(points):
adjusted_point = (point[0], point[1] + toolbar_height)
if idx == selected_point:
cv2.circle(display_img, adjusted_point, point_radius + 3, (0, 0, 255), -1) # Highlight selected point
cv2.circle(display_img, adjusted_point, point_radius, (0, 255, 0), -1)
# Draw reference points if any
for i, pt in enumerate(ref_points_image):
adjusted_pt = (pt[0], pt[1] + toolbar_height)
cv2.circle(display_img, adjusted_pt, point_radius, (0, 0, 255), -1)
cv2.putText(display_img, f"R{i+1}", (pt[0] + 10, pt[1] + toolbar_height - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1)
cv2.imshow("Image", display_img)
6. Update the Distance Calculation Function to Handle Real-World Distances
Modify the calculate_distance function to accept real-world points.
def calculate_distance(pt1, pt2):
return math.hypot(pt2[0] - pt1[0], pt2[1] - pt1[1])
(No changes needed; function already suitable)
7. Update Final Output to Show Real-World Distances
Modify the final print statements to display real-world distances.
# After the main loop
print("\nFinal Selected Points (x, y):")
for i, point in enumerate(points):
print(f"Point {i + 1}: {point}")
if homography_matrix is not None:
real_pt = cv2.perspectiveTransform(np.array([[point]], dtype=np.float32), homography_matrix)[0][0]
print(f" Real-world coordinates: ({real_pt[0]:.2f}, {real_pt[1]:.2f})")
print("\nFinal Drawn Lines:")
for i, line in enumerate(lines):
pt1, pt2, distance = line['points'][0], line['points'][1], line['distance']
if homography_matrix is not None:
real_pt1 = cv2.perspectiveTransform(np.array([[pt1]], dtype=np.float32), homography_matrix)[0][0]
real_pt2 = cv2.perspectiveTransform(np.array([[pt2]], dtype=np.float32), homography_matrix)[0][0]
print(f"Line {i + 1}: ({real_pt1[0]:.2f}, {real_pt1[1]:.2f}) to ({real_pt2[0]:.2f}, {real_pt2[1]:.2f}) - Distance: {distance:.2f} units")
else:
print(f"Line {i + 1}: ({pt1[0]}, {pt1[1]}) to ({pt2[0]}, {pt2[1]}) - Distance: {distance:.2f}px")
8. Update Instructions for the User
Ensure the user knows how to set reference points.
print("Interactive Point and Line Editor with OpenCV")
print("-------------------------------------------------")
print("Use the toolbar buttons to switch modes:")
print("Add - Add a new point")
print("Delete - Delete an existing point")
print("Move - Move an existing point")
print("Line - Draw a line between two points and show distance")
print("Remove Line - Remove a line by clicking near it")
print("Set Reference - Define reference points for real-world scaling")
print("Clear - Clear all points, lines, and references")
print("Quit - Exit the application")
print("-------------------------------------------------")
Workflow Summary
-
Set Reference Points:
- Click the "Set Reference" button on the toolbar.
- Click four points on the image corresponding to known real-world coordinates.
- For each clicked point, input the real-world X and Y coordinates when prompted.
- The application computes the homography matrix, enabling real-world distance calculations.
-
Add Points and Draw Lines:
- Switch to "Add" mode to add new points.
- Switch to "Line" mode to draw lines between points. The distances shown will be in real-world units if the homography is set; otherwise, in pixels.
-
Manage Points and Lines:
- Use "Delete", "Move", and "Remove Line" modes to manage points and lines.
- Use "Clear" to reset all data.
-
Exit Application:
- Click the "Quit" button or press 'q' to exit.
Considerations and Tips
-
Planar Assumption: Homography assumes that the scene is planar. Ensure that the reference points lie on the same plane.
-
Accuracy of Reference Points: The precision of real-world distances depends on the accurate selection of reference points and their corresponding real-world coordinates.
-
Camera Calibration: For more accurate results, especially in non-planar scenes, consider performing camera calibration to obtain intrinsic parameters.
-
User Input: When setting reference points, ensure that the real-world coordinates are entered correctly to avoid scaling errors.
-
Scale Units: Decide on the unit of measurement (e.g., meters, centimeters) and ensure consistency when entering real-world coordinates.
Complete Updated Code
Below is the complete updated code incorporating the real-world distance calculation using homography.
import cv2
import numpy as np
import math
# Load the image
image_path = "output_folder/20241027_092609_tp00004/frame_0000.jpg"
original_image = cv2.imread(image_path)
if original_image is None:
print("Error: Image not found or unable to load.")
exit()
# Constants for the toolbar
toolbar_height = 60
button_width = 120
button_height = 50
button_margin = 10
# Define button properties: (label, color)
buttons = [
{"label": "Add", "color": (200, 200, 200)},
{"label": "Delete", "color": (200, 200, 200)},
{"label": "Move", "color": (200, 200, 200)},
{"label": "Line", "color": (200, 200, 200)},
{"label": "Remove Line", "color": (200, 200, 200)},
{"label": "Clear", "color": (200, 200, 200)},
{"label": "Set Reference", "color": (200, 200, 200)}, # New Button
{"label": "Quit", "color": (200, 200, 200)}
]
# Calculate window size to include toolbar
toolbar = np.ones((toolbar_height, original_image.shape[1], 3), dtype=np.uint8) * 50 # Dark gray toolbar
window_image = np.vstack((toolbar, original_image.copy()))
# Initialize variables
points = []
lines = [] # List to store lines with their endpoints and distance
selected_point = -1 # Index of the selected point, if any
mode = 'add' # Default mode; can be 'add', 'delete', 'move', 'line', 'remove_line', 'set_reference'
point_radius = 7 # Increased radius for better hit detection
line_mode_selected_points = [] # To store two points for line drawing
current_mouse_position = (-1, -1) # To store current mouse position
# Homography related variables
homography_matrix = None
ref_points_image = []
ref_points_real = [] # User should input real-world coordinates for these points
reference_mode = False
# Function to draw buttons on the toolbar
def draw_toolbar(img):
for idx, button in enumerate(buttons):
x_start = button_margin + idx * (button_width + button_margin)
y_start = 5
# Draw button rectangle
cv2.rectangle(img, (x_start, y_start),
(x_start + button_width, y_start + button_height),
button["color"], -1)
# Highlight the selected mode button
if button["label"].lower().replace(" ", "_") == mode:
cv2.rectangle(img, (x_start, y_start),
(x_start + button_width, y_start + button_height),
(0, 255, 0), 3)
# Put button label
text_size = cv2.getTextSize(button["label"], cv2.FONT_HERSHEY_SIMPLEX, 0.6, 2)[0]
text_x = x_start + (button_width - text_size[0]) // 2
text_y = y_start + (button_height + text_size[1]) // 2
cv2.putText(img, button["label"], (text_x, text_y),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 0), 2)
# If in reference mode, display instruction
if reference_mode and len(ref_points_image) < 4:
cv2.putText(img, f"Select reference point {len(ref_points_image)+1}/4",
(original_image.shape[1] - 300, toolbar_height - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 255), 2)
# Function to calculate distance between two points
def calculate_distance(pt1, pt2):
return math.hypot(pt2[0] - pt1[0], pt2[1] - pt1[1])
# Function to check if a click is near a line
def is_near_line(click_pt, line_pt1, line_pt2, tolerance=10):
# Calculate distance from click_pt to the line
x0, y0 = click_pt
x1, y1 = line_pt1
x2, y2 = line_pt2
numerator = abs((y2 - y1)*x0 - (x2 - x1)*y0 + x2*y1 - y2*x1)
denominator = math.hypot(y2 - y1, x2 - x1)
if denominator == 0:
return False
distance = numerator / denominator
return distance <= tolerance
# Function to redraw points, lines, and toolbar on the image
def redraw_image():
display_img = window_image.copy()
draw_toolbar(display_img)
# Display current mouse position
if current_mouse_position != (-1, -1):
cv2.putText(display_img, f"Mouse: {current_mouse_position}", (10, toolbar_height - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 1)
# Draw all saved lines
for line in lines:
pt1, pt2, distance = line['points'][0], line['points'][1], line['distance']
adjusted_pt1 = (pt1[0], pt1[1] + toolbar_height)
adjusted_pt2 = (pt2[0], pt2[1] + toolbar_height)
cv2.line(display_img, adjusted_pt1, adjusted_pt2, (255, 0, 0), 2)
# Calculate midpoint for distance text
mid_point = ((pt1[0] + pt2[0]) // 2, (pt1[1] + pt2[1]) // 2)
adjusted_mid_point = (mid_point[0], mid_point[1] + toolbar_height)
if homography_matrix is not None:
cv2.putText(display_img, f"{distance:.2f} units", adjusted_mid_point,
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 255), 2)
else:
cv2.putText(display_img, f"{distance:.2f}px", adjusted_mid_point,
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 255), 2)
# If in line mode and two points are selected, draw temporary line
if mode == 'line' and len(line_mode_selected_points) == 2:
temp_pt1 = (line_mode_selected_points[0][0],
line_mode_selected_points[0][1] + toolbar_height)
temp_pt2 = (line_mode_selected_points[1][0],
line_mode_selected_points[1][1] + toolbar_height)
cv2.line(display_img, temp_pt1, temp_pt2, (0, 0, 255), 2)
# Draw points
for idx, point in enumerate(points):
adjusted_point = (point[0], point[1] + toolbar_height)
if idx == selected_point:
cv2.circle(display_img, adjusted_point, point_radius + 3, (0, 0, 255), -1) # Highlight selected point
cv2.circle(display_img, adjusted_point, point_radius, (0, 255, 0), -1)
# Draw reference points if any
for i, pt in enumerate(ref_points_image):
adjusted_pt = (pt[0], pt[1] + toolbar_height)
cv2.circle(display_img, adjusted_pt, point_radius, (0, 0, 255), -1)
cv2.putText(display_img, f"R{i+1}", (pt[0] + 10, pt[1] + toolbar_height - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1)
cv2.imshow("Image", display_img)
# Mouse callback function
def handle_mouse(event, x, y, flags, param):
global selected_point, points, mode, line_mode_selected_points
global current_mouse_position, lines
global homography_matrix, ref_points_image, ref_points_real, reference_mode
# Update current mouse position
if y > toolbar_height:
img_x, img_y = x, y - toolbar_height
current_mouse_position = (img_x, img_y)
else:
current_mouse_position = (-1, -1)
if y <= toolbar_height:
# Click is on the toolbar
if event == cv2.EVENT_LBUTTONDOWN:
for idx, button in enumerate(buttons):
x_start = button_margin + idx * (button_width + button_margin)
y_start = 5
x_end = x_start + button_width
y_end = y_start + button_height
if x_start <= x <= x_end and y_start <= y <= y_end:
label = button["label"].lower().replace(" ", "_")
if label == 'add':
mode = 'add'
reference_mode = False
elif label == 'delete':
mode = 'delete'
reference_mode = False
elif label == 'move':
mode = 'move'
reference_mode = False
elif label == 'line':
mode = 'line'
line_mode_selected_points = []
reference_mode = False
elif label == 'remove_line':
mode = 'remove_line'
reference_mode = False
elif label == 'clear':
points.clear()
lines.clear()
line_mode_selected_points = []
selected_point = -1
homography_matrix = None
ref_points_image = []
ref_points_real = []
print("All points, lines, and references cleared.")
reference_mode = False
elif label == 'set_reference':
mode = 'set_reference'
reference_mode = True
ref_points_image = []
ref_points_real = []
print("Reference mode activated. Please select four reference points.")
elif label == 'quit':
cv2.destroyAllWindows()
exit()
print(f"Mode: {mode.replace('_', ' ').capitalize()}")
redraw_image()
return # Exit after handling button click
else:
# Click is on the image
if img_x < 0 or img_y < 0 or img_y >= original_image.shape[0] or img_x >= original_image.shape[1]:
return # Click outside the image area
if reference_mode:
if event == cv2.EVENT_LBUTTONDOWN:
if len(ref_points_image) < 4:
ref_points_image.append((img_x, img_y))
print(f"Reference image point {len(ref_points_image)}: {ref_points_image[-1]}")
try:
# Prompt user to input real-world coordinates
real_x = float(input(f"Enter real-world X for reference point {len(ref_points_real)+1}: "))
real_y = float(input(f"Enter real-world Y for reference point {len(ref_points_real)+1}: "))
ref_points_real.append((real_x, real_y))
except ValueError:
print("Invalid input. Please enter numerical values.")
ref_points_image.pop() # Remove last added point due to invalid input
return
if len(ref_points_image) == 4 and len(ref_points_real) == 4:
# Compute Homography
src_pts = np.array(ref_points_image, dtype=np.float32)
dst_pts = np.array(ref_points_real, dtype=np.float32)
homography_matrix, status = cv2.findHomography(src_pts, dst_pts)
if homography_matrix is not None:
print("Homography matrix computed successfully.")
else:
print("Error computing homography matrix.")
reference_mode = False
redraw_image()
else:
print("Already selected four reference points.")
return # Exit after handling reference point click
# Proceed with regular modes
if mode == 'add' and event == cv2.EVENT_LBUTTONDOWN:
# Add a new point
points.append((img_x, img_y))
print(f"Point added at: ({img_x}, {img_y})")
redraw_image()
elif mode == 'delete' and event == cv2.EVENT_LBUTTONDOWN:
# Delete point if close to it
for i, point in enumerate(points):
distance_sq = (img_x - point[0]) ** 2 + (img_y - point[1]) ** 2
if distance_sq <= (point_radius * 2) ** 2: # Increased area for better hit detection
print(f"Point deleted at: {points[i]}")
points.pop(i)
# Also remove any lines connected to this point
lines[:] = [line for line in lines if line['points'][0] != point and line['points'][1] != point]
break
redraw_image()
elif mode == 'move':
if event == cv2.EVENT_LBUTTONDOWN:
# Select the point if close to it
for i, point in enumerate(points):
distance_sq = (img_x - point[0]) ** 2 + (img_y - point[1]) ** 2
if distance_sq <= (point_radius * 2) ** 2:
selected_point = i
print(f"Selected point {i + 1} for moving.")
break
elif event == cv2.EVENT_MOUSEMOVE and selected_point != -1 and flags & cv2.EVENT_FLAG_LBUTTON:
# Update the position of the selected point
points[selected_point] = (img_x, img_y)
redraw_image()
elif event == cv2.EVENT_LBUTTONUP:
# Release the point
if selected_point != -1:
print(f"Point {selected_point + 1} moved to: {points[selected_point]}")
selected_point = -1
redraw_image()
elif mode == 'line':
if event == cv2.EVENT_LBUTTONDOWN:
# Select two points to draw a line
clicked_point = None
for point in points:
distance_sq = (img_x - point[0]) ** 2 + (img_y - point[1]) ** 2
if distance_sq <= (point_radius * 2) ** 2:
clicked_point = point
break
if clicked_point:
# Avoid selecting the same point twice
if clicked_point not in line_mode_selected_points:
line_mode_selected_points.append(clicked_point)
print(f"Point selected for line: {clicked_point}")
else:
print("Same point selected. Please select a different point.")
if len(line_mode_selected_points) == 2:
pt1, pt2 = line_mode_selected_points
if homography_matrix is not None:
# Map to real-world coordinates
real_pt1 = cv2.perspectiveTransform(np.array([[pt1]], dtype=np.float32), homography_matrix)[0][0]
real_pt2 = cv2.perspectiveTransform(np.array([[pt2]], dtype=np.float32), homography_matrix)[0][0]
distance = calculate_distance(real_pt1, real_pt2)
lines.append({'points': (pt1, pt2), 'distance': distance})
print(f"Line drawn between {pt1} and {pt2} with real-world distance {distance:.2f} units")
else:
# Fallback to pixel distance if homography not set
distance = calculate_distance(pt1, pt2)
lines.append({'points': (pt1, pt2), 'distance': distance})
print(f"Line drawn between {pt1} and {pt2} with pixel distance {distance:.2f}px")
line_mode_selected_points = [] # Reset after drawing
redraw_image()
else:
print("No point near the click to select for line.")
elif mode == 'remove_line' and event == cv2.EVENT_LBUTTONDOWN:
# Attempt to remove a line near the click
for idx, line in enumerate(lines):
pt1, pt2 = line['points']
if is_near_line((img_x, img_y), pt1, pt2):
if homography_matrix is not None:
print(f"Line removed between {pt1} and {pt2} with distance {line['distance']:.2f} units")
else:
print(f"Line removed between {pt1} and {pt2} with distance {line['distance']:.2f}px")
lines.pop(idx)
redraw_image()
break
else:
print("No line found near the click to remove.")
# Display instructions in the console
print("Interactive Point and Line Editor with OpenCV")
print("-------------------------------------------------")
print("Use the toolbar buttons to switch modes:")
print("Add - Add a new point")
print("Delete - Delete an existing point")
print("Move - Move an existing point")
print("Line - Draw a line between two points and show distance")
print("Remove Line - Remove a line by clicking near it")
print("Set Reference - Define reference points for real-world scaling")
print("Clear - Clear all points, lines, and references")
print("Quit - Exit the application")
print("-------------------------------------------------")
# Initial drawing
redraw_image()
# Set up OpenCV window and callback
cv2.namedWindow("Image")
cv2.setMouseCallback("Image", handle_mouse)
# Main loop
while True:
key = cv2.waitKey(1) & 0xFF
# Optionally, you can handle keyboard shortcuts here
if key == ord('q'):
break
# Close OpenCV windows
cv2.destroyAllWindows()
# Print all selected points and lines
print("\nFinal Selected Points (x, y):")
for i, point in enumerate(points):
print(f"Point {i + 1}: {point}")
if homography_matrix is not None:
real_pt = cv2.perspectiveTransform(np.array([[point]], dtype=np.float32), homography_matrix)[0][0]
print(f" Real-world coordinates: ({real_pt[0]:.2f}, {real_pt[1]:.2f})")
print("\nFinal Drawn Lines:")
for i, line in enumerate(lines):
pt1, pt2, distance = line['points'][0], line['points'][1], line['distance']
if homography_matrix is not None:
real_pt1 = cv2.perspectiveTransform(np.array([[pt1]], dtype=np.float32), homography_matrix)[0][0]
real_pt2 = cv2.perspectiveTransform(np.array([[pt2]], dtype=np.float32), homography_matrix)[0][0]
print(f"Line {i + 1}: ({real_pt1[0]:.2f}, {real_pt1[1]:.2f}) to ({real_pt2[0]:.2f}, {real_pt2[1]:.2f}) - Distance: {distance:.2f} units")
else:
print(f"Line {i + 1}: ({pt1[0]}, {pt1[1]}) to ({pt2[0]}, {pt2[1]}) - Distance: {distance:.2f}px")
Usage Guide
-
Start the Application:
- Run the updated script. The image along with the toolbar will appear.
-
Set Reference Points:
- Click the "Set Reference" button on the toolbar.
- Click four distinct points on the image that lie on the same plane and whose real-world coordinates you know.
- After each click, input the corresponding real-world X and Y coordinates when prompted in the console.
- Once four points are set, the application computes the homography matrix.
-
Add Points:
- Click the "Add" button.
- Click on the image to add points whose real-world positions you want to measure.
-
Draw Lines and Measure Distances:
- Click the "Line" button.
- Select two points by clicking near them on the image.
- The application draws a line between them and displays the calculated real-world distance.
-
Manage Points and Lines:
- Use the "Delete", "Move", and "Remove Line" buttons to manage existing points and lines.
- Use the "Clear" button to reset all points, lines, and references.
-
Exit the Application:
- Click the "Quit" button or press 'q' on the keyboard.
Conclusion
By incorporating homography into your OpenCV application, you can accurately translate pixel distances into real-world units, accounting for rotation, perspective, and other transformations. This enhancement allows for robust measurements within the scene, making your tool versatile for various applications such as mapping, surveying, and spatial analysis.
Feel free to further customize the application, such as adding validations, supporting different units of measurement, or enhancing the user interface for a more seamless experience.