我有一张拼图的图像,我需要调整其大小,以便我需要比较的两 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)
最佳答案
我不完全确定您在问什么,但似乎您想调整两个图像的大小并保持两个图像之间的纵横比。如果是这样,这里有一个函数可以调整图像大小并保持任意宽度或高度的纵横比。
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/