我是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;
}
感谢您的帮助。
答案 0 :(得分:0)
您的crop
实施不正确。
var sourceIndex = xOffset + (yOffset + x) * sourceWidth;
您想要一个反映Line
y = mx + b; // where y is your offset
// m is your vertical position
// x is your width
// b is your starting horizontal position
所以你基本上复制了图像的水平部分并将这些像素复制到缓冲区,重复直到你有足够的部分。
全面实施:
private WriteableBitmap CropImage(WriteableBitmap source, int x, int y, int width, int height)
{
// range check
if (x < 0 || y < 0 || width <= 0 || height <= 0)
return null;
// create the bitmap
WriteableBitmap dest = new WriteableBitmap(width, height);
// calculate the starting offset
int offset = (y * source.PixelWidth) + x;
// copy each row of pixels from the starting y location to (y + height) with the width of width
for (int i = 0; i < height; i++)
{
Array.Copy(source.Pixels, offset, dest.Pixels, i * width, width);
offset += source.PixelWidth;
}
// return the crop image
return dest;
}
其他参考资料