我有一个大尺寸图像。由于处理高分辨率图像需要很长时间,我调整它的大小以保持纵横比。从调整大小的图像中我检测到一个矩形,我有矩形的坐标。
Bitmap ResizekeepAspectRatio(Bitmap imgPhoto, int Width, int Height)
{
int sourceWidth = imgPhoto.Width;
int sourceHeight = imgPhoto.Height;
int sourceX = 0;
int sourceY = 0;
int destX = 0;
int destY = 0;
float nPercent = 0;
float nPercentW = 0;
float nPercentH = 0;
nPercentW = ((float)Width / (float)sourceWidth);
nPercentH = ((float)Height / (float)sourceHeight);
if (nPercentH < nPercentW)
{
nPercent = nPercentH;
destX = System.Convert.ToInt16((Width -
(sourceWidth * nPercent)) / 2);
}
else
{
nPercent = nPercentW;
destY = System.Convert.ToInt16((Height -
(sourceHeight * nPercent)) / 2);
}
int destWidth = (int)(sourceWidth * nPercent);
int destHeight = (int)(sourceHeight * nPercent);
Bitmap bmPhoto = new Bitmap(Width, Height,
PixelFormat.Format24bppRgb);
bmPhoto.SetResolution(imgPhoto.HorizontalResolution,
imgPhoto.VerticalResolution);
Graphics grPhoto = Graphics.FromImage(bmPhoto);
grPhoto.Clear(Color.Red);
grPhoto.InterpolationMode =
InterpolationMode.HighQualityBicubic;
grPhoto.DrawImage(imgPhoto,
new Rectangle(destX, destY, destWidth, destHeight),
new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
GraphicsUnit.Pixel);
grPhoto.Dispose();
return bmPhoto;
}
有没有一种方法可以将这个矩形转换/映射到大图像,以便获得相同的区域。我这样做是为了节省时间。
一些说明: 我有一个大的原始图像..我调整它的大小保持纵横比并使用一些处理我在其中得到一个矩形部分(只是坐标)。由于这部分的图像质量不好我需要找到一种方法来映射这个坐标到大图。
最佳答案
好的,如果我在这里理解清楚的话,它是:
您在选择矩形的区域中有一个视口(viewport),并且您希望将此矩形缩放到未缩放的图像。
所以我们将有这样一个函数:
public RectangleF TranslateScale(RectangleF CropRectangle, Bitmap imgPhoto)
首先,我们需要计算乘数以适应视口(viewport)上的图像,就像您的函数一样:
int sourceWidth = imgPhoto.Width;
int sourceHeight = imgPhoto.Height;
int sourceX = 0;
int sourceY = 0;
int destX = 0;
int destY = 0;
float nPercent = 0;
float nPercentW = 0;
float nPercentH = 0;
nPercentW = ((float)Width / (float)sourceWidth);
nPercentH = ((float)Height / (float)sourceHeight);
if (nPercentH < nPercentW)
nPercent = nPercentH;
else
nPercent = nPercentW;
现在我们知道了缩放百分比,我们只是取函数的倒数,而不是乘以矩形大小和位置:
CropRectangle.X /= nPercent;
CropRectangle.Y /= nPercent;
CropRectangle.Width /= nPercent;
CropRectangle.Height /= nPercent
return CropRectangle;
就是这样,现在您已将矩形缩放到原始图像大小,您现在可以裁剪该矩形。
关于c# - 从调整大小的图像中翻译/检测图像的矩形部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35244688/