python - 如何调整图像大小并保持纵横比

标签 python image numpy opencv image-processing

我有一张拼图的图像,我需要调整其大小,以便我需要比较的两 block 拼图具有相同的尺寸。我使用以下代码来调整图像大小。问题是图像 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 - 如何调整图像大小并保持纵横比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55258272/

相关文章:

java - 为什么这个 JLabel 的 ImageIcon 没有更新?

css - 使用 IF 语句将类添加到 Rails 中的 image_tag

python - 需要更快的 python 代码来计算样本熵

python - python中的模块化算法迭代 Pandas 数据框

python - 在 python 中绘制 3D 零均值、单位方差高斯会产生意想不到的结果

python - 如何在python中使用正则表达式查找特定格式的值,包括括号

python - Pandas OHLCV 转 JSON 格式

python - 打印由任何字符而不是逗号分隔的列表项 (Python)

vb.net - 如何将数据库中的图像添加到PictureBox?

python - read() 函数的返回值是什么类型?