I have a simple image file as below, where I have defined a set of coordinates, I want to crop.
The cropping selection is happening on the frontend, which means that the image that the user is seeing, is scaled down to fit the user's screen. Below is the information of the image:
imageWidth: 965
imageHeight: 1365.46875
Based on above width and height, the coordinates of the box you see in the image, is:
"x":405.5,
"y":130,
"height":36
"width":129
(All numbers are in pixels)
On my backend, in my Python code, I want to make sure that I crop the same as the users are seeing. So I figured, I would have to calculate the x,y scaling factor:
import numpy as np
import cv2
#Open the original image and get widht/height
image = cv2.imread(image_file)
height, width = image.shape[0:2]
The original image's height and width is: H: 3508, W: 2479
I then calculate the scaling factors:
# Set scaling factors
scalingFactorX = width / imageWidth
scalingFactorY = height / imageHeight
Which equals: Scaling X: 2.5689119170984456, Scaling Y: 2.569081130564138
After calculating the scaling factors, I convert the original coordinates to scale accordingly:
crop_x = scalingFactorX * box['x']
crop_y = scalingFactorY * box['y']
crop_w = scalingFactorX * box['width']
crop_h = scalingFactorY * box['height']
And then finally, I crop the image and save it:
crop = image[int(crop_y):int(crop_y)+int(crop_h),
int(crop_x): int(crop_x) + int(crop_w)]
cv2.imwrite("cropped_image.png", crop)
However, the cropped area is not correct. It's simply a blank image (I guess the coordinates are way off, which means it ultimately crops another part of the page):
The result is a 331 x 92 pixel blank image.
I am not sure what I am doing wrong?
Edit:
The original image can be found here.