首先计算新的盒子大小,使其 w:h 为 3:2。如果它的一侧比图像的长,则修剪框。
确定盒子大小后,我们再计算盒子中心。默认情况下,盒子中心保持不变,但如果盒子越过图像的边界,它就会移动。
最后我们可以使用box size和box center来计算box角的坐标。
import cv2
def draw_rectangle(img, min_x, min_y, max_x, max_y):
# resize box to 3:2(only enlarge it)
# determine the box_w and box_h
box_w, box_h = max_x-min_x, max_y-min_y
if box_w/box_h < 3/2:
box_w = int(box_h*(3/2))
else:
box_h = int(box_w*(2/3))
# trim the box so it won't be bigger than image
h, w = img.shape[:2]
box_w = w if box_w > w else box_w
box_h = h if box_h > h else box_h
# determine the center of box
# the default box center
box_center_x = (min_x+max_x)//2
box_center_y = (min_y+max_y)//2
# shift the box if it cross the boundary
if box_center_x + box_w//2 > w:
box_center_x = w - box_w//2
elif box_center_x - box_w//2 < 0:
box_center_x = box_w//2
if box_center_y + box_h//2 > h:
box_center_y = h - box_h//2
elif box_center_y - box_h//2 < 0:
box_center_y = box_h//2
# calculate the corner of the box
min_x, max_x = box_center_x - box_w//2, box_center_x + box_w//2
min_y, max_y = box_center_y - box_h//2, box_center_y + box_h//2
cv2.rectangle(img, (min_x, min_y), (max_x, max_y), (255,0,0), thickness=10)
return img
img = cv2.imread('image.jpg')
min_x, min_y, max_x, max_y = 0, 0, 400, 230
img = draw_rectangle(img, min_x, min_y, max_x, max_y)
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()