#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; }