'How do I center an object of an image in a square?

I have to center the object of this image 1 in a 1080x1080 square, with the same distance from the top and bottom (100px) image 2 - in other words the object' height should be 880.

Image 1 input_image

Image 2 output_image

I'm a newby and I tried to watch a bunch of tutorial trying to understand how to do it.

I thought that would be possible to detect the object and then the center point of the it and crop it, but the white points of dust on the scan messed up the whole shape detection.

  • Is there a way to make it work, not only for this scan but for every other book scan I'll use?

  • If the object in the input image is not straight, how do I manage to straitghten it up?

Thanks in advance

As suggested I'm adding the code I'm using

Like I said before, it's the result of me watching different tutorial and having very little knowledge, so probably there will be some mistakes.

`

import cv2
import numpy as np


img = cv2.imread('37_gialli-rizzoli.jpg')
hh, ww = img.shape[:2]

lower = np.array([0, 0, 0])
upper = np.array([10, 10, 10])

thresh = cv2.inRange(img, lower, upper)

kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (20, 20))
morph = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)

mask = 255 - morph

img_mask = cv2.bitwise_and(img, img, mask=mask)

image = cv2.cvtColor(img_mask, cv2.COLOR_BGR2GRAY) 

_, contours, _ = cv2.findContours(image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

print("no of shapes: {0}".format(len(contours)))

for cnt in contours:
    rect = cv2.minAreaRect(cnt)
    box = cv2.boxPoints(rect)
    box = np.int0(box)
    img = cv2.drawContours(img, [box], 0, (0,0,255)) 

cv2.imshow('ImageWindow', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

`



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source