Python版本可参考以下链接:
https://github.com/crossin/snippet/tree/master/face_detect
//人脸宽度
//im为原始视频帧
const std::string strPath = AppPath.substr(0, AppPath.rfind("\")) + "\" + "hat8.png";
Mat m_hatImg = imread(strPath, -1);//带alpha通道的图片如果仍要保留alpha通道,imread的第二个参数必须是-1
int faceWidth = face_info_list[best_index].face.right - face_info_list[best_index].face.left; int faceHeight = face_info_list[best_index].face.bottom - face_info_list[best_index].face.top; //人脸与帽子的比例 float scale = (float)(faceWidth) / (float)m_hatImg.cols * 2.7; Mat hatScale; m_hatImg.copyTo(hatScale); //缩放帽子 resize(hatScale, hatScale, Size(), scale, scale); //imwrite("F:\HappyNewYear\hatImg_new.png", hatScale); //人脸正中位置坐标 int face_mid_x = face_info_list[best_index].face.left + faceWidth / 2; int face_mid_y = face_info_list[best_index].face.top - hatScale.rows/5; //帽子左上位置坐标 int hat_offset_x = face_mid_x - hatScale.cols / 2; int hat_offset_y = face_mid_y - hatScale.rows / 2; //调整,以免超出边界 //x1 帽子左上角x坐标 //x2 帽子右上角x坐标 int x1 = max(hat_offset_x, 0); int x2 = min(hat_offset_x + hatScale.cols, im.cols); //y1 帽子左上角y坐标 //y2 帽子右上角y坐标 int y1 = max(hat_offset_y, 0); int y2 = min(hat_offset_y + hatScale.rows, im.rows); //调整坐标 int hat_x1 = max(0, -hat_offset_x); int hat_x2 = hat_x1 + x2 - x1; int hat_y1 = max(0, -hat_offset_y); int hat_y2 = hat_y1 + y2 - y1; Mat ROI = im(cv::Rect(x1, y1, hat_x2- hat_x1, hat_y2 - hat_y1)); channels.clear(); src_channels.clear(); Mat hatROI = hatScale(cv::Rect(hat_x1, hat_y1, hat_x2 - hat_x1, hat_y2 - hat_y1)); split(hatROI, channels); split(ROI, src_channels); for (int i=0;i<3;i++) { src_channels[i]= src_channels[i].mul(255.0 / 1.0 - channels[3], 1.0 / 255.0); src_channels[i] += channels[i].mul(channels[3], 1.0 / 255.0); } merge(src_channels, ROI);
效果如下: