如何修复图像大小

时间:2019-03-20 10:13:05

标签: python image numpy opencv

我有一个拼图的图像,我需要调整其大小,以便需要比较的两个拼图都具有相同的大小。我使用以下代码调整图像大小。问题是图像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)

1 个答案:

答案 0 :(得分:0)

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

enter image description here

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)

您可能想重新表达您的问题,以使其更加清晰。