Ask Your Question
0

Distance between 2 points in opencv (Pixel to cm)

asked 2017-12-05 08:58:16 -0600

pipeecs780 gravatar image

Hello, I asked a month about a code that can measure the distance betweet two points, but I think the result is in pixels, so would like to get the distance, but in cm. I'm using webcam Microsoft lifecam hd-3000, and I really don't know what to do at this point in the code.

TEST

import cv2   
    import numpy as np

    #Captura de video a traves de la webcam
    cap=cv2.VideoCapture(0)

    D = []
    max_samples = 10000 

    outfile = open('new.txt', 'w')

    while(1):
            d=0.1
            centers=[]
            _, img = cap.read()

            hsv=cv2.cvtColor(img,cv2.COLOR_BGR2HSV) #Se obtiene un histograma basada en las saturaciones de colores.

            blue_lower=np.array([95,150,100],np.uint8)
            blue_upper=np.array([150,255,255],np.uint8)

            blue=cv2.inRange(hsv,blue_lower,blue_upper) #Se crea una mascara utilizando intervalos de color azul.

            kernel = np.ones((5 ,5), "uint8") #Crea una matriz de 5x5 la cual recorrera el video,
            blue = cv2.morphologyEx(blue,cv2.MORPH_OPEN,kernel)
            blue = cv2.morphologyEx(blue,cv2.MORPH_CLOSE,kernel)    

            blue=cv2.erode(blue,kernel, iterations=1) #Se erosiona utilizando el kernel sobre la mascara.
            res1=cv2.bitwise_and(img, img, mask = blue) #La nueva imagen reemplazara a blue.


            (_,contours,hierarchy)=cv2.findContours(blue,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) #Encuentra los contornos de los objetos que se ven en el filtro

            for pic, contour in enumerate(contours):
                area = cv2.contourArea(contour) #funcion de opencv que obtiene los contornos
                mayor_contorno = max(contours, key = cv2.contourArea)

                if(area>2000):
                    x,y,w,h = cv2.boundingRect(contour) #Encuentra coordenadas de los contornos.
                    img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
                    cv2.putText(img,"Marcador",(x,y),cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255,0,0))
                    M = cv2.moments(contour) #Se obtiene el centro de masa de los marcadores enconrados.
                    cx = int(M['m10'] /M['m00'])
                    cy = int(M['m01'] /M['m00'])
                    centers.append([cx,cy])
                    cv2.circle(img, (cx, cy), 7, (255, 255, 255), -1)

                if len(centers)==2:
                    D = (np.linalg.norm(cx-cy)) #Se aplica distancia euclidiana para encontrar la distancia entre los centros de masa.
                    print(D)
                    outfile.write("{0} \n".format(D))


            cv2.imshow("Color Tracking",img)
            if cv2.waitKey(10) & 0xFF == ord('q'):
                outfile.close()
                print('Los datos han sido enviados al doctor')
                cap.release()
                cv2.destroyAllWindows()
                break

I read about extrinsic and intrinsic parameters, but how do I get them with the webcam? Greetings

edit retag flag offensive close merge delete

Comments

helo, do you have any idea, how those duplicate questions happened ?

(it's probably not really your fault, but if you have some helpful observation, please let us know !)

berak gravatar imageberak ( 2017-12-05 09:14:17 -0600 )edit
1
berak gravatar imageberak ( 2017-12-05 09:15:19 -0600 )edit

1 answer

Sort by ยป oldest newest most voted
3

answered 2017-12-05 10:52:33 -0600

updated 2017-12-05 10:57:10 -0600

If I were you I would start with something even much simpler than what @berak suggested. Instead of calibrating the camera, have a reference object of known size and location in your image.

From here on, you simply have to convert the pixels to the reference object's metric in order to determine the distance of any other object(s) from the reference object. This and this blog posts do exactly that. The first one shows you how to measure the size of objects whilst the latter discusses distance. I would recommend reviewing the first link followed by the second one.

Thereafter you can go ahead and generalize the concept all together.

PS: I am suggesting this method first because judging by your recent questions, you sound like a newbie and I wouldn't want you to get lost copy pasting code without having a general grasp of what is actually happening.

edit flag offensive delete link more

Comments

1

^^ yea, voice of reason ...

berak gravatar imageberak ( 2017-12-05 11:13:26 -0600 )edit

I will try that today, thank you for your help again. And its true, I'm completly newby in opencv hahaha, this is my first project, but i have learned a lot.

pipeecs780 gravatar imagepipeecs780 ( 2017-12-06 08:51:09 -0600 )edit

hi! how you combined two calibration methods in one program? i have a program which detecting object in rea time i want in that program can detect and aslo distance from my dash board camera to other things how much is far help me please

Ayeshayounis gravatar imageAyeshayounis ( 2019-09-12 01:45:40 -0600 )edit

Question Tools

1 follower

Stats

Asked: 2017-12-05 08:58:16 -0600

Seen: 114,197 times

Last updated: Dec 05 '17