OpenCv:如何保存Mat::Rect到文件



我将相机图像捕获到图像中。我从图像中选择对象并跟踪对象。但我想把选择保存到文件中因为我不想每次都选择对象。这是我的选区;

Mat image;
Rect selection;
selection.x = MIN(x, origin.x);
selection.y = MIN(y, origin.y);
selection.width = abs(x - origin.x);
selection.height = abs(y - origin.y);
selection &= Rect(0, 0, image.cols, image.rows);

如何保存选择或如何第一次选择对象?谢谢你

不能直接使用FileStorage存储Rect,但可以存储x, y, widthheight的整数值。

写文件:
Rect rect;
// ... init your Rect
FileStorage fs("rect.yml", FileStorage::WRITE);
if( fs.isOpened() ){
    fs << "x" << rect.x << "y" << rect.y;
    fs << "width" << rect.width << "height" << rect.height;
    fs.release();
}
else cout << "Error: can not save the rectn";

读取文件

Rect rect;
FileStorage fs("rect.yml", FileStorage::READ);
if( fs.isOpened() ){
    fs["x"] >> rect.x;
    fs["y"] >> rect.y;
    fs["width"] >> rect.width;
    fs["height"] >> rect.height;
}
else cout << "Error: can not load the rectn";

尝试OpenCV文件存储来保存矩形。或者如果你想保存图片的选定部分,然后使用cv::Mat roi构造函数,然后使用cv::imwrite保存。

最新更新