Dawzer
Dawzer

Reputation: 169

Get center of rectangle opencv python

import cv2
import numpy as np



blank = np.zeros((720,720,3), np.uint8)
cv2.rectangle(blank,(168,95),(2,20),(0,0,255),3)
cv2.rectangle(blank,(366,345),(40,522),(0,255,0),3)
cv2.imshow('test', blank)
cv2.waitKey(0)
cv2.destroyAllWindows()

enter image description here

How can I get the coordinates of the centers of each rectangle ? I'm trying to draw a line covering the distance between them.

Upvotes: 3

Views: 19462

Answers (2)

Yusuf
Yusuf

Reputation: 41

The above method gave me an error like

cv2.error: OpenCV(4.5.5) :-1: error: (-5:Bad argument) in function 'line'
> Overload resolution failed:
>  - Can't parse 'pt1'. Sequence item with index 0 has a wrong type
>  - Can't parse 'pt1'. Sequence item with index 0 has a wrong type

so i tried the following method and it worked for me:

import cv2
import numpy as np

blank = np.zeros((720,720,3), np.uint8)
cv2.rectangle(blank,(168,95),(2,20),(0,0,255),3)
cv2.rectangle(blank,(366,345),(40,522),(0,255,0),3)

rect1x, rect1y = ((168+2)/2, (95+20)/2)
rect2x, rect2y = ((366+40)/2, (345+522)/2)
rect1center = int(rect1x),int(rect1y)
rect2center = int(rect2x),int(rect2y)
print(rect1center)
print(rect2center)
cv2.line(blank, (rect1center), (rect2center), (0,0,255), 4)

cv2.imshow('test', blank)
cv2.waitKey(0)
cv2.destroyAllWindows()

Upvotes: 0

Hal Jarrett
Hal Jarrett

Reputation: 835

cv2.rectangle only draws the rectangle itself, it doesn't return a class or store meta-data. Since you already have the points for the corners that define the rectangles, getting the centers of each is trivial, just ((x1+x2)/2, (y1+y2)/2). Thus, you can draw the line between them like:

rect1center = ((168+2)/2, (95+20)/2)
rect2center = ((366+40)/2, (345+522)/2)
cv2.line(blank, rect1center, rect2center, color, thickness)

Upvotes: 8

Related Questions