Python-Opencv :how to draw not complete rectangle with four corners on image

Opencv :how to draw not complete rectangle with four corners on image… here is a solution to the problem.

Opencv :how to draw not complete rectangle with four corners on image

After searching online, I couldn’t find a way to draw a bounding box like this. Images using OpenCV in Python. It has two features, the first is the four corners that are not connected to each other, and the second is a transparent bounding box.

I

know I should use polygons, but I can’t go further at this point.

Solution

The following function draws an incomplete rectangle around the area of interest. I used cv2.line() twice for each point provided. Also, I marked 4 points with cv2.circle().

There is only one constraint. You must provide 4 points in the following order: upper left, bottom left, upper right corner, bottom right corner.

There is also an option to change the length of the line you want to draw line_length.

Code:

def draw_border(img, point1, point2, point3, point4, line_length):

x1, y1 = point1
    x2, y2 = point2
    x3, y3 = point3
    x4, y4 = point4    

cv2.circle(img, (x1, y1), 3, (255, 0, 255), -1)    #-- top_left
    cv2.circle(img, (x2, y2), 3, (255, 0, 255), -1)    #-- bottom-left
    cv2.circle(img, (x3, y3), 3, (255, 0, 255), -1)    #-- top-right
    cv2.circle(img, (x4, y4), 3, (255, 0, 255), -1)    #-- bottom-right

cv2.line(img, (x1, y1), (x1 , y1 + line_length), (0, 255, 0), 2)  #-- top-left
    cv2.line(img, (x1, y1), (x1 + line_length , y1), (0, 255, 0), 2)

cv2.line(img, (x2, y2), (x2 , y2 - line_length), (0, 255, 0), 2)  #-- bottom-left
    cv2.line(img, (x2, y2), (x2 + line_length , y2), (0, 255, 0), 2)

cv2.line(img, (x3, y3), (x3 - line_length, y3), (0, 255, 0), 2)  #-- top-right
    cv2.line(img, (x3, y3), (x3, y3 + line_length), (0, 255, 0), 2)

cv2.line(img, (x4, y4), (x4 , y4 - line_length), (0, 255, 0), 2)  #-- bottom-right
    cv2.line(img, (x4, y4), (x4 - line_length , y4), (0, 255, 0), 2)

return img

line_length = 15

img = np.zeros((512,512,3), np.uint8)
cv2.imshow('img', img)

point1, point2, point3, point4 = (280,330), (280,390), (340,330), (340,390)
fin_img = draw_border(img, point1, point2, point3, point4, line_length)

cv2.imshow('fin_img', fin_img)

cv2.waitKey()
cv2.destroyAllWindows() 

Result:

enter image description here

Related Problems and Solutions