#include
#include
using namespace cv;
Mat mask, img1, img2;
//全局变量
Mat g_ImageROI;
Mat g_ImageROI1;
Rect g_rectangle;
Point g_startPoint;
Mat g_srcImage;
RNG g_rng(12345);
bool click_flag = 0;
void onMouse(int event, int x, int y, int flags, void* param)
{
//鼠标移动事件
if (event == EVENT_MOUSEMOVE)
{
if (click_flag == 1)
{
g_rectangle.x = MIN(g_startPoint.x, x);
g_rectangle.y = MIN(g_startPoint.y, y);
g_rectangle.width = abs(x - g_startPoint.x);
g_rectangle.height = abs(y - g_startPoint.y);
g_rectangle = g_rectangle & Rect(0, 0, g_srcImage.cols, g_srcImage.rows);
}
}
//左键按下事件
if (event == EVENT_LBUTTONDOWN)
{
g_startPoint.x = x;
g_startPoint.y = y;
click_flag = 1;
}
//左键弹起事件
if (event == EVENT_LBUTTONUP)
{
click_flag = 0;
//显示感兴趣区域的图片
g_ImageROI = g_srcImage(g_rectangle);
//g_ImageROI1 = g_srcImage(g_rectangle);
//namedWindow("截取的图片", 0);
//imshow("截取的图片", g_ImageROI);
mask = Mat::zeros(g_srcImage.size(), CV_8UC1);
mask(g_rectangle).setTo(255);
img1 = g_srcImage(g_rectangle);
g_srcImage.copyTo(img2, mask);
cv::Mat img_gray{};
cv::cvtColor(img2, img_gray, cv::COLOR_RGB2GRAY);
//使用高斯滤波
cv::GaussianBlur(img_gray, img_gray, cv::Size(3, 3), 0, 0, cv::BORDER_DEFAULT);
//使用canny算子
double threshold1 = 120.0;
double threshold2 = 55.0;
int apertureSize = 3;
cv::Canny(img_gray, img_gray, threshold1, threshold2, apertureSize);
//imshow("mask", mask);
//imshow("img2", img2);
cv::imshow("Canny", img_gray);
}
}
void main()
{
namedWindow("摄像头", 0);
setMouseCallback("摄像头", onMouse);
g_srcImage = imread("0001.jpg");
//画矩形,边框随机颜色
rectangle(g_srcImage, g_rectangle, cv::Scalar(g_rng.uniform(0, 255), g_rng.uniform(0, 255), g_rng.uniform(0, 255)), 3);
imshow("摄像头", g_srcImage);
waitKey(0);
}