4 opencv 安装
cd opencv
mkdir build
cd build
cmake ..
make -j 10
make install
如果执行cmake时候出现如下错误信息
FATAL: In-source builds are not allowed.
则应该是在代码根目录下直接执行过cmake,导致根目录下生成了CMakeCache.txt,需要删除CMakeCache.txt再次执行编译即可。
5 例子 显示图片g++ `pkg-config --cflags opencv` -o show show.c `pkg-config --libs opencv`
YUV找人脸
Mat yuvImg;
yuvImg.create(height, width , CV_8UC1);
const int framesize = width * height ;
memcpy(yuvImg.data, pYuvBuf, framesize*sizeof(unsigned char));
vector
faceCascade.detectMultiScale(yuvImg, faces, 1.1, 3, 0, Size(0, 0));
if(faces.size()>0){
printf("%d\n", faces.size());
for(int i =0; i
rectangle(yuvImg, Point(faces[i].x, faces[i].y), Point(faces[i].x +faces[i].width, faces[i].y + faces[i].height),
Scalar(0, 255, 0), 1, 8);
}
imshow("FacesOfPrettyGirl", yuvImg);
cvWaitKey(0);
}
YUV2RGB找人脸
CascadeClassifier faceCascade;
faceCascade.load("xxx/opencv-3.3.0/data/haarcascades/haarcascade_frontalface_alt.xml");
int facedectect_yuv(u_char* pYuvBuf, int width, int height)
{
Mat yuvImg;
yuvImg.create(height*3/2, width, CV_8UC1);
const int framesize = width * height * 3 / 2;
memcpy(yuvImg.data, pYuvBuf, framesize*sizeof(unsigned char));
Mat rgbImg;
//yuv 2 rgb
cvtColor(yuvImg, rgbImg, CV_YUV2BGR_I420);
Mat imgGray;
vector
if(rgbImg.empty()){
return 1;
}
if(rgbImg.channels() ==3){
cvtColor(rgbImg, imgGray, CV_RGB2GRAY);
}else{
imgGray = rgbImg;
}
faceCascade.detectMultiScale(imgGray, faces, 1.2, 6, 0, Size(0, 0));
return faces.size();
if(faces.size()>0){
printf("%d\n", faces.size());
for(int i =0; i printf("x:%d,y:%d,w:%d,h:%d\n", faces[i].x, faces[i].y,faces[i].width, faces[i].height); rectangle(rgbImg, Point(faces[i].x, faces[i].y), Point(faces[i].x +faces[i].width, faces[i].y + faces[i].height), Scalar(0, 255, 0), 1, 8); } } imshow("FacesOfPrettyGirl", rgbImg); cvWaitKey(0); return 0; } JPG找人脸 // 【1】加载分类器 问题: opencv直接用haarcascade_frontalface_alt2找人脸不是很准。如:
CascadeClassifier cascade;
cascade.load("haarcascade_frontalface_alt2.xml");
Mat srcImage, grayImage,dstImage;
// 【2】读取图片
srcImage = imread("image.jpg");
dstImage = srcImage.clone();
imshow("【原图】", srcImage);
grayImage.create(srcImage.size(), srcImage.type());
cvtColor(srcImage, grayImage, CV_BGR2GRAY); // 生成灰度图,提高检测效率
vector
cascade.detectMultiScale(grayImage, rect, 1.1, 3, 0); // 分类器对象调用
printf("检测到人脸个数:%d\n", rect.size());