在图像上以3:2长宽比绘制矩形

时间:2019-02-16 12:17:38

标签: python opencv image-processing

我正在尝试绘制纵横比为3:2的矩形。 我正在使用OpenCV来检测图像中的对象。因此,从输出值中,我绘制了一个具有最小X,最小Y,最大X,最大Y的矩形。现在,我需要使该矩形从起始点(即最小x和最小Y)开始具有3:2的长宽比。

  

它不应超出原始图像的最大X和最大Y以及   矩形不应小于周围的现有矩形   检测到的物体。

2 个答案:

答案 0 :(得分:1)

这是解决此问题的一种方法:

# determine the y / x length of the rectangle
len_X = maxX - minX
len_Y = maxY - minY

# determine the largest side, this will be the 3 in the aspect ratio
if len_X > len_Y:
    # check if the shorter side is larger than a 3:2 ration
    if len_Y > len_X * (3/2):
        # if so, increase larger side to 3:2 ratio
        len_X = len_Y * 1.5
    else:
        # else, increase shorter side to 3:2 ratio
        len_Y = len_X * (3/2) 
else:
    # same as above
    if len_X > len_Y * (3/2):
        len_Y = len_X * 1.5
    else:
        len_X = len_Y * (3/2) 

# if the rectangle exceeds the image, constrain the rectangle
# other option (commented): move the starting position
if minX + len_X > img.shape[1]:
    len_X = img.shape[1]-minX
    #minX = img.shape[1]-len_X
if minY + len_Y > img.shape[0]:
    len_Y = img.shape[0]-minY
    #minY = img.shape[0]-len_Y

# draw the rectangle
cv2.rectangle(img, (minX, minY), (minX + len_X, minY + len_Y), (0,0,255),1)

答案 1 :(得分:0)

首先计算新的包装盒尺寸,使其w:h为3:2。如果框的一侧比图像的长,则修剪框。

确定盒子尺寸后,我们将计算盒子中心。默认情况下,框的中心保持不变,但是如果框越过图像的边界,框的中心将被偏移。

最后,我们可以使用框的大小和框的中心来计算框角的坐标。

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()