“Python-OpenCV” How to Measure the Distance of Clicked Two Position on Image.

Python
higashi
higashi

Hi, I’m higashi.

This page introduces how to measure the distance of clicked two position (‘Euclidean Distance’) on image as shown below movie by using Python-OpenCV.

Just only designate the initial position by left click and end position by right click.

 

So, let’s get started.

 

Sponsored Links

Necessary Libraries

These libraries are used.

◆OpenCV

◆numpy

◆math

In case not installed, please install first of all.

 

Sponsored Links

Introduce of Sample Image

In this case, I use the below image.

Introduce of sample image

This picture’s resolution is known to be 0.178mm/pixel in advance.

 

The program introduced later use this value.

So, please change this value to appropriate for your picture.

 

Sponsored Links

Sample Code of Measuring the Distance of Two Position

The below is the sample code that can execute the process of the video introduced at the beginning of this page.

 

import cv2
import numpy as np
import math
file_name='sample.jpg'
kaizo=0.178 #mm/piexl
img=cv2.imread(file_name,cv2.IMREAD_GRAYSCALE)
x1,y1=0,0
counter=1
def click_length(event, x, y, flags, params):
    global x1,y1,img2,counter,kaizo
    if event == cv2.EVENT_LBUTTONDOWN:
        counter=0
        x1=x
        y1=y
    elif event == cv2.EVENT_MOUSEMOVE and counter==0:
        img2=np.copy(img)
        cv2.circle(img2,center=(x1,y1),radius=5,color=255,thickness=-1)
        cv2.line(img2,(x1,y1),(x,y),255, thickness=1, lineType=cv2.LINE_4)
        cv2.imshow('window', img2)
    elif event == cv2.EVENT_RBUTTONDOWN:
        counter=1
        img3=np.copy(img2)
        x2=x
        y2=y
        piexl=math.sqrt((x1-x2)**2+(y1-y2)**2)
        length=round(piexl*kaizo,3)
        length_str=str(length)+'mm'
        cv2.circle(img3,center=(x2,y2),radius=5,color=255,thickness=-1)
        cv2.putText(img3,length_str,(30, 50),cv2.FONT_HERSHEY_PLAIN,2,255,2,cv2.LINE_AA)
        cv2.imshow('window', img3)
cv2.imshow('window', img)
cv2.setMouseCallback('window', click_length)
cv2.waitKey(0)
cv2.destroyAllWindows()

 

Just you should change are the file name at 4th line and resolution at 5th line.

 

Sponsored Links

How to Use This Program

Finally, I introduce how to use the program.

  1. By Conducted the Program, Image Window will be Displayed.
  2. Left Click and designate the initial position of measuring.
  3. Right Click and designate the end position of measuring.
  4. If You want to Measure Again, Re-Execute 2. & 3. Process.

I re-post the movie just in case.

 

That’s all. Thank you!!

コメント