opencv3之人脸识别匹配

人脸识别匹配

这里的人脸匹配是我们提前存好一些图片,然后它会在文件夹里寻找最相似的图片匹配。

然后也是用的opencv3.4训练好的检查模型文件。

opencv3之人脸识别匹配_第1张图片

直接上代码。

#include
#include
#include
#include
#include "opencv2/objdetect.hpp"
#include "opencv2/videoio.hpp"
#include "opencv2/imgproc.hpp"
using namespace cv;
using namespace std;


string xmlPath = "haarcascade_frontalface_alt.xml";
//识别并截取人脸
Mat detectAndDisplay(Mat image)
{
CascadeClassifier ccf;
ccf.load(xmlPath);
vector faces;
Mat gray;
cvtColor(image, gray, CV_BGR2GRAY);
equalizeHist(gray, gray);
ccf.detectMultiScale(gray, faces, 1.1, 3, 0, Size(50, 50), Size(500, 500));
for (vector::const_iterator iter = faces.begin(); iter != faces.end(); iter++)
{
rectangle(image, *iter, Scalar(0, 0, 255), 2, 8); //画出脸部矩形
}
for (size_t i = 0; i {
Point center(faces[i].x + faces[i].width / 2, faces[i].y + faces[i].height / 2);
image = image(Rect(faces[i].x, faces[i].y, faces[i].width, faces[i].height));
}
return image;
}


//得到图片的哈希值
string HashValue(Mat &src)      
{
string rst(64, '\0');
Mat img;
if (src.channels() == 3)
cvtColor(src, img, CV_BGR2GRAY);
else
img = src.clone();
resize(img, img, Size(8, 8));
uchar *pData;
for (int i = 0; i {
pData = img.ptr(i);
for (int j = 0; j {
pData[j] = pData[j] / 4;
}
}


int average = mean(img).val[0];
Mat mask = (img >= (uchar)average);
int index = 0;
for (int i = 0; i {
pData = mask.ptr(i);
for (int j = 0; j {
if (pData[j] == 0)
rst[index++] = '0';
else
rst[index++] = '1';
}
}
return rst;
cout << "return rst ,hass value " << endl;
}
//求两张图片的汉明距离
int HanmingDistance(string &str1, string &str2)       
{
if ((str1.size() != 64) || (str2.size() != 64))
return -1;
int diff = 0;
for (int i = 0; i<64; i++)
{
if (str1[i] != str2[i])
diff++;
}
return diff;
cout << "return diff ,hanming distance " << endl;
}
         
int main(int argc, char** argv)
{
using std::cout;
using std::endl;
using std::cin;
cout << "请输入想要识别的图片名字:1-8" << endl;//5/6任意,7、8任意,3->4
int a, x, i;
int diff[9];
cin >> a;
//
//从数据库选择,实际上如果2张判断更简单,只是一次比对而已。我数据库的是多次循环,取最优而已
//
const string path1 = format("C:\\images\\%d.jpg", a);
Mat image1, image2;
image1 = imread(path1, -1);
string str1, str2, path2;
cvNamedWindow("你输入的图片", 1);
imshow("你输入的图片", image1);





image1=detectAndDisplay(image1);
//imshow("after cut ", image1);
str1 = HashValue(image1);


for (i = 1; i <= 8; i++)//因为我完成的就是8张图片的检测,所以循环值为8
{
path2 = format("C:\\images\\%d.jpg", i);
image2 = imread(path2, -1);
image2=detectAndDisplay(image2);
str2 = HashValue(image2);
diff[i] = HanmingDistance(str1, str2);
}


int min = 1000, t;
for (i = 1; i <= 8; i++)    //循环值为8,求与原图片汉明距离最小的那张图片
{
if (min>diff[i] && diff[i] != 0)
{
min = diff[i];
t = i;
}           //检测出的标记为t
}



path2 = format("C:\\images\\%d.jpg", t);
image2 = imread(path2, -1);//将图片t显示出来
cvNamedWindow("最相似的图片", 1);

imshow("最相似的图片", image2);//这时显示的就是最相似的照片
cvWaitKey(0);
cin.get();                    //吃掉回车符

}


由于参考的博文链接没有保存好,请见谅。

你可能感兴趣的:(opencv)