人脸VOC数据集制作

版权声明:guojawee https://blog.csdn.net/weixin_36750623/article/details/84782660

获取人脸框,写入txt

使用opencv自带的haar人脸检测器,将检测到的人脸,保存入txt中保存格式为 000002.png face 44 28 132 121

//运行环境OPENCV2.4.9 VS2012 WIN7X64
#include <opencv2\opencv.hpp>
#include <iostream>
#include <Windows.h>
#include <fstream>  //
#include <io.h>
#include <iostream>
using namespace std;
using namespace cv;

void AllImagePro(string src, string dst, static int number);
void detectAndCut(Mat img, string dir, string filename);
char* WcharToChar(const wchar_t* wp);
wchar_t* CharToWchar(const char* c);
wchar_t* CharToWchar(const char* c);
wchar_t* StringToWchar(const string& s);

CascadeClassifier face_cascade;
String face_cascade_name = "./haarcascade_frontalface_alt.xml";

ofstream outFile;  //


//读取目录src下min(number,所有图像)图像提取人脸并保存到srccut目录,
//参数:原图片目录src       剪切图片保存目录dst     读取最大数量number    
void AllImagePro(string src, string dst, static int number)
{
	int count = 0;
	string src1 = src;
	string src1cut = dst;
	HANDLE hFile;
	LPCTSTR lpFileName = StringToWchar(src1 + "/" + "*.*"); //指定搜索目录和文件类型,如搜索d盘的音频文件可以是"D:\\*.mp3"
	WIN32_FIND_DATA pNextInfo;  //搜索得到的文件信息将储存在pNextInfo中;
	hFile = FindFirstFile(lpFileName, &pNextInfo);//请注意是 &pNextInfo , 不是 pNextInfo;
	if (hFile == INVALID_HANDLE_VALUE)
	{
		//搜索失败
		exit(-1);
	}
	cout << "文件夹" << src << "找到的图片:" << endl;
	do
	{
		if (pNextInfo.cFileName[0] == '.')//过滤.和..
			continue;
		count++;
		printf("%s\n", WcharToChar(pNextInfo.cFileName));
		Mat img = imread(src1 + "/" + WcharToChar(pNextInfo.cFileName), 1);
		detectAndCut(img, src1cut, WcharToChar(pNextInfo.cFileName));
	} while (FindNextFile(hFile, &pNextInfo) && count<number);//如果设置读入的图片数量,则以设置的为准,如果图片不够,则读取文件夹下所有图片
}

//人脸检测
//参数:待检测图像img       保存路径dir     保存文件名name
void detectAndCut(Mat img, string dir, string filename)
{
	std::vector<Rect> faces;
	Mat img_gray;

	cvtColor(img, img_gray, COLOR_BGR2GRAY);
	equalizeHist(img_gray, img_gray);
	//-- Detect faces
	face_cascade.detectMultiScale(img_gray, faces, 1.1, 2, 0 | CV_HAAR_SCALE_IMAGE, Size(30, 30));

	for (size_t i = 0; i < faces.size(); i++)
	{
		Point rec(faces[i].x, faces[i].y);
		Point rec2(faces[i].x + faces[i].width, faces[i].y + faces[i].height);
		Mat roi_img = img(Range(faces[i].y, faces[i].y + faces[i].height), Range(faces[i].x, faces[i].x + faces[i].width));
		
		//写入文件
		char bufferWrite[256];
		//左上角,右下角
		sprintf(bufferWrite, "%s face %d %d %d %d", filename, faces[i].x, faces[i].y, faces[i].x + faces[i].width, faces[i].y + faces[i].height);
		outFile << bufferWrite << endl;	
		//imwrite(dir + "/" + filename, roi_img);
		rectangle(img, Point(faces[i].x, faces[i].y), Point(faces[i].x + faces[i].width, faces[i].y + faces[i].height),
			Scalar(0, 255, 0), 2, 8);    //框出人脸位置  
		
		cout << bufferWrite << endl;
	}
	//imshow("face", img);
	//waitKey();
}


char* WcharToChar(const wchar_t* wp)
{
	char *m_char;
	int len = WideCharToMultiByte(CP_ACP, 0, wp, wcslen(wp), NULL, 0, NULL, NULL);
	m_char = new char[len + 1];
	WideCharToMultiByte(CP_ACP, 0, wp, wcslen(wp), m_char, len, NULL, NULL);
	m_char[len] = '\0';
	return m_char;
}

wchar_t* CharToWchar(const char* c)
{
	wchar_t *m_wchar;
	int len = MultiByteToWideChar(CP_ACP, 0, c, strlen(c), NULL, 0);
	m_wchar = new wchar_t[len + 1];
	MultiByteToWideChar(CP_ACP, 0, c, strlen(c), m_wchar, len);
	m_wchar[len] = '\0';
	return m_wchar;
}

wchar_t* StringToWchar(const string& s)
{
	const char* p = s.c_str();
	return CharToWchar(p);
}


int main()
{
	outFile.open("F:\\results.txt");  //
	//在文件夹0图片中寻找人脸并截取存放到文件夹0cut中
	if (!face_cascade.load(face_cascade_name))
	{
		printf("--(!)Error loading\n");
		return -1;
	};
	AllImagePro("F:\\Facedevkit\\Face\\JPEGImages\\", "F:\\", 6302);
	cout << "cut……OK!" << endl;
	system("pause");
	return 0;
}

txt2xml

将txt转换成xml数据集

%%
%该代码可以做voc2007数据集中的xml文件,
%txt文件每行格式为:000002.png dog 44 28 132 121
%即每行由图片名、目标类型、包围框坐标组成,空格隔开
%如果一张图片有多个目标,则格式如下:(比如两个目标)
%000002.png dog 44 28 132 121
%000002.png car 50 27 140 110
%包围框坐标为左上角和右下角
%作者:小咸鱼_
%CSDN:http://blog.csdn.net/sinat_30071459
%%
clc;
clear;
%注意修改下面四个变量
imgpath='F:\Facedevkit\Face\JPEGImages\';%图像存放文件夹
txtpath='F:\results.txt';%txt文件
xmlpath_new='F:\Facedevkit\Face\Annotations\';%修改后的xml保存文件夹
foldername='Face';%xml的folder字段名


fidin=fopen(txtpath,'r');
lastname='begin';

while ~feof(fidin)
     tline=fgetl(fidin);
     str = regexp(tline, ' ','split');
     filepath=[imgpath,str{1}];
     img=imread(filepath);
     [h,w,d]=size(img);
      imshow(img);
      rectangle('Position',[str2double(str{3}),str2double(str{4}),str2double(str{5})-str2double(str{3}),str2double(str{6})-str2double(str{4})],'LineWidth',4,'EdgeColor','r');
      pause(0.1);
      
        if strcmp(str{1},lastname)%如果文件名相等,只需增加object
           object_node=Createnode.createElement('object');
           Root.appendChild(object_node);
           node=Createnode.createElement('name');
           node.appendChild(Createnode.createTextNode(sprintf('%s',str{2})));
           object_node.appendChild(node);
          
           node=Createnode.createElement('pose');
           node.appendChild(Createnode.createTextNode(sprintf('%s','Unspecified')));
           object_node.appendChild(node);
          
           node=Createnode.createElement('truncated');
           node.appendChild(Createnode.createTextNode(sprintf('%s','0')));
           object_node.appendChild(node);

           node=Createnode.createElement('difficult');
           node.appendChild(Createnode.createTextNode(sprintf('%s','0')));
           object_node.appendChild(node);
          
           bndbox_node=Createnode.createElement('bndbox');
           object_node.appendChild(bndbox_node);

           node=Createnode.createElement('xmin');
           node.appendChild(Createnode.createTextNode(sprintf('%s',num2str(str{3}))));
           bndbox_node.appendChild(node);

           node=Createnode.createElement('ymin');
           node.appendChild(Createnode.createTextNode(sprintf('%s',num2str(str{4}))));
           bndbox_node.appendChild(node);

           node=Createnode.createElement('xmax');
           node.appendChild(Createnode.createTextNode(sprintf('%s',num2str(str{5}))));
           bndbox_node.appendChild(node);

           node=Createnode.createElement('ymax');
           node.appendChild(Createnode.createTextNode(sprintf('%s',num2str(str{6}))));
           bndbox_node.appendChild(node);
        else %如果文件名不等,则需要新建xml
           copyfile(filepath, 'JPEGImages');
            %先保存上一次的xml
           if exist('Createnode','var')
              tempname=lastname;
              tempname=strrep(tempname,'.png','.xml');
              xmlwrite(tempname,Createnode);   
           end
            
            
            Createnode=com.mathworks.xml.XMLUtils.createDocument('annotation');
            Root=Createnode.getDocumentElement;%根节点
            node=Createnode.createElement('folder');
            node.appendChild(Createnode.createTextNode(sprintf('%s',foldername)));
            Root.appendChild(node);
            node=Createnode.createElement('filename');
            node.appendChild(Createnode.createTextNode(sprintf('%s',str{1})));
            Root.appendChild(node);
            source_node=Createnode.createElement('source');
            Root.appendChild(source_node);
            node=Createnode.createElement('database');
            node.appendChild(Createnode.createTextNode(sprintf('My Database')));
            source_node.appendChild(node);
            node=Createnode.createElement('annotation');
            node.appendChild(Createnode.createTextNode(sprintf('VOC2007')));
            source_node.appendChild(node);

           node=Createnode.createElement('image');
           node.appendChild(Createnode.createTextNode(sprintf('flickr')));
           source_node.appendChild(node);

           node=Createnode.createElement('flickrid');
           node.appendChild(Createnode.createTextNode(sprintf('NULL')));
           source_node.appendChild(node);
           owner_node=Createnode.createElement('owner');
           Root.appendChild(owner_node);
           node=Createnode.createElement('flickrid');
           node.appendChild(Createnode.createTextNode(sprintf('NULL')));
           owner_node.appendChild(node);

           node=Createnode.createElement('name');
           node.appendChild(Createnode.createTextNode(sprintf('guojawee')));
           owner_node.appendChild(node);
           size_node=Createnode.createElement('size');
           Root.appendChild(size_node);

          node=Createnode.createElement('width');
          node.appendChild(Createnode.createTextNode(sprintf('%s',num2str(w))));
          size_node.appendChild(node);

          node=Createnode.createElement('height');
          node.appendChild(Createnode.createTextNode(sprintf('%s',num2str(h))));
          size_node.appendChild(node);

         node=Createnode.createElement('depth');
         node.appendChild(Createnode.createTextNode(sprintf('%s',num2str(d))));
         size_node.appendChild(node);
         
          node=Createnode.createElement('segmented');
          node.appendChild(Createnode.createTextNode(sprintf('%s','0')));
          Root.appendChild(node);
          object_node=Createnode.createElement('object');
          Root.appendChild(object_node);
          node=Createnode.createElement('name');
          node.appendChild(Createnode.createTextNode(sprintf('%s',str{2})));
          object_node.appendChild(node);
          
          node=Createnode.createElement('pose');
          node.appendChild(Createnode.createTextNode(sprintf('%s','Unspecified')));
          object_node.appendChild(node);
          
          node=Createnode.createElement('truncated');
          node.appendChild(Createnode.createTextNode(sprintf('%s','0')));
          object_node.appendChild(node);

          node=Createnode.createElement('difficult');
          node.appendChild(Createnode.createTextNode(sprintf('%s','0')));
          object_node.appendChild(node);
          
          bndbox_node=Createnode.createElement('bndbox');
          object_node.appendChild(bndbox_node);

         node=Createnode.createElement('xmin');
         node.appendChild(Createnode.createTextNode(sprintf('%s',num2str(str{3}))));
         bndbox_node.appendChild(node);

         node=Createnode.createElement('ymin');
         node.appendChild(Createnode.createTextNode(sprintf('%s',num2str(str{4}))));
         bndbox_node.appendChild(node);

        node=Createnode.createElement('xmax');
        node.appendChild(Createnode.createTextNode(sprintf('%s',num2str(str{5}))));
        bndbox_node.appendChild(node);

        node=Createnode.createElement('ymax');
        node.appendChild(Createnode.createTextNode(sprintf('%s',num2str(str{6}))));
        bndbox_node.appendChild(node);
       
       lastname=str{1};
        end
        %处理最后一行
        if feof(fidin)
            tempname=lastname;
            tempname=strrep(tempname,'.png','.xml');
            xmlwrite(tempname,Createnode);
        end
end
fclose(fidin);

file=dir(pwd);
for i=1:length(file)
   if length(file(i).name)>=4 && strcmp(file(i).name(end-3:end),'.xml')
    fold=fopen(file(i).name,'r');
    fnew=fopen([xmlpath_new file(i).name],'w');
    line=1;
    while ~feof(fold)
        tline=fgetl(fold);
        if line==1
           line=2;
           continue;
        end
        expression = '   ';
        replace=char(9);
        newStr=regexprep(tline,expression,replace);
        fprintf(fnew,'%s\n',newStr);
    end
    fprintf('已处理%s\n',file(i).name);
    fclose(fold);
    fclose(fnew);
	delete(file(i).name);
   end
end

猜你喜欢

转载自blog.csdn.net/weixin_36750623/article/details/84782660