如何读取并固定图像,手动绘制ROI矩形并获取其坐标?
Hey there! Let's tackle this interactive ROI selection task with OpenCV step by step. You've already got the image reading part sorted, so we'll build on that to add the rectangle drawing, coordinate output, and persistent ROI marking functionality.
Solution for Interactive ROI Selection
Here's a complete, ready-to-use implementation that meets all your requirements:
import cv2 import numpy as np # Global variables to track mouse actions and ROI data drawing = False # Tracks if mouse button is held down start_x, start_y = -1, -1 final_roi = [] def roi_drawing_callback(event, x, y, flags, param): global drawing, start_x, start_y, img, final_roi if event == cv2.EVENT_LBUTTONDOWN: # Triggered when left mouse button is pressed down drawing = True start_x, start_y = x, y elif event == cv2.EVENT_MOUSEMOVE: # Draw a temporary rectangle while dragging the mouse if drawing: temp_img = img.copy() cv2.rectangle(temp_img, (start_x, start_y), (x, y), (0, 255, 0), 2) cv2.imshow('Image with ROI', temp_img) elif event == cv2.EVENT_LBUTTONUP: # Finalize the ROI when mouse button is released drawing = False # Draw permanent green rectangle on the original image cv2.rectangle(img, (start_x, start_y), (x, y), (0, 255, 0), 2) cv2.imshow('Image with ROI', img) # Store and print the ROI coordinates final_roi = [(start_x, start_y), (x, y)] print(f"ROI Coordinates: Top-left {final_roi[0]}, Bottom-right {final_roi[1]}") # Load your image (replace with your actual file path) img = cv2.imread('/path/to/your/image.jpg') # Keep a copy of the original image for reset functionality (optional) original_img = img.copy() # Create display window and attach the mouse callback cv2.namedWindow('Image with ROI') cv2.setMouseCallback('Image with ROI', roi_drawing_callback) # Main loop to keep the image window open while True: cv2.imshow('Image with ROI', img) key = cv2.waitKey(1) & 0xFF # Press 'q' to close the window and exit if key == ord('q'): break # Press 'r' to reset the image and start over (optional) elif key == ord('r'): img = original_img.copy() final_roi = [] # Clean up all OpenCV windows cv2.destroyAllWindows()
Key Details & Usage Tips
- Mouse Interaction:
- Click and drag your left mouse button to draw a rectangle around your ROI
- Release the button to lock in the rectangle – it will stay on the image permanently
- Controls:
- Press
qto exit the program - Press
rto reset the image and draw a new ROI if you make a mistake
- Press
- Coordinate Output: As soon as you finalize the rectangle, the top-left and bottom-right coordinates will print to your console, ready for further use
This implementation is lightweight, intuitive, and keeps your ROI visible while giving you precise coordinate data for whatever you need to do next!
内容的提问来源于stack exchange,提问作者Jess
相关产品推荐
相关产品推荐

