Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get center of rectangle opencv python

Tags:

python

opencv

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.

like image 397
Dawzer Avatar asked Sep 08 '26 04:09

Dawzer


1 Answers

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)
like image 60
Hal Jarrett Avatar answered Sep 10 '26 18:09

Hal Jarrett