Creeper2962
Creeper2962

Reputation: 35

How to convert coordinates of resized image to coordinate of original Image?

I am Creating an image cropper in python using opencv. I am selecting coordinates of 4 points of section to crop from mouse click. Problem is I am resizing the image to show it on screen like (800x600) and I cannot use those Points to crop Original Image.

How can i convert those coordinates to so that i can crop large resolution image but show them resized??

E.g.- if image is 1920x1080 it will take whole screen so i resize it to 1067x600 and then take points to crop it but then the cropped image will be of resized one not original hi-resolution one. how to convert coordinate like (234,455) to non-resized image coordinate?

Upvotes: 2

Views: 2673

Answers (1)

Kakshil Shah
Kakshil Shah

Reputation: 3796

You can deal with this with percentages. Basically, maintaining the aspect ratio of the image, resize it to a smaller size.

def resize_to_max_dimension(image,max_dimension):
    image_height,image_width,channels = image.shape


    if image_height < max_dimension and image_width < max_dimension: ##Only resize larger images
        return image


    if image_height > image_width:
        final_height = max_dimension
        final_width = int(final_height *  image_width / image_height )
    else:
        if not image_width == 0:
            final_width = max_dimension
            final_height = int(final_width *  image_height / image_width)
        else:
            final_height = 0
            final_width = 0


    return cv2.resize(image,(int(final_width),int(final_height)))

Now, once resized, let us say to 800 x 600, when you crop, calculate the percentage from the top sides. Basically, x_min_percentage, y_min_percentage, x_max_percentage, y_max_percentage So if the x min from left was 200 and the width was 800, you will have a 25% as the x_min_percentage.

Now it is easy, take the original image dimension, multiply by the percentages, and you have the new crop coordinates.

image_height,image_width,channels = original_image.shape
crop_x_min = image_width * x_min_percentage
crop_y_min = image_height * y_min_percentage
crop_x_max = image_width * x_max_percentage
crop_y_max = image_height * y_max_percentage

Upvotes: 2

Related Questions