Getting Same Rectangle Position from Scaled Small Size Image

人走茶凉 提交于 2019-12-11 12:18:22

问题


I'm trying to process a large size image.Since the processing takes too much time to complete i'm resizing the image prior processing.After processing i'm drawing a rectangle on the small size image.How can i translate the the coordinates of this rectangle to original unscaled image ie:Draw the rectangle at the same position on the unscaled image.

I'm using the following code to resize the image

public static Size ResizeKeepAspect(Size CurrentDimensions, int maxWidth, int maxHeight)
{
    int newHeight = CurrentDimensions.Height;
    int newWidth = CurrentDimensions.Width;
    if (maxWidth > 0 && newWidth > maxWidth) //WidthResize
    {
        Decimal divider = Math.Abs((Decimal)newWidth / (Decimal)maxWidth);
        newWidth = maxWidth;
        newHeight = (int)Math.Round((Decimal)(newHeight / divider));
    }
    if (maxHeight > 0 && newHeight > maxHeight) //HeightResize
    {
        Decimal divider = Math.Abs((Decimal)newHeight / (Decimal)maxHeight);
        newHeight = maxHeight;
        newWidth = (int)Math.Round((Decimal)(newWidth / divider));
    }
    return new Size(newWidth, newHeight);
}

This is what im trying to achieve


回答1:


Rectangle ConvertToLargeRect(Rectangle smallRect, Size largeImageSize, Size smallImageSize)
{
    double xScale = (double)largeImageSize.Width / smallImageSize.Width;
    double yScale = (double)largeImageSize.Height / smallImageSize.Height;    
    int x = (int)(smallRect.X * xScale + 0.5);
    int y = (int)(smallRect.Y * yScale + 0.5);
    int right = (int)(smallRect.Right * xScale + 0.5);
    int bottom = (int)(smallRect.Bottom * yScale + 0.5);
    return new Rectangle(x, y, right - x, bottom - y);
}



回答2:


It's a simple relation calculation. For example:

Image A 100 (w) x 100 (h): Pixel x = 10, y = 30
Image B 200 (w) x 200 (h): Pixel x = a, y = b

10 / 100 (w) = a / 200 (w) 
200 (w) * 10 / 100 (w) = a //Image B's x value
a = 20

30 / 100 (h) = b / 200 (h) 
200 (h) * 30 / 100 (h) = b //Image A's y value
b = 60


来源:https://stackoverflow.com/questions/47709943/getting-same-rectangle-position-from-scaled-small-size-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!