+-
python-如何调整图像大小并保持宽高比
我有一个拼图的图像,我需要调整其大小以使需要比较的两个拼图具有相同的大小.我使用以下代码调整图像大小.问题是图像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)
最佳答案
我不确定您要问什么,但似乎您想调整两个图像的大小并保持两个图像之间的长宽比.如果是这样,这是一个调整图像大小并将纵横比保持为任意宽度或高度的功能.

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)

您可能需要改写您的问题,以使问题更加清楚.

点击查看更多相关文章

转载注明原文:python-如何调整图像大小并保持宽高比 - 乐贴网