利用opencv剪切图片

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/leng0yan/article/details/79977878

最近在做目标识别分类相关工作,有的数据集使用了BBox标注,而给的图片是原图,就需要将数据集中的图片根据BBox的标注重新剪切,生成新的数据集,下面是利用opencv来剪切图片的代码:

#include <opencv2/opencv.hpp>
#include<iostream>
using namespace std;
using namespace cv;
//分割字符串
void SplitString(const string& s, vector<string>& v, const string& c)
{
    string::size_type pos1, pos2;
    pos2 = s.find(c);
    pos1 = 0;
    while (string::npos != pos2)
    {
        v.push_back(s.substr(pos1, pos2 - pos1));

        pos1 = pos2 + c.size();
        pos2 = s.find(c, pos1);
    }
    if (pos1 != s.length())
        v.push_back(s.substr(pos1));
}
//切割,保存图片
void cut(string path,string path_out,int x,int y,int wigh,int high) {
    Mat img = imread(path, 1);
    Mat imgout = img(Rect(x, y, wigh, high));
    imwrite(path_out,imgout);
//  imshow("imgout", imgout);
}
int main(int argc, char* argv[])
{

    ifstream fin("F://dateset//Stanford car dataset//demo.txt");//demo.txt里面保存的是图片名称,BBox的四个坐标
    string s;
    string path;
    string path_out;
    int x1;
    int y1;
    int x2;
    int y2;
    while (getline(fin, s))
    {
        vector<string> v;
        SplitString(s, v, ","); 
        for (vector<string>::size_type i = 0; i != v.size(); ++i) {
            path = "F://dateset//Stanford car dataset//" + (string)v[0];
            path_out = "F://dateset//Stanford car dataset//car//"+ (string)v[0];
            x1 = atoi(v[1].c_str());
            y1 = atoi(v[2].c_str());
            x2 = atoi(v[3].c_str());
            y2 = atoi(v[4].c_str());
        }
        cout << path_out << endl;
        cut(path,path_out, x1, y1, x2 - x1, y2 - y1);
    //  Mat img = imread(path, 1);
    //  imshow("img",img);
    //  imwrite(path_out, img);
    //  waitKey(0);
    }
}
阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页