【分类器训练——样本准备】读文件夹下的图像序列,批量裁剪txt中ROI区域并保存图像

本文思路及用途如下:
由于用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;
	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值