我是一名新手Windows Phone程序员。我正在尝试创建一个人脸识别应用程序。我的问题是:我无法正确地通过矩形裁剪掉检测到的人脸图像。
以下是原始图像和裁剪后的图像:https://onedrive.live.com/redir?resid=3F56C0D8DEC03C5B%21109
foreach (var r in faces)
{
System.Windows.Shapes.Rectangle toAdd = new System.Windows.Shapes.Rectangle();
TranslateTransform loc = new TranslateTransform();
loc.X = r.X * _downsampleFactor / (double)w * cnvsFaceRegions.ActualWidth;
loc.Y = r.Y * _downsampleFactor / (double)w * cnvsFaceRegions.ActualHeight;
toAdd.RenderTransform = loc;
toAdd.Width = r.Width * _downsampleFactor+50;
toAdd.Height = r.Height * _downsampleFactor+50;
toAdd.Stroke = new SolidColorBrush(Colors.Red);
cnvsFaceRegions.Children.Add(toAdd);
widthRectangle = toAdd.Width;
heightRectangle = toAdd.Height;
point1 = loc.X ;
point2 = loc.Y ;
}
接下来我将裁剪图片:
private void SaveScreenShots()
{
WriteableBitmap bmp = new WriteableBitmap((int)this.ActualWidth, (int)this.ActualHeight);
WriteableBitmap bmp2= CropImage(bmp,(int)point1, (int)point2, (int)widthRectangle, (int)heightRectangle);
bmp2.Render(this, null);
byte[] bb = EncodeToJpeg(bmp2);
bmp2.Invalidate();
MemoryStream mem = new MemoryStream();
bmp2.SaveJpeg(mem, bmp2.PixelWidth, bmp2.PixelHeight, 0, 100);
mem.Seek(0, System.IO.SeekOrigin.Begin);
if (mem != null)
{
MediaLibrary library = new MediaLibrary();
try
{
pic = library.SavePicture("Mask_" + Guid.NewGuid().ToString(), mem);
MaskPath = pic.GetPath();
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
MessageBoxResult result = MessageBox.Show("", "Saved successfully", MessageBoxButton.OK);
});
}
catch (Exception ex)
{
MessageBox.Show("Unable to save the photo." + ex);
}
}
cameraViewer.NewCameraFrame += NewCameraFrame;
}
裁剪功能:
private static WriteableBitmap CropImage(WriteableBitmap source, int xOffset, int yOffset, int width, int height)
{
var sourceWidth = source.PixelWidth;
var result = new WriteableBitmap(width, height);
for (var x = 0; x <= height - 1; x++)
{
var sourceIndex = xOffset + (yOffset + x) * sourceWidth;
var destinationIndex = x * width;
Array.Copy(source.Pixels, sourceIndex, result.Pixels, destinationIndex, width);
}
return result;
}
感谢您的帮助。
WriteableBitmap source
的宽度/高度与你期望的宽度/高度进行比较。 - meneses.pt