# Assigning unique identifier to shapes in real-time

Dear all,

Suppose I wish to keep track of multiple shapes that is detected via approxPolyDP in real-time (example: there are 3 individual triangles). How could I go about naming those triangles 1, 2 and 3? As I need to perform an operation starting from the left-most triangle. Here is my base code for shape detection.

canny_white, contours, hierarchy = cv2.findContours(white_mask,cv2.RETR_CCOMP,cv2.CHAIN_APPROX_SIMPLE)

for i in range(0,len(contours)):

approx = cv2.approxPolyDP(contours[i],cv2.arcLength(contours[i],True)*0.02,True)

if(len(approx) == 3):
x,y,w,h = cv2.boundingRect(contours[i])
cv2.putText(frame,"Triangle",(x,y),cv2.FONT_HERSHEY_SIMPLEX,1.5,(255,0,0),2,cv2.LINE_AA)


Thank you.

edit retag close merge delete

Sort by » oldest newest most voted

Hi you could use center of gravity of the contour:

    cx = []
cy = []
pos = []
for i in range(0, len(contours)):

approx = cv2.approxPolyDP(contours[i], cv2.arcLength(contours[i], True) * 0.02, True)

if (len(approx) == 3):
M = cv2.moments(contours[i])
if M['m00'] > 0:
pos.append(cv2.boundingRect(contours[i]))
cx.append(int(M['m10'] / M['m00']))
cy.append(int(M['m01'] / M['m00']))

idx = np.argsort(cx)
for i in range(0, len(idx)):
cv2.putText(im, "Triangle" + str(idx[i]), (pos[i], pos[i]), cv2.FONT_HERSHEY_SIMPLEX, 1.5,
(255, 0, 0), 2, cv2.LINE_AA)


result image: more

and minimize distance between gravity center in succesive frame

Official site

GitHub

Wiki

Documentation