鼠标在图片上画矩形(ROI)区域并保存ROI区域

#include <iostream>
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"

using namespace std;
using namespace cv;

bool draw;
Mat src;//原始图像  
Mat roi;//ROI图像
Mat run_roi;  //实时ROI
Mat img5;
Point cursor;//初始坐标   
Rect rect;//标记ROI的矩形框

		  /*
		  void onMouse(int event, int x, int y, int flags, void *param);
		  第一个参数,鼠标操作时间的整数代号,在opencv中,event鼠标事件总共有10中,从0-9依次代表如下:
		  EVENT_MOUSEMOVE      =0,    //滑动
		  EVENT_LBUTTONDOWN    =1,    //左键点击
		  EVENT_RBUTTONDOWN    =2,    //右键点击
		  EVENT_MBUTTONDOWN    =3,    //中间点击
		  EVENT_LBUTTONUP      =4,    //左键释放
		  EVENT_RBUTTONUP      =5,    //右键释放
		  EVENT_MBUTTONUP      =6,    //中间释放
		  EVENT_LBUTTONDBLCLK  =7,    //左键双击
		  EVENT_RBUTTONDBLCLK  =8,    //右键双击
		  EVENT_MBUTTONDBLCLK  =9     //中间释放
		  第二个参数,代表鼠标位于窗口的(x,y)坐标位
  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
OpenCV是一个开源的计算机视觉库。它提供了许多处理数字像和视频的函数,而其中之一就是画矩形ROI。 首先,要创建一个矩形ROI,需要知道需要截取的区域的左上角和右下角的坐标。可以使用OpenCV鼠标事件函数,在像上拖动鼠标选择需要截取的区域并获取该区域的坐标。 其次,使用cv2.rectangle函数将矩形绘制在像上。函数参数包括:原始像,矩形左上角坐标,矩形右下角坐标,颜色和线宽度。 最后,使用numpy的切片操作截取原始像中的ROI区域。切片的参数是左上角和右下角坐标,保持一致性。 示例程序如下: ```python import cv2 import numpy as np # Mouse callback function def draw_rect(event, x, y, flags, params): global x_init, y_init, drawing, top_left_pt, bottom_right_pt if event == cv2.EVENT_LBUTTONDOWN: drawing = True x_init, y_init = x, y elif event == cv2.EVENT_MOUSEMOVE: if drawing: top_left_pt = (min(x_init, x), min(y_init, y)) bottom_right_pt = (max(x_init, x), max(y_init, y)) img[y_init:y, x_init:x] = 255 - img[y_init:y, x_init:x] elif event == cv2.EVENT_LBUTTONUP: drawing = False top_left_pt = (min(x_init, x), min(y_init, y)) bottom_right_pt = (max(x_init, x), max(y_init, y)) img[y_init:y, x_init:x] = 255 - img[y_init:y, x_init:x] # MAIN SCRIPT drawing = False top_left_pt, bottom_right_pt = (-1, -1), (-1, -1) # Open image img = cv2.imread('test.png') copy = img.copy() # Create a window cv2.namedWindow("Window") # Set the mouse callback function to "draw_rect" cv2.setMouseCallback("Window", draw_rect) while True: cv2.imshow("Window", img) k = cv2.waitKey(1) & 0xFF # If "c" is pressed, reset the window if k == ord('c'): img = copy.copy() # If "r" is pressed, crop the ROI elif k == ord('r'): if top_left_pt != (-1, -1) and bottom_right_pt != (-1, -1): roi = copy[top_left_pt[1]:bottom_right_pt[1], top_left_pt[0]:bottom_right_pt[0]] cv2.imshow("ROI", roi) # If "q" is pressed, exit elif k == ord('q'): break cv2.destroyAllWindows() ``` 该程序允许用户在像上拖动鼠标选择需要截取的区域。在选择完区域后,按下“r”键就可以截取该区域并显示在一个新窗口中。按下“c”键可以重置窗口。如果想要结束程序,按下“q”键即可。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值