用鼠标在OpenCV中画一个框(使用Mat而不是IplImage)



我正在尝试在OpenCV中的特定位置绘制一个框,以便我可以在那里裁剪它。 现在我正在尝试在我的感兴趣区域周围绘制一个重新分类,但我在mouseEvent()中的drawBox()中出现错误。 下面是我的代码,下面是错误输出。 我怎样才能让它工作? 我正在寻找的任何地方都有较旧的 IplImage 和其他已弃用的功能。

#include stuff
using namespace cv;
bool isDrawing = false;
Point start, end;
void drawBox(Point start, Point end, Mat& img){
Scalar color = (0,255,0);
rectangle(img, start, end, color, 1, 8, 0);
return;
}
void mouseEvent(int evt, int x, int y, int flags, void* param){
if(isDrawing){
    if(evt==CV_EVENT_LBUTTONUP){
        printf("up %d %dn",x,y);
        isDrawing = false;
        end.x = x;
        end.y = y;
        drawBox(start, end, (Mat&) param);
        return;
    }
}
else{
    if(evt==CV_EVENT_LBUTTONDOWN){
        printf("down %d %dn",x,y);
        isDrawing = true;
        start.x = x;
        start.y = y;
        return;
    }
}
}
int main(){
Mat feed = imread("C:/Users/Timo/Desktop/image1.jpg", CV_LOAD_IMAGE_GRAYSCALE);
namedWindow("Feed");
imshow("Feed", feed);
cvSetMouseCallback("Feed", mouseEvent, &feed);
waitKey(0);
return 1;
}

安慰

down 293 26
up 520 217
OpenCV Error: Assertion failed <cn <= 4> in unknown function, file ......srcopencvmodulescoresrcmatrix.cpp, line 845

弹出

Unhandled exception at 0x80000000 in opencv_project.exe: )xC0000005: Access violation.

输出日志

First-chance exception at 0x7796c41f in opencv_project.exe: Microsoft C++ exception: cv::Exception at memory location 0x002de9b4..
Unhandled exception at 0x7796c41f in opencv_project.exe: Microsoft C++ exception: cv::Exception at memory location 0x002de9b4..

问题是你传递了一个指向cvSetMouseCallback()的指针,然后试图将其视为引用。

您可以通过替换行来解决此问题

drawBox(start, end, (Mat&) param);

cv::Mat* image  = static_cast<cv::Mat *>(param);
drawBox(start, end, *image);

此外,要实际看到您绘制的框,您需要再次调用imshow(),即:

rectangle(img, start, end, color, 1, 8, 0);
imshow("Feed", img);

最新更新