如何调整图像大小并保持宽高比 [英] How to resize image and maintain aspect ratio

查看:138
本文介绍了如何调整图像大小并保持宽高比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an image of a puzzle piece that i need to resize in order for both the pieces I need to compare to have the same size. I have used the following codes to resize my image. The problem is the length of the line in the image 1 is 187 and after resizing the length of the line in image 2 is 194. intended output is for them to be same

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)

推荐答案

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

I'm not entirely sure what you're asking but it seems like you want to resize two images and maintain aspect ratio between the two. If so, here's a function to resize a image and maintain aspect ratio to any width or height.

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)

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

You may want to rephrase your question to be more clear.

这篇关于如何调整图像大小并保持宽高比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆