【问题标题】:How to resize image and maintain aspect ratio如何调整图像大小并保持纵横比
【发布时间】:2019-08-10 23:59:55
【问题描述】:

我有一张拼图的图像,我需要调整它的大小,以便我需要比较的两个拼图具有相同的大小。我使用以下代码来调整图像大小。问题是图像 1 中线的长度为 187,调整图像 2 中线的长度后为 194。预期的输出是使它们相同

ratio = math.hypot(x2 - x1, y2 - y1) / math.hypot(x4 - x3, y4 - y3)
print("img1", math.hypot(x2 - x1, y2 - y1),"img 2", math.hypot(x4 - x3, y4 - y3)*ratio)

n = int(ratio * new_img_2.shape[0])
img = cv2.resize(new_img_2, (n, n), cv2.INTER_CUBIC)

【问题讨论】:

  • 您调整了图像的大小,使它们的对角线具有相同的长度,但它们可能一开始就没有相同的形状(宽/高比)。
  • @ThierryLathuille 它们确实具有相同的宽度和高度。图像的外部尺寸是一个完美的正方形
  • 这可能是舍入错误的结果吗? n = int(ratio * ...) 导致一些数据丢失。您应该考虑到这一点并增加一个计算步骤。
  • @xMutzelx 这个错误的最大值可能相差 1 对,还有很多

标签: python image numpy opencv image-processing


【解决方案1】:

我不完全确定您在问什么,但您似乎想要调整两个图像的大小并保持两者之间的纵横比。如果是这样,这是一个调整图像大小并将纵横比保持为任意宽度或高度的函数。

import cv2

# Resizes a image and maintains aspect ratio
def maintain_aspect_ratio_resize(image, width=None, height=None, inter=cv2.INTER_AREA):
    # Grab the image size and initialize dimensions
    dim = None
    (h, w) = image.shape[:2]

    # Return original image if no need to resize
    if width is None and height is None:
        return image

    # We are resizing height if width is none
    if width is None:
        # Calculate the ratio of the height and construct the dimensions
        r = height / float(h)
        dim = (int(w * r), height)
    # We are resizing width if height is none
    else:
        # Calculate the ratio of the 0idth and construct the dimensions
        r = width / float(w)
        dim = (width, int(h * r))

    # Return the resized image
    return cv2.resize(image, dim, interpolation=inter)

if __name__ == '__main__':
    image = cv2.imread('../color_palette.jpg')
    cv2.imshow('image', image)
    cv2.waitKey(0)

    resized = maintain_aspect_ratio_resize(image, width=400)
    cv2.imshow('resized', resized)
    cv2.waitKey(0)

您可能需要重新表述您的问题以更清楚。

【讨论】:

    猜你喜欢
    • 2012-11-15
    • 2013-06-26
    • 2012-04-15
    • 1970-01-01
    • 2012-05-01
    相关资源
    最近更新 更多