本文思路及用途如下:
由于用ObjectMaker程序会产生带有目标ROI信息的txt文件(即txt中内容为:XXXXXX.jpg 1 19 21 50 50)
其中XXXXXX.jpg为图像名,1为该图包含一个目标,其中目标的坐标信息为:左上角x=19,y=21,目标框width=50,height=50;
由于txt中包含成千上万张图像及对应目标信息;所以本程序旨在批量从原图中裁出目标ROI区域的图像并保存。
PS:在做正样本时,其实不必非要裁剪目标,作者这么做有别的用途。

以下程序有待改进,效果还算可行。建议用python写处理会快。
#include "stdafx.h"
#include "cv.h"
#include "cvaux.h"
#include "highgui.h"
// for filelisting
#include <stdio.h>
#include <io.h>
// for fileoutput
#include <string>
#include <fstream>
#include <sstream>
#include<iostream>
using namespace std;
#define MAX_LINE 1024
string st;
string strPrefix;
IplImage* img;
IplImage* dst;
CvRect rect;
using namespace cv;
int num; //每张图像包含目标总数
int main()
{
char buf[MAX_LINE]; /*缓冲区*/
char *p;
char *split = " ";
char b[MAX_LINE][500];
int roi[100];
char outputImageName[20];
FILE *fp; /*文件指针*/
int len; /*行字符个数*/
if ((fp = fopen("带目标的文档.txt", "r")) == NULL) //打开包含目标的txt文件,格式如上面描述
{
perror("fail to read");
exit(1);
}
while (fgets(buf, MAX_LINE, fp) != NULL)
{
int k = 0, z = 0, d = 0;
len = strlen(buf);
buf[len - 1] = '\0'; /*去掉换行符*/
st = buf;
int j=st.find(".");
num = int(buf[j + 5] - '0'); //输出每张图中框选目标总数
printf("%d \n", num);
printf("%s %d \n", buf, len - 1);
p = strtok(buf,split); //用于分割第一个空格前面的图片名称
char*picName = p;
strPrefix = "原图像序列集/";
strPrefix += p;
img= cvLoadImage(strPrefix.data(), 1);
while ((p = strtok(NULL, split)))
{
strcpy(b[k++], p);
}
for (z = 0; z < k; printf("%s ", b[z++]));
int index = 0;
for (z = 1; z < k;z++ )
{
long int m = 0, o = 0;
while (b[z][m])
{
o = o * 10 + b[z][m] - '0';
m++;
}
roi[index] = o;
printf("%d ", roi[index]);
index++;
}
printf("\n");
rect.x = roi[0];
rect.y = roi[1];
rect.width = roi[2];
rect.height = roi[3];
dst= cvCreateImage(cvSize(rect.width, rect.height), 8, 3);//创建图像空间
if (num) {
cvSetImageROI(img, rect);
cvCopy(img, dst);
cvResetImageROI(img);
//cvShowImage("test", dst);
sprintf(outputImageName, "%s%d%s", picName,d++, ".jpg");
cvSaveImage(outputImageName,dst);
//int iKey = cvWaitKey(10);
/*num--;*/
}
cvReleaseImage(&dst);
//cvDestroyWindow("test");
}
system("pause");
cvReleaseImage(&img);
return 0;
}