1. 程式人生 > >視頻檢測人臉添加帽子完美方案

視頻檢測人臉添加帽子完美方案

snippet AD 超出 std ros sin width 圖片 detect

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);

效果如下:

技術分享圖片

技術分享圖片

技術分享圖片

技術分享圖片

視頻檢測人臉添加帽子完美方案