Reputation: 994
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)
Upvotes: 2
Views: 3040
Reputation: 46680
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.
Upvotes: 2