初学opencv,什么都不会。只能“拿来主义”,把别人的写好的东西,自己组合下,望各位大牛们指点。
功能很简单,由于以后的人脸识别中要用的是灰度图像,所以先把一幅图片转化成灰度图片,再去检测图片中的人脸(但我发现这个过程中会有些误差,比如有时把图片总的非人脸检测成了人脸,不明opencv检测函数,只能“睁一只眼闭一只眼”),最后把检测出来的人脸归一化为固定大小保存到文件中。
过程感觉比较简单,没什么可再说的了,直接贴代码:
由于之前的代码在文件存储处有bug,现在重改下代码。
#include "stdafx.h"
#include "highgui.h"
#include
#include
#include
#include
#include
#pragma comment(lib, "opencv_objdetect248d.lib")
using namespace std;
static CvMemStorage* storage = 0;
static CvHaarClassifierCascade* cascade = 0;
static char* cascade_name="haarcascade_frontalface_alt.xml";
string ss("saveImg/");
int detectFace(IplImage* grayImg);
int _tmain(int argc, _TCHAR* argv[])
{
double scale=1.0;
const char * filename = "nba2.jpg";
// // Matlab风格的cvLoadImage 函数的另一种调用
IplImage* img = cvLoadImage(filename,1);
IplImage* grayImg=cvCreateImage(cvGetSize(img),img->depth,1);
IplImage* smallImg=cvCreateImage(cvSize(cvRound(img->width/scale),cvRound(img->height/scale)),IPL_DEPTH_8U,1);
cvCvtColor(img,grayImg,CV_BGR2GRAY);
cvResize(grayImg,smallImg,CV_INTER_LINEAR);
cvEqualizeHist(smallImg,smallImg);
detectFace(smallImg);
system("pause");
cvReleaseImage(&img);
cvReleaseImage(&grayImg);
cvReleaseImage(&smallImg);
return 0;
}
int detectFace(IplImage* grayImg){
static CvScalar colors[] = {
{{0,0,255}},{{0,128,255}},{{0,255,255}},{{0,255,0}},
{{255,128,0}},{{255,255,0}},{{255,0,0}},{{255,0,255}}
};
cascade_name = "haarcascade_frontalface_alt2.xml";
storage = cvCreateMemStorage(0);
cvClearMemStorage(storage);
cascade = (CvHaarClassifierCascade*)cvLoad( cascade_name, 0, 0, 0 );
if( !cascade )
{
fprintf( stderr, "ERROR: Could not load classifier cascade\n" );
return -1;
}
CvSeq* objects = cvHaarDetectObjects(grayImg, cascade, storage, 1.1,2,
0/*CV_HAAR_DO_CANNY_PRUNING*/,
cvSize(30,30));
IplImage* temp=cvCreateImage(cvGetSize(grayImg),grayImg->depth,1);
cvCopyImage(grayImg,temp);
CvSize dst_cvsize;
dst_cvsize.width=200;
dst_cvsize.height=200;
for(int i=0;i<(objects? objects->total:0);++i)
{
char char2[3];
itoa(i,char2,10);
ss.append(char2);
ss.append(".bmp");
CvRect* r=(CvRect*)cvGetSeqElem(objects,i);
cvSetImageROI(temp,cvRect(r->x,r->y,r->width,r->height));
IplImage* dst = cvCreateImage(cvSize(r->width,r->height),
IPL_DEPTH_8U,
1);
IplImage* fixed_dst=cvCreateImage(dst_cvsize,IPL_DEPTH_8U,1);
cvCopy(temp,dst,0);
cvResetImageROI(temp);
cvResize(dst,fixed_dst,CV_INTER_LINEAR);
cvNamedWindow(ss.c_str(),1);
cvShowImage(ss.c_str(),fixed_dst);
cvSaveImage(ss.c_str(),fixed_dst);
cvRectangle(grayImg, cvPoint(r->x,r->y), cvPoint((r->x+r->width),(r->y+r->height)), colors[i%8]);
cvReleaseImage(&dst);
cvReleaseImage(&fixed_dst);
ss.clear();
ss.append("saveImg/");
}
cvReleaseImage(&temp);
cvNamedWindow( "result", 1 );
cvShowImage( "result", grayImg);
cvWaitKey();
return 1;
}
这个完成了,下阶段要做的就是进行8*8的DCT处理了,但是这个不太明白,望哪位大牛能指点下。