OpenCV鼠标操作(画红色方框截取图像)

Point sp(-1, -1);
Point ep(-1, -1);
Mat temp;
static void on_draw(int event, int x, int y, int flags,void *user_data)
{
  Mat image = *((Mat *)user_data);
  if (event == EVENT_LBUTTONDOWN)
  {
    sp.x = x;
    sp.y = y;
  }
  else if (event == EVENT_LBUTTONUP)
  {
    ep.x = x;
    ep.y = y;
    int dx = ep.x - sp.x;
    int dy = ep.y - sp.y;
    if (dx > 0 && dy > 0)
    {
      Rect rect(sp.x,sp.y,dx,dy);
      rectangle(image, rect, Scalar(0, 0, 255), 2, 8, 0);
      imshow("mouse_draw", image);
      imshow("roi", image(rect));
      sp.x = -1;
      sp.y = -1;
    }
  }
  else if (event == EVENT_MOUSEMOVE)
  {
    if (sp.x > 0 && sp.y > 0)
    {
      ep.x = x;
      ep.y = y;
      int dx = ep.x - sp.x;
      int dy = ep.y - sp.y;
      if (dx > 0 && dy > 0)
      {
        temp.copyTo(image);

        Rect rect(sp.x, sp.y, dx, dy);
        rectangle(image, rect, Scalar(0, 0, 255), 2, 8, 0);
        imshow("mouse_draw", image);
      }
    }
  }
}

void introduction::mouse_demo()
{
  QString appPath = QCoreApplication::applicationDirPath();
  imagePath = appPath + "/A.jpg";
  img = cv::imread(imagePath.toStdString());
  if (img.empty())
    return;
  temp = img.clone();
  namedWindow("mouse_draw", WINDOW_AUTOSIZE);
  setMouseCallback("mouse_draw", on_draw,(void*)(&img));

  imshow("mouse_draw", img);
}

推荐一个零声学院项目课,个人觉得老师讲得不错,分享给大家:
零声白金学习卡(含基础架构/高性能存储/golang云原生/音视频/Linux内核)
https://xxetb.xet.tech/s/3Zqhgt

你可能感兴趣的:(OpenCV学习,opencv,计算机外设,人工智能,C++)