Ask Your Question
0

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

asked 2017-01-23 06:19:03 -0600

agroms gravatar image

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[0], contourMidpoint[1])
    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 flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
1

answered 2017-01-23 07:20:42 -0600

berak gravatar image

updated 2017-01-23 07:27:53 -0600

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[0][0] - centers[1][0]
    dy = centers[0][1] - centers[1][1]
    D = math.sqrt(dx*dx+dy*dy)
    print(D)
edit flag offensive delete link more

Comments

1

This worked, thank you so much :)

agroms gravatar imageagroms ( 2017-01-23 07:42:52 -0600 )edit

Question Tools

1 follower

Stats

Asked: 2017-01-23 06:19:03 -0600

Seen: 692 times

Last updated: Jan 23 '17