You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何读取并固定图像,手动绘制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 q to exit the program
    • Press r to reset the image and draw a new ROI if you make a mistake
  • 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 07:59:32