2

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)
coffeewin
  • 182
  • 3
  • 6
  • 26
Eshaka
  • 974
  • 1
  • 14
  • 38
  • You resized your images so that their diagonals have the same length, but they probably didn't have the same shape (width/height ratio) to begin with. – Thierry Lathuille Mar 20 '19 at 10:17
  • @ThierryLathuille they do have the same width and height. the outer size of the image is a perfect square – Eshaka Mar 20 '19 at 10:19
  • Is it possible that this is the result of a rounding error? n = int(ratio * ...) leads to some data lose. You should take this in account and add one more computing step. – xMutzelx Mar 21 '19 at 11:05
  • @xMutzelx this maximum that this error can be is a difference of 1 right, there its a lot more than that – Eshaka Mar 22 '19 at 00:41

1 Answers1

2

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.

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)

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

nathancy
  • 42,661
  • 14
  • 115
  • 137