标识训练数据,生成文件索引程序

#include <iostream>
#include "opencv2/opencv.hpp"

#define SAMPLE_NUM 31

CvRect rect;
bool bDrawFlag=false;
IplImage * g_image = NULL;
bool bIsMark = false;

void Draw_Box(void * param)
{
	CvPoint pt1;
	pt1.x = rect.x;
	pt1.y = rect.y;

	CvPoint pt2;
	pt2.x = rect.x+rect.width;
	pt2.y = rect.y+rect.height;

	cvRectangle(param,pt1,pt2,cvScalar(0,0,255));

	cvShowImage("img", param);
	cvWaitKey(1);
}

void OnMouse(int event,int x, int y, int flags,void *)
{
	
	switch(event)
	{
	case CV_EVENT_LBUTTONDOWN:

		printf("OnMouse ");

		rect.x = x;
		rect.y = y;
		rect.width = 0;
		rect.height = 0;

		bDrawFlag = true;
		break;
	case CV_EVENT_LBUTTONUP:

		if(rect.width < 0)
		{
			rect.width *= -1;
			rect.x = rect.x - rect.width;
		}

		if(rect.height < 0)
		{
			rect.height *= -1;
			rect.y = rect.y - rect.height;		
		}

		printf("rect x = %d, y = %d, width= %d, height = %d\n", rect.x,rect.y,rect.width,rect.height);
		Draw_Box(g_image);
		
		bDrawFlag = false;
		bIsMark = true;
		break;
	case CV_EVENT_MOUSEMOVE:
		rect.width = x-rect.x;
		rect.height = y -rect.y;

		break;

	default:
		break;
	}

	return;
}


int main(int argc, char * argv[])
{
	//CV_WINDOW_AUTOSIZE和CV_WINDOW_NORMAL只影响显示,并不影响获取矩形框的位置,矩形框的位置始终是根据原图大小获取的
	cvNamedWindow("RectAngle", CV_WINDOW_AUTOSIZE); 
	cvSetMouseCallback("RectAngle", OnMouse, 0);//设置回调函数对应的窗口

	//最终保存的样本索引文件,格式:文件名,样本个数,矩形框位置
	FILE *pFile = fopen("E:/train/neg/index.txt", "w+");	
	if(pFile == NULL)
		printf("write file open error!");
	
	
	//依次读1.bmp,2.bmp........
	char str[256];	
	for (int index = 0; index < SAMPLE_NUM; index++)
	{
		sprintf(str,"E:/train/neg/%d.bmp",index);
		printf("%s", str);

		g_image = (IplImage*)cvLoadImage(str);
		bIsMark = false;		
	
		if(bDrawFlag == true)
		{			
			Draw_Box(g_image);
		}

		cvShowImage("RectAngle",g_image);
		char c = cvWaitKey(0);
		if(27 == c){ break; }

		//写样本索引文件,格式:文件名,样本个数,矩形框位置
		sprintf(str,"%d.bmp",index);
		fwrite(str, strlen(str), 1,pFile);

		fwrite(" 1",2,1,pFile); //样本个数。默认都为1个

		//如果鼠标标示了矩形框,则为矩形框的位置,如果没有标示,矩形框为原图的大小
		if (true == bIsMark)
		{
			sprintf(str," %d %d %d %d",rect.x,rect.y,rect.width,rect.height);
			fwrite(str, strlen(str), 1,pFile);
		}
		else
		{
			sprintf(str," 0 0 %d %d",g_image->width-1, g_image->height-1);
			fwrite(str, strlen(str), 1,pFile);
		}		

		fwrite("\n",1,1,pFile);
	}

	fclose(pFile);
	cvReleaseImage(&g_image);

	return 0;
}



下面的例子是文件名为0.bmp,1.bmp.......,最终生成了文件索引neg.txt

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值