Iam using an object detection algorithm to detect objects in an image. The code is as below. Image used is of a car as below.
I would like to crop the original image to keep only the object detected in the image PLUS whatever is necessary to maintain aspect ratio between 4/3 and 16/9.
The box around the car is already deduced from below algorithm [variable is box] and the image dimensions are [variable is height,width] in below code.
If we were to do this manually, it would be cumbersome due to the multiple iterations required, as an example: we have to ensure that resizing does not extend beyond the original image size.
There are 3 images included below, the original image, the modified image with car detected, and the resized image to meet a aspect ratio range.(4/3 to 16/9)
Is there an existing function within python to accomplish this task. Hence, resizing/increasing box dimensions from [91, 90, 226, 158] to the minimum necessary amount to be within the limits of original image size 183x275 while maintaining the aspect ratio
Thanks in advance.
CODE:
import cv2
import matplotlib.pyplot as plt
import cvlib as cv
from cvlib.object_detection import draw_bbox
imagepath='/home/usr/Desktop/car.jpeg'
img = cv2.imread(imagepath)
####STEP 1
img1 = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
box, label, count = cv.detect_common_objects(img)
output = draw_bbox(img, box, label, count)
output = cv2.cvtColor(output,cv2.COLOR_BGR2RGB)
plt.figure(figsize=(10,10))
plt.axis('off')
plt.imshow(output)
plt.show()
print("Number of objects in this image are " +str(len(label)))
height,width,_=img1.shape
print(height,width)
print(box)
#box size is [91, 90, 226, 158] (w1,h1,w2,h2)
#image size is 183x275 (heightxwidth)
#STEP2 (cropping original image to car dimensions as per box size)
crop_img = img[90:158, 91:226]
cv2.imshow("cropped", crop_img)
cv2.waitKey(0)
Image Example:
Detect Object (Step1)
Crop Image (Step2)
Expected Outcome(Step3)