算法定位到人脸框,我们需要把人脸框截取出来。因为算法可能指定为到人脸,我们需要把整个人头截取出来,故不能简单的按照矩形框截图,需要做下简单处理。同时也要考虑到,扩大后的截图尺寸可能大于原图尺寸,需要判断一下。
代码如下
private void clipImage(ref Bitmap image, System.Drawing.Rectangle rect)
{
if (rect.Width != 0 && rect.Height != 0)
{
int offsetX = rect.X - rect.Width / 2;
offsetX = offsetX > 0 ? offsetX : 0;
int offsetY = rect.Y - (int)(rect.Height / 1.5);
offsetY = offsetY > 0 ? offsetY : 0;
int width = rect.Width * 2;
width = Math.Min(width, image.Width - offsetX);
int height = (int)(126.0 / 102.0 * width);
height = Math.Min(height, image.Height - offsetY);
Bitmap newImage = new Bitmap(width, height);
Graphics g = Graphics.FromImage(newImage);
g.DrawImage(image, System.Drawing.Rectangle.FromLTRB(0, 0, width, height), System.Drawing.Rectangle.FromLTRB(offsetX, offsetY, offsetX + width, offsetY + height), GraphicsUnit.Pixel);
image.Dispose();
image = newImage;
}
}
人脸可能占整个图像尺寸比例过大,或者太靠近屏幕边缘,需要额外处理。