原理: 计算每个像素点的三通道差值,所有差值相加,小于 30 即为灰度图,大于30即为彩色图
float caculate_residual_pixel(cv::Mat face_img) {
//threadhold 建议 30
int channels = face_img.channels();
int rows = face_img.rows;
int cols = face_img.cols;
if (channels == 3) {
int ele_cols = cols*channels;
float sum = 0;
for (size_t i = 0; i < rows; i++)
{
uchar * ptr = face_img.ptr<uchar>(i);
for (size_t j = 0; j < ele_cols; j += 3)
{
sum += abs(ptr[j] - ptr[j + 1]) + abs(ptr[j] - ptr[j + 2]) + abs(ptr[j + 1] - ptr[j + 2]);
}
}
return sum / (rows*cols);
}
return -1;
}
void bgr_gray_classify() {
string gray_path = "E:\\work\\anti_spoofing\\data\\CASIA_ANTI\\data\\data_picture\\anti_print\\gray\\gray\\";
string bgr_path = "E:\\work\\anti_spoofing\\data\\CASIA_ANTI\\data\\data_picture\\really\\real_faces\\celebra\\celebra1\\";
string file_path[] = {gray_path, bgr_path};
glasssix::libfacewrapper face_detect = glasssix::libfacewrapper(3);
vector<vector<float>> value(2);
for (size_t temp = 0; temp < 2; temp++)
{
vector<string> files, file_names;
util::getFiles(file_path[temp], files, file_names, ".jpg");
int length = file_names.size();
cv::Mat img, gray;
for (size_t i = 0; i < length; i++)
{
img = imread(files[i]);
cvtColor(img, gray, CV_BGR2GRAY);
vector<Rect> rects;
int status = getFaceRect(face_detect, gray, rects);
if (status > 0) {
value[temp].push_back(caculate_residual_pixel(img(rects[0])));
}
}
float value_mean = 0;
int value_size = value[temp].size();
for (size_t i = 0; i < value_size; i++)
{
value_mean += value[temp][i];
}
value_mean = value_mean / value_size;
std::cout << " value mean is:" << value_mean << std::endl;
}
}