Measuring distance between objects in an image with OpenCV

distance_between_objects_result_01We have now reached the final installment in our three part series on measuring the size of objects in an image and computing the distance between objects.

Two weeks ago, we started this round of tutorials by learning how to (correctly) order coordinates in a clockwise manner using Python and OpenCV. Then, last week, we discussed how to measure the size of objects in an image using a reference object.

This reference object should have two important properties, including:

  1. We know the dimensions (in terms of inches, millimeters, etc.) of the object.
  2. It can be easily identifiable in our image (based on either location or appearances).

Given such a reference object, we can use it compute the size of objects in our image.

Today, we are going to combine the techniques used in the previous blog posts in this series and use these methods to compute the distance between objects.

Keep reading to find out how…

Looking for the source code to this post?
Jump right to the downloads section.

Measuring distance between objects in an image with OpenCV

Computing the distance between objects is very similar to computing the size of objects in an image — it all starts with the reference object.

As detailed in our previous blog post, our reference object should have two important properties:

  • Property #1: We know the dimensions of the object in some measurable unit (such as inches, millimeters, etc.).
  • Property #2: We can easily find and identify the reference object in our image.

Just as we did last week, we’ll be using a US quarter as our reference object which has a width of 0.955 inches (satisfying Property #1).

We’ll also ensure that our quarter is always the left-most object in our image, thereby satisfying Property #2:

Figure 1: We'll identify our reference object based on location, hence we'll always ensure our quarter is the left-most object in the image.

Figure 1: We’ll identify our reference object based on location, hence we’ll always ensure our quarter is the left-most object in the image.

Our goal in this image is to (1) find the quarter and then (2) use the dimensions of the quarter to measure the distance between the quarter and all other objects.

Defining our reference object and computing distances

Let’s go ahead and get this example started. Open up a new file, name it , and insert the following code:

Our code here is near identical to last week. We start by importing our required Python packages on Lines 2-8. If you don’t already have the imutils package installed, stop now to install it:

Otherwise, you should upgrade to the latest version ( 0.3.6  at the time of this writing) so you have the updated order_points function:

Lines 14-19 parse our command line arguments. We need two switches here: --image , which is the path to the input image containing the objects we want to measure, and --width , the width (in inches) of our reference object.

Next, we need to preprocess our image:

Lines 22-24 load our image from disk, convert it to grayscale, and then blur it using a Gaussian filter with a 7 x 7 kernel.

Once our image has been blurred, we apply the Canny edge detector to detect edges in the image — a dilation + erosion is then performed to close any gaps in the edge map (Lines 28-30).

A call to cv2.findContours  detects the outlines of the objects in the edge map (Lines 33-35) while Line 39 sorts our contours from left-to-right. Since we know that our US quarter (i.e., the reference object) will always be the left-most object in the image, sorting the contours from left-to-right ensures that the contour corresponding to the reference object will always be the first entry in the cnts  list.

We then initialize a list of colors  used to draw the distances along with the refObj  variable, which will store our bounding box, centroid, and pixels-per-metric value of the reference object.

On Line 45 we start looping over each of the contours in the cnts  list. If the contour is not sufficiently large (Lines 47 and 48), we ignore it.

Otherwise, Lines 51-53 compute the rotated bounding box of the current object (using  for OpenCV 2.4 and cv2.boxPoints  for OpenCV 3).

A call to order_points  on Line 59 rearranges the bounding box (x, y)-coordinates in top-left, top-right, bottom-right, and bottom-left order, which as we’ll see, is important when we go to compute the distance between object corners.

Lines 62 and 63 compute the center (x, y)-coordinates of the rotated bounding box by taking the average of the bounding box in both the x and y direction.

The next step is to calibrate our refObj :

If our refObj  is None  (Line 68), then we need to initialize it.

We start by unpacking the (ordered) rotated bounding box coordinates and computing the midpoint between the top-left and bottom-left along with top-right and bottom-right points, respectively (Lines 73-75).

From there, we compute the Euclidean distance between the points, giving us our “pixels-per-metric”, allowing us to determine how many pixels fit into --width  inches.

Note: See last week’s post for a more detailed discussion of the “pixels-per-metric” variable.

Finally, we instantiate our refObj  as a 3-tuple consisting of:

  1. The sorted coordinates corresponding to the rotated bounding box reference object.
  2. The centroid of the reference object.
  3. The pixels-per-metric ratio that we’ll be using to determine the distance between objects.

Our next code block handles drawing the contours around our reference object and the object we are currently examining, followed by constructing refCoords  and objCoords  such that (1) the bounding box coordinates and (2) the (x, y)-coordinates of the of the centroid are included in the same arrays:

We are now ready to compute the distance between the respective corners and centroids of objects in our image:

On Line 94 we start looping over pairs of (x, y)-coordinates that correspond to our reference object and object of interest.

We then draw a circle representing the (x, y)-coordinates of the current points we are computing the distance between and draw a line to connect the points (Lines 97-110).

From there, Line 105 computes the Euclidean distance between the reference location and the object location, followed by dividing the distance by the “pixels-per-metric”, giving us the final distance in inches between the two objects. The computed distance is then drawn on our image (Lines 106-108).

Note: This distance computation is performed for each of the top-left, top-right, bottom-right, bottom-left, and centroid coordinates for a total of five distance comparisons.

Finally, Lines 111 and 112 display the output image to our screen.

Distance measurement results

To give our distance measurement script a try, download the source code and corresponding images to this post using the “Downloads” form at the bottom of this tutorial. Unarchive the .zip  file, change directory to the  script, and then execute the following command:

Below follows a GIF animation demonstrating the output of our script:

Figure 2: Computing the distance between objects in an image with OpenCV.

Figure 2: Computing the distance between objects in an image with OpenCV.

In each of these cases, our script matches the top-left (red), top-right (purple), bottom-right (orange), bottom-left (teal), and centroid (pink) coordinates, followed by computing the distance (in inches) between the reference object and the current object.

Notice how the two quarters in the image are perfectly parallel to each other, implying that the distance between all five control points is 6.1 inches.

Below follows a second example, this time computing the distance between our reference object and a set of pills:

Figure 3: Computing the distance between pills using OpenCV.

Figure 3: Computing the distance between pills using OpenCV.

This example could be used as input to a pill sorting robot that automatically takes a set of pills and organizes them according to their size and distance from a pill container.

Our last example computes the distance between our reference object (a 3.5in x 2in business card) and a set of 7″ vinyl records and an envelope:

Figure 4: A final example of computing the distance between objects using OpenCV and computer vision.

Figure 4: A final example of computing the distance between objects using OpenCV and computer vision.

As you can see, in each of these cases, we have successfully computed the distance (in actual, measurable units) between objects in an image.


In the third and final installment in our series on measuring object sizes, we learned how to take two different objects in an image and compute the distance between them in actual measurable units (such as inches, millimeters, etc.).

Just as we found out in last week’s post, before we can (1) compute the size of an object or (2) measure the distance between two objects, we first need to compute the “pixels-per-metric” ratio, used to determine how many pixels “fit” into a given unit of measurement.

Once we have this ratio, computing the distance between objects is almost trivially easy.

Anyway, I hope you enjoyed this series of blog posts! If you have any suggestions for a future series, please leave a comment on shoot me a message.

And before you go, be sure to signup for the PyImageSearch Newsletter by entering your email address in the form below!


If you would like to download the code and images used in this post, please enter your email address in the form below. Not only will you get a .zip of the code, I’ll also send you a FREE 17-page Resource Guide on Computer Vision, OpenCV, and Deep Learning. Inside you'll find my hand-picked tutorials, books, courses, and libraries to help you master CV and DL! Sound good? If so, enter your email address and I’ll send you the code immediately!

, , , ,

112 Responses to Measuring distance between objects in an image with OpenCV

  1. AJ April 4, 2016 at 5:46 pm #

    Thanks for the great tutorial, I have one question.

    if I don’t have a reference object but I know the distance from the left edge of the image to the right edge can I find the distance from any object to the center of the image ?

    Best Regards

    • Adrian Rosebrock April 6, 2016 at 9:15 am #

      Yep, you absolutely can! The same ratio test applies.

    • aisha March 21, 2019 at 1:26 am #

      hi adrian, i want to know the distance between digits in an image, where should i make changes to get desired output?

    • james May 14, 2019 at 5:24 pm #

      Adria, Western Washington is Seeing ALOT of distracted driving collisions. I have seen a increase in guarder rail damage “most likely the car went off the highway as the driver was distracted”. LOTS of rear end collisions. Do you have sample code that determines distance to the rear of a vehicle and sends out a alert town to brake? Does the code measure the distance of the rear tail lights and uses trig to determine distance from the car in front of the vehicle? I have a Beagleboard and want to set it up to do do the test.

      • Adrian Rosebrock May 15, 2019 at 2:34 pm #

        Sorry, I do not have any code for that specific project.

  2. ghanendra April 5, 2016 at 6:05 am #

    Hey Adrian Its a Great Tutorial, thanks a lot I used it in my project for determining distance between the two bright objects.

    What If the reference object dimensions are continuously varying?? How to determine distance between the two variable size objects in a live stream video??

    • Adrian Rosebrock April 6, 2016 at 9:14 am #

      Can you elaborate on what you mean by “continuously varying”? If you have different reference objects, you’ll need to identify which one you are looking at. This can be done using all sorts of methods including object detection, keypoint matching, template matching, etc.

      • ghanendra April 6, 2016 at 10:28 pm #

        In your tutorial about Ball Tracking with opencv, when we move the ball back and forth in front of camera, the size of the contour varies accordingly, So taking this as reference, how to find distance between two balls??
        I have to detect the distance between the two head lights of a car and distance from the camera when car is moving.

        • Adrian Rosebrock April 7, 2016 at 12:54 pm #

          You’ll need to combine two calibration methods. The first (this blog post) to measure the distance between objects in images. Then, you can use this blog post to measure the distance from the camera to the object.

          • ghanendra April 7, 2016 at 11:32 pm #

            Really thanks a lot Adrian!!!!!!!!

          • Adrian Rosebrock April 8, 2016 at 12:54 pm #

            No problem 🙂

  3. Mahed April 5, 2016 at 10:58 am #

    Well … you know what they, there really is no off-switch to genius !!!

    Cant wait to see what Adrian has got brilliant plans for PyImage Gurus bit 🙂

    • Adrian Rosebrock April 6, 2016 at 9:10 am #

      Thanks Mahed! I have some pretty special announcements related to PyImageSearch Gurus coming in the next 1-2 months, so be sure to keep an eye on the blog 🙂

  4. Jim April 9, 2016 at 7:05 pm #

    Hello Adrian,

    can you explain what this line does:
    cnts = cnts[0] if imutils.is_cv2() else cnts[1]


    • Adrian Rosebrock April 13, 2016 at 7:11 pm #

      That line of code handles if you are using OpenCV 2.4 or OpenCV 3. There is a difference in the tuple returned by OpenCV between OpenCV 2.4 and OpenCV 3. You can read more about the change to cv2.findContours in this blog post.

  5. Marcus W. April 29, 2016 at 4:54 am #

    Hey, nice post.
    I guess its a stupid question, but how can i loop only over the center of the objects.

    Thanks for any help ^^

    • Adrian Rosebrock April 30, 2016 at 4:01 pm #

      The center of the coordinates are stored in cX and cY. You can just loop over those and ignore the other 🙂

      • Xzavier April 6, 2019 at 4:04 pm #

        Can you elaborate more on how to do this, like where in the code to comment out the rest?

  6. suresh June 7, 2016 at 10:44 am #

    great work bro . u r really awesome …

    can u plzz explain how to find distance between two tracked objects in a live video

    • Adrian Rosebrock June 7, 2016 at 3:11 pm #

      The same general algorithm as discussed in this blog post needs to be applied. You first need to “calibrate” the camera. From there, determining the distance between two objects in a video stream is the same as determining the distance between two objects in an image — you just need to access the video stream and then process every frame of the stream.

  7. vinaya June 16, 2016 at 5:00 am #

    how to measure eye to eye distance?? can this be done similar way?

    • Adrian Rosebrock June 18, 2016 at 8:22 am #

      If you can detect both eyes in an image, then yes, you can use this method to compute the distance between them.

  8. priyanka July 1, 2016 at 6:09 am #

    what values are stored in (xA, yA), (xB, yB) ..please explain

    • Adrian Rosebrock July 1, 2016 at 3:01 pm #

      (xA, yA) stores the (x, y)-coordinates of the reference image, meanwhile (xB, yB) store the (x, y)-coordinates of the object we are computing the distance to.

  9. Raycuz July 21, 2016 at 8:08 am #

    Is that possible if I want to draw all the lines of distances between objects and saved it in a single image..??

    • Raycuz July 21, 2016 at 8:40 am #

      Found it
      Thank you very much
      You gave an awesome guide for beginners

      • Jacki June 6, 2017 at 7:40 pm #

        Plz if you can explain for me
        How i can draw all rectangles in a single image?
        Thanks in advance

        • Adrian Rosebrock June 9, 2017 at 1:57 pm #

          Draw the lines on the original image loaded on Line 22 (rather than orig). Then save the image to disk once all lines are drawn via cv2.imwrite.

          • Jacki June 10, 2017 at 10:08 pm #

            Dear Dr. Adrian;
            Thanks in advance for your reply
            I do it. Now i can save all result in a single image, but i have a problem:
            When i delet line 111  [ cv2.imshow(“Image”, orig)] when i want to stop show result on the screen, for loop not work perfectly!! Just work for 3 object ((it save result just for 2 or 3 object )) not for all object
            Please if you can help me ?
            How i can cancel line 111 and run program with out error ??

          • Jacki June 11, 2017 at 5:38 pm #

            Thanks a lot dear Dr. Adrian i do it
            I removed line 112
            And now works fine without problem
            Your blog post very awesome
            Thanks again

          • hafiz October 12, 2019 at 7:12 pm #

            Hi Adrian, im new with OpenCV so if i may ask in detail how does i draw the lines on the original image? because i keep getting the image saved without the lines using cv2.imwrite

          • Adrian Rosebrock October 17, 2019 at 8:00 am #

            If you’re new to the world of computer vision and OpenCV you should read Practical Python and OpenCV first. That book will teach you the fundamentals. From there you can continue with your project. Walk before you run.

  10. Agnel Vishal November 20, 2016 at 8:09 am #

    I think some modifications are required if the distance between reference object and camera are different from other objects and camera. What should be done then?

  11. Abeer December 9, 2016 at 2:15 am #

    I see that the calculated distance is between the reference object and all other objects, what if I want to measure the distance between two objects that both are non reference objects?

    • Adrian Rosebrock December 10, 2016 at 7:13 am #

      You can certainly do that as well. The important part is that you find your reference object first. Your reference object allows you to compute the number of pixels per metric. As long as you have this, you can compute the distance between two non-reference objects.

  12. Sam March 9, 2017 at 3:48 am #

    HI Adrian. Is the distance between two objects affected by the viewpoint of camera or the camera lens angle?

    • Adrian Rosebrock March 10, 2017 at 3:52 pm #

      Yes, it absolutely is. In order to correct for this it’s common to calibrate our camera by computing the intrinsic properties of the camera. This allows us to help us correct for distortion. For these measurements to be correct you should have an (approximately) 90 degree, birds-eye-view of the objects.

  13. shahid March 28, 2017 at 7:57 am #

    hi adrian!
    Is this code suitable for android app development?

    • Adrian Rosebrock March 28, 2017 at 12:49 pm #

      You would need to convert the code from Python to Java + OpenCV for Android, but the same computer vision algorithms can be used.

  14. Ahmed May 7, 2017 at 3:44 am #

    Hi Adrian,

    Thanks a lot for your tutorials .. I an still a beginner in Opencv and I want to use the same approach but with camera .. how to determine the distance between two Pink boxes by Camera ?

    What is the simplest code for that ?


    • Adrian Rosebrock May 8, 2017 at 12:27 pm #

      I would suggest starting with this blog post to learn how to measure the distance between a camera and an object. Once you’ve detected both objects you can apply the same triangle similarity technique to measure the distance between the objects.

  15. David L. May 28, 2017 at 5:30 am #

    Do you have code to convert a perspective image into a birds-eye-view?

  16. Faisal June 4, 2017 at 7:00 am #


    The tutorial is awesome, but i need to adapt it for a video. So it can detect distances in real time. Could you please help me with it?


    • Adrian Rosebrock June 6, 2017 at 12:11 pm #

      The same techniques applied to single images can also be applied to video. I would suggest reading this blog post on accessing video streams. If you are new to OpenCV and Python, be sure to read through Practical Python and OpenCV as this book will give you the fundamentals you need to be successful porting the algorithm from single images to video.

  17. Anil June 19, 2017 at 10:44 am #

    Hi Adrian!!!!
    The tutorial was great. Thank you for that.
    I wanted to know if i have a set of parallel lines, then can i get the distance between two consecutive lines instead of with reference to just the first one???

    • Anil June 20, 2017 at 2:10 am #

      What would be the execution time for this code???
      If given an image, in how much time can it provide the answer on a raspberry pi based camera?

      • Adrian Rosebrock June 20, 2017 at 11:21 am #

        Regardless if your lines or parallel you would still need to be able to detect them both, otherwise how would you be able to know the distance between two arbitrary points on either line?

        As for the execution time, yes, you could certainly run this script on a Raspberry Pi.

  18. JD July 13, 2017 at 10:12 am #

    Hey, I was working on a project which required me to measure the diameter of holes and length and width of a plate using the image of the plate and a rasp pi cam and ofc rasp pi. I was wondering if this has the ability to be accurate to .001 in? Please let me know

    • Adrian Rosebrock July 14, 2017 at 7:26 am #

      For that level of accuracy I would recommend computing the intrinsic and extrinsic parameters of your camera and calibrating.

  19. Law August 19, 2017 at 8:07 am #

    Hi Adrian!

    This tutorial is great! But what if I want to make one pupil of the eye as a reference object and determine its distance to the other pupil without detecting other edges like the eyebrows, mouth etc. ?

    Thank you!

  20. Zaira Zafar August 25, 2017 at 1:16 am #

    Hi Adrian,

    Loved the work you have done. What if the second object is moving instead of being static? Will it calculate correct distance from reference object? If not then, how do I achieve that?

    • Adrian Rosebrock August 25, 2017 at 12:43 pm #

      As long as you have your reference object computed initially you can compute the distance between any other object in the image (provided it can be detected and localized, of course). In order to work with a video stream you’ll need to access your webcam. I discuss the topic in detail inside this post.

  21. sri September 15, 2017 at 6:07 am #

    Hi Adrian,
    Can you tell me how to display all the lines and distance in a single image rather than pressing other keys to display the distance.

    • Adrian Rosebrock September 18, 2017 at 2:15 pm #

      Moe the cv2.imshow and cv.waitKey calls to the end of the script rather than inside the loop.

  22. Yan October 29, 2017 at 7:11 am #

    Hi Adrien ,

    I use this program to determine distance beetween cars. Can you help to find the shortest distance please ?

    • Adrian Rosebrock October 30, 2017 at 3:01 pm #

      Hi Yan — I’m not sure I understand your question fully, but I’ll give it a shot. The shortest distance would be where the contour of the car is bigger than the image frame.

  23. berk November 1, 2017 at 6:57 pm #

    Hello Adrian;
    for example; There is a person identified with haarcascade; how the distances of detected persons to a specific object are calculated?

    thank you so much for your work.

    • Adrian Rosebrock November 2, 2017 at 2:17 pm #

      There are a number of ways you could determine the (x, y)-coordinate of the person. I personally would recommend (1) computing the center of the person bounding box or (2) compute the center (x, y)-coordinates of their face.

  24. Amna November 26, 2017 at 12:44 pm #

    Hello Adrian:
    Hey Adrian Its a Great Tutorial, thanks a lot I used it in my project for determining distance between the two objects. Can you tell how to reduce size of an image ?

    • Adrian Rosebrock November 27, 2017 at 1:04 pm #

      You can reduce the size of an image via cv2.resize or imutils.resize. If you’re new to OpenCV and image processing I would suggest working through Practical Python and OpenCV where I discuss image transformation basics in detail.

      • Amna November 29, 2017 at 3:34 am #

        Ok thankew 🙂

  25. Izzan February 21, 2018 at 1:00 am #

    hi andrian
    i have a problem with that code. like this :
    usage: [-h] -i IMAGE -w WIDTH error: argument -i/–image is required
    Can you explain that ?

    • Adrian Rosebrock February 22, 2018 at 9:06 am #

      Hey Izzan — you need to pass the command line arguments to the script when you execute it via the command line. The code itself does not need to be updated. If you’re new to command line arguments, that’s okay, but you should read up on them before continuing.

  26. Izzan February 25, 2018 at 12:47 pm #

    that’s for linux do you have any idea for windows ?

    • Adrian Rosebrock February 26, 2018 at 1:52 pm #

      This code can be executed and ran on Windows.

  27. Francis vikram sagar March 1, 2018 at 11:25 pm #

    Hello, adrian

    Could you please explain this part of the code. What is the” –image” and do we need to download a reference object image and parse the dimensions to it or is it something else?

    ap.add_argument(“-i”, “–image”, required=True,
    help=”path to the input image”)
    ap.add_argument(“-w”, “–width”, type=float, required=True,
    help=”width of the left-most object in the image (in inches)”

    • Adrian Rosebrock March 2, 2018 at 10:29 am #

      Hey Francis — I would suggest reading up on command line arguments before continuing.

  28. Sarkesh March 17, 2018 at 12:18 pm #

    hello adrian,

    Thanks for the great tutorial !! If I want to calculate the center distance of the object only, what line of code should I remove?

    Thank youu~

    • Adrian Rosebrock March 19, 2018 at 5:20 pm #

      You should compute the center (x, y)-coordinates of the bounding box. Add the two x-coordinates together and divide by two. Repeat for the y-coordinate.

  29. Ali K April 10, 2018 at 1:54 am #

    Hi Adrian… many thanks for the tutorial…since I am a beginner I just tried to download and run your code on my RPi 3 but I got “No module named scipy.spatial” error message… so I tried $ pip install scipy and then after few minutes my RPi was frozen 🙁 any idea what should I do? Thanks.

    • Ali K April 10, 2018 at 3:04 am #

      BTW, I am using Python virtual environment based on your suggestion in other tutorials… so I did $workon cv $pip install scipy and it did not work

      • Adrian Rosebrock April 10, 2018 at 11:58 am #

        Make sure you supply the --no-cache-dir when installing SciPy on a Raspberry Pi:

        $ pip install scipy --no-cache-dir

        The only time we use SciPy is for the Euclidean distance so I would instead recommend you implement it as a helper function at the top of the script. This would allow you to skip installing SciPy entirely.

  30. Nihel May 10, 2018 at 5:48 am #


    How to convert inches to millimeters in this code??


    • Adrian Rosebrock May 14, 2018 at 12:17 pm #

      1 inch is 25.4 millimeters. You can use this relationship to perform the conversion.

  31. Monwar Jahan July 5, 2018 at 1:12 am #

    Hi Adrian,
    I’m trying to detect distance between objects in my mobile app , can I follow your workflow while implementing it for openCV in Android?

    Or should I follow something different?
    Please let me know

    • Adrian Rosebrock July 5, 2018 at 6:15 am #

      You can use the same algorithm discussed in this blog post but you’ll need to implement it in Java rather than Python.

  32. Nidhi Deshmukh August 22, 2018 at 9:37 am #

    Hello Adrian
    I am trying to do stackup analysis on NX unigraphics using Python. Is that possible?
    Stackup analysis is measuring the gap between assembled parts.
    Could u please help me with that Python code?

    • Adrian Rosebrock August 22, 2018 at 10:19 am #

      Sorry, I do not have any blog posts or source code on “stackup analysis”.

      • Nidhi Deshmukh August 26, 2018 at 11:57 pm #

        Thank you Adrian for reverting back.
        Can you suggest any other solution or provide me with a code for measuring the gap between two end points of a mechanical part?

        • Adrian Rosebrock August 30, 2018 at 9:22 am #

          I do not have any code for such as specific use case. The PyImageSearch blog contains over 300+ free tutorials on how to learn computer vision — use them to learn and enrich your knowledge but I cannot write code for you. Additionally, I would suggest you work through Practical Python and OpenCV so you can learn the basics of computer vision and image processing.

  33. Nidhi deshmukh September 12, 2018 at 10:42 am #

    Tysm Adrian.

  34. Swapnil September 15, 2018 at 9:34 am #

    Hi Adrian,

    This is quite interesting post. I wanted to ask you one interesting problem related to this or even suggestion will help. Is it possible to find the distance between two objects, but without going through the objects, means the distance between objects though some random curves without touching other objects.

    Thanks for any help

    • Adrian Rosebrock September 17, 2018 at 2:30 pm #

      Hey Swapnil — I’m not sure what you mean by “distance through some random curves”. Perhaps you could clarify or provide an example?

  35. Phong October 8, 2018 at 11:45 pm #

    Hi Adrian
    Thanks for awesome codes, Your descriptions on file ease noob like me in learning them. My question is on section “ # loop over the original points” , why refCoords unchanged , objCoords changed to next object. Is It caused by zip class? Is there any class will change refCoords by previous objCoords whenever new objCoords changed to next.
    Im stuck in a problem, have three known points, how to find a point that connect a known point to perpendicular line of rest 2 known points
    can you please recommend example code for it

  36. ram October 24, 2018 at 3:24 am #

    how can we apply this code for video

  37. M Chafidh October 27, 2018 at 11:06 pm #

    Hello, Mr. Adrian Rosebrock, i wanna ask to you.
    I’m a newbie to learn opencv. How to streaming video and calculating distance measurement with plate police? if distance between my camera and plate in front of me too close, i’ve already make notification to rasb pi.
    but i cannot to make coding of plate police distance measurement

    • Adrian Rosebrock October 29, 2018 at 1:29 pm #

      You would want to first detect the license plate in the image. Do you already have a license plate detector? If not, I cover Automatic License Plate Recognition (ANPR) inside the PyImageSearch Gurus course.

  38. Arthur Faustinelli January 30, 2019 at 12:46 pm #

    Hello man, how you doing?
    Sorry about my english errors and excitement, i’m not a professional programer and english isn’t my native language.
    The first time I saw this post I get really excited because i am working on a project that requires object distance measuring and I have been looking for a solution like this for too long.
    The way you explain each line on your code and call your own blog links is amazing.
    Looking on the post’s date, I get a bit nervous thinking that maybe I would have some problems with Python and the Libraries version, but it doesn’t happened.
    On the same way your blog is still alive since them! You are always here answering the questions and helpping people.
    When I got to the end of the reading I thought: I need to thank that guy! And for my surprise all of your posts have such a good amount of replys and polite people doing this.

    By the way, thank you very much for your job and support for the community. I hope you really get the gratitude for all of us.

    • Adrian Rosebrock February 1, 2019 at 7:06 am #

      Thank you for the kind words, Arthur! I really appreciate your comment. I’m so happy you enjoyed the tutorial 🙂

  39. Rkz February 16, 2019 at 11:10 pm #

    Hey! im working on small project where I need to detect the size of a object .Is it possible to measure the size without using a reference object but instead calibrating initially with a reference and later working for objects independent of reference ?

    • Adrian Rosebrock February 20, 2019 at 12:41 pm #

      Yes, take a look into computing the intrinsic/extrinsic parameters of the camera.

  40. calics April 3, 2019 at 12:33 am #

    Is it possible to change the units to Microns? If yes, can you please help in the conversion factor.

    • Adrian Rosebrock April 4, 2019 at 1:28 pm #

      1 inch is equal to 25400 microns if I’m not mistaken. You should double-check that though.

  41. Arthur Faustinelli April 10, 2019 at 12:02 am #

    Hello, Adrian. I’m having a little problem looping only over the centers. Already tried looping over cX and cY, created new variables to alocate centers and alot of other things but nothing works. Could you please help me?

    • Adrian Rosebrock April 12, 2019 at 12:13 pm #

      What specifically do you mean by “nothing works”? It sounds like there is a probably a logic error in the code. In that I would recommend reading through Practical Python and OpenCV to help you learn the fundamentals of OpenCV. That will better prepare you to write your own custom OpenCV code (and build your own projects).

  42. Varun Kumar April 23, 2019 at 1:37 am #

    Can i convert the inches to mm in my output??

    • Adrian Rosebrock April 25, 2019 at 8:51 am #

      1in is 25.4mm. You can do that the conversion.

  43. Varun Kumar April 23, 2019 at 1:41 am #

    Hey how can i include a second or third decimal value in my output??

    • Adrian Rosebrock April 25, 2019 at 8:51 am #

      You would change “{:.1f}in” to “{:.3f}in” in the “cv2.putText” function.

  44. Julie May 7, 2019 at 8:56 am #

    Hello Adrian, thank you for you tutorial.

    i don’t speak english very well, excuse me in advance.

    I work on a picture. I did the job to have the contour on my thread (it’s a picture of thread).

    Now i would like to measure the dimension on my thread.

    Do you have an idea to do it ?

    thank you

    • Adrian Rosebrock May 8, 2019 at 12:56 pm #

      This tutorial will show you how to measure the size of your thread.

      • Julie May 9, 2019 at 3:36 am #

        Thank you Adrian

  45. Blake Hoffman May 17, 2019 at 1:03 pm #

    Hello Adrian,

    I appreciate these tutorials as they are helping me a lot in getting started with OpenCV. I plan on incorporating this into a video instead of a single image.

    However, I want to determine how far an object has moved in the video from its original place in inches, based on using the size of the object that is being tracked. Am I correct in assuming that using the object reference’s size will help me determine in how far the object has traveled from it’s original starting point? Also, how do I reference this original “starting point” as the object moves across the screen?

    Also, I am just speaking in terms of x, y. The distance from the camera will not change.

    • Adrian Rosebrock May 23, 2019 at 10:08 am #

      Yes, all you need to do is (1) detect its original position and (2) detect its now position. Compute the midpoint between the two and then compute the distance.

  46. laiba June 14, 2019 at 12:35 am #

    hi adrian i am new to this field . i have a stupid question is this code for linux or windows

    • Adrian Rosebrock June 19, 2019 at 2:23 pm #

      This code will work on both Windows and Linux.

  47. Raghu June 19, 2019 at 9:08 am #

    Hi Adrian I am Raghu i currently working on the dynamic distance measurement between moving cars in a video. Please provide me a suitable solution for estimating the distance between the contours in a video

  48. Iain November 22, 2019 at 4:31 pm #

    Hey thanks a lot for all the guides. They have all been great!

    I was just wondering if it is possible to calculate the distance from the centre of the whole image to the objects. This will be helpful for a project I am working on. I am trying to get the reference object as the point in the centre of the image but I have had no luck so far. Any advice would be appreciated. Thanks in advance.

    • Adrian Rosebrock December 5, 2019 at 11:01 am #

      Computing the center (x, y)-coordinates of the image is easy, just divide the width and height by half. Unless I’m misunderstanding your question?

  49. paula December 18, 2019 at 6:57 am #

    Hello Adrian! thanks for the tutorial. I need only compute a distance, from the nearest corners. What modifications should I make? I was trying and I can’t make it

Before you leave a comment...

Hey, Adrian here, author of the PyImageSearch blog. I'd love to hear from you, but before you submit a comment, please follow these guidelines:

  1. If you have a question, read the comments first. You should also search this page (i.e., ctrl + f) for keywords related to your question. It's likely that I have already addressed your question in the comments.
  2. If you are copying and pasting code/terminal output, please don't. Reviewing another programmers’ code is a very time consuming and tedious task, and due to the volume of emails and contact requests I receive, I simply cannot do it.
  3. Be respectful of the space. I put a lot of my own personal time into creating these free weekly tutorials. On average, each tutorial takes me 15-20 hours to put together. I love offering these guides to you and I take pride in the content I create. Therefore, I will not approve comments that include large code blocks/terminal output as it destroys the formatting of the page. Kindly be respectful of this space.
  4. Be patient. I receive 200+ comments and emails per day. Due to spam, and my desire to personally answer as many questions as I can, I hand moderate all new comments (typically once per week). I try to answer as many questions as I can, but I'm only one person. Please don't be offended if I cannot get to your question
  5. Do you need priority support? Consider purchasing one of my books and courses. I place customer questions and emails in a separate, special priority queue and answer them first. If you are a customer of mine you will receive a guaranteed response from me. If there's any time left over, I focus on the community at large and attempt to answer as many of those questions as I possibly can.

Thank you for keeping these guidelines in mind before submitting your comment.

Leave a Reply