# How to get first row of np.vstack? midpoint of contour - Python

Hello,

Im new to OpenCV and Python, and Im trying to meassure the distance of the midpoints of two contours. This is my code so far:

image = cv2.imread('TwoMarkers.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray, 127 , 255, 0)
im2, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
for c in contours:
# if the contour is not sufficient large, or to small, ignore it
if cv2.contourArea(c) > 2000:
continue
elif cv2.contourArea(c) < 100:
continue
M = cv2.moments(c)
cX = int(M['m10'] /M['m00'])
cY = int(M['m01'] /M['m00'])
contourMidpoint= np.vstack([(cX, cY)])

D = dist.euclidean(contourMidpoint, contourMidpoint)
print(D)


How can I get the distance D between the two found values that are stacked? The apporach I tried dident work, and I have no clue how to sepererate the values that are stacked. Any help is much appreciated.

edit retag close merge delete

Sort by » oldest newest most voted

this looks like a more general code-flow / logic problem.

i'd try to:

1.: collect midpoints 2.: check their distances.

(you simply can't do all of it in the same loop)

# step 1, collect centers:
centers=[]
for c in contours:
# if the contour is not sufficient large, or to small, ignore it
if cv2.contourArea(c) > 2000:
continue
elif cv2.contourArea(c) < 100:
continue
M = cv2.moments(c)
cX = int(M['m10'] /M['m00'])
cY = int(M['m01'] /M['m00'])
centers.append([cx,cy])

# step 2, compare:
if len(centers) >=2:
dx = centers - centers
dy = centers - centers
D = math.sqrt(dx*dx+dy*dy)
print(D)

more

1

Official site

GitHub

Wiki

Documentation