Hi, I’m higashi.
This time I introduce how to measure the angle on image by only three clicking shown in below movie.
I conduct this work by using python.
So, let’s get stared!!
Necessary Python Library
◆OpenCV
◆numpy
◆math
If you not installed them, please install first.
Introduce of Sample Image
I use this image for demonstration.
This image is monochrome, so the sample code shown later is also written for monochrome.
In the case you want to use color image, you should change some code.
If you don’t know how to do it, please contact me from comment section.
Sample Code of Measuring the Angle on Image
This is the sample code of measuring the angle on image.
import cv2
import numpy as np
import math
file_name='sample.jpg'
img=cv2.imread(file_name,cv2.IMREAD_GRAYSCALE)
x1,y1,x2,y2=0,0,0,0
counter=0
def click_deg(event, x, y, flags, params):
global x1,y1,x2,y2,img2,counter
if event == cv2.EVENT_LBUTTONDOWN and counter==0:
counter=1
x1=x
y1=y
elif event == cv2.EVENT_MOUSEMOVE and counter==1:
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_LBUTTONDOWN and counter==1:
counter=2
x2=x
y2=y
elif event == cv2.EVENT_MOUSEMOVE and counter==2:
img2=np.copy(img)
cv2.circle(img2,center=(x1,y1),radius=5,color=255,thickness=-1)
cv2.line(img2,(x1,y1),(x2,y2),255, thickness=1, lineType=cv2.LINE_4)
cv2.circle(img2,center=(x2,y2),radius=5,color=255,thickness=-1)
cv2.line(img2,(x2,y2),(x,y),255, thickness=1, lineType=cv2.LINE_4)
cv2.imshow('window', img2)
elif event == cv2.EVENT_LBUTTONDOWN and counter==2:
img2=np.copy(img)
x3=x
y3=y
cv2.circle(img2,center=(x1,y1),radius=5,color=255,thickness=-1)
cv2.line(img2,(x1,y1),(x2,y2),255, thickness=1, lineType=cv2.LINE_4)
cv2.circle(img2,center=(x2,y2),radius=5,color=255,thickness=-1)
cv2.line(img2,(x2,y2),(x3,y3),255, thickness=1, lineType=cv2.LINE_4)
cv2.circle(img2,center=(x3,y3),radius=5,color=255,thickness=-1)
#calculate angle
vec1=[x2-x1,y2-y1]
vec2=[x2-x3,y2-y3]
absvec1=np.linalg.norm(vec1)
absvec2=np.linalg.norm(vec2)
inner=np.inner(vec1,vec2)
cos_theta=inner/(absvec1*absvec2)
theta=round(math.degrees(math.acos(cos_theta)),3)
deg_str=str(theta)+'deg'
cv2.putText(img2,deg_str,(30, 50),cv2.FONT_HERSHEY_PLAIN,2,255,2,cv2.LINE_AA)
cv2.imshow('window', img2)
counter=0
cv2.imshow('window', img)
cv2.setMouseCallback('window', click_deg)
cv2.waitKey(0)
cv2.destroyAllWindows()
In this code, I use ‘inner product formula’ for calculating the angle.
If you interested in how to calculate, please search about ‘inner product formula’.
How to Use the Sample Code
Finally, I introduce how to use the sample code shown before.
1.Conduct the Sample Code
⇒New window of image will be shown.
2.Click Three Position
⇒The angle will be display on left-top of image.
3.Click Again
⇒Reset & Recalculation will be started.
The working view is shown below movie.
That’s all. Thank you!!
コメント