How to find distance between centers of two green boxes?

Hi , I am still beginner in opencv and I have this task :

find the distance between the centers of two green boxes using camera.

I could be able to find the centers of the boxes but how to find the distance between their centers ?

below is my code

Many thanks.

import numpy as np
import cv2
import imutils

cap = cv2.VideoCapture(1)

while(1):

#read frame and convert the color scheme of the frame BGR to HSV
image = imutils.resize(image, width=600)

hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)

#Our operations on the frame come here

lower_pink = np.array([38, 50, 50])
upper_pink = np.array([75, 255, 255])

#Our frame, the HSV image, is thresholded among upper and lower pixel ranges to get only green colors

kernel = np.ones((5,5),'int')

# Then we thresholded the masked image and get the contours.

ret,thresh = cv2.threshold(cv2.cvtColor(res,cv2.COLOR_BGR2GRAY),3,255,cv2.THRESH_BINARY)

# find contours in the thresholded image
cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if imutils.is_cv2() else cnts[1]

# loop over the contours
for c in cnts:
# compute the center of the contour
area=cv2.contourArea(c)
M = cv2.moments(c)
if M["m00"] >1000:
cX = int(M["m10"] / M["m00"])
cY = int(M["m01"] / M["m00"])

# draw the contour and center of the shape on the image
cv2.drawContours(mask, [c], -1, (0, 255, 0), 2)
cv2.circle(mask, (cX, cY), 7, (0, 255, 255), -1)
cv2.putText(mask, "center", (cX - 20, cY - 20),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 255), 2)

k = cv2.waitKey(5) & 0xFF
if k == 27:
break

cap.release()
cv2.destroyAllWindows()

edit retag close merge delete

you mean distance in pixels?

( 2017-06-03 06:56:54 -0500 )edit

in cm or inches .. even in pixels is ok ..

( 2017-06-03 07:00:00 -0500 )edit

Sort by ยป oldest newest most voted

For example, cX1 and cY1 are coordinates of center of first box, cX2 and cY2 are coordinates of center of second box. You can find the distance:

 distance = (((cX1 - cX2) ** 2) + ((cY1 - cY2) ** 2)) ** 0.5


If you know real sizes of boxes you can also compute distance in cm. But accuracy will be low.

more

but how can I get cX1,cX2 and cY1,cY2 ?

( 2017-06-03 07:43:54 -0500 )edit

using your code. you wrote that you can find centers of boxes and seems that your code really can do this, just save coordinates cX, cY to appropiated variables

( 2017-06-03 08:24:09 -0500 )edit

Thank you so much

( 2017-06-03 11:59:24 -0500 )edit

but why the distance is changing when I move my cam forward or backward ?

( 2017-06-03 12:09:00 -0500 )edit

because cm count per pixel is different in these cases. distance in cm is the same, but in pixels it will change depends on your camera position. that's normal

( 2017-06-03 13:05:27 -0500 )edit

If, for example, box1.center = X1,Y1 and box2.center = X2,Y2 , then your answer is:

sqrt((X2-X1)^2 + (Y2-Y1)^2)

more