Ask Your Question

# 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

really appreciate your help.

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 = cap.read()
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

mask = cv2.inRange(hsv, lower_pink, upper_pink)
kernel = np.ones((5,5),'int')
dilated = cv2.dilate(mask,kernel)

res = cv2.bitwise_and(image,image, mask=mask)

# 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
cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts if imutils.is_cv2() else cnts

# 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)

cv2.imshow('frame',mask)

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

cap.release()
cv2.destroyAllWindows()

edit retag close merge delete

## 2 answers

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

## Comments

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

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

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

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

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

more

Official site

GitHub

Wiki

Documentation

## Stats

Asked: 2017-06-03 06:37:07 -0500

Seen: 775 times

Last updated: Jun 03 '17