Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

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



    cv2.imshow('frame',mask)

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

cap.release()
cv2.destroyAllWindows()