반응형

두 직선 사이의 각도를 구하는 OpenCV Python 예제 코드입니다.

 

2023.2.25  최초작성



두 개의 직선을 그리면 사이 각을 출력해줍니다. 

 

왼쪽 마우스 버튼을 클릭하여 첫번째 직선의 출발점을 지정합니다. 

 

마우스 왼쪽 버튼을 클릭하여 첫번째 직선의 끝점을 지정해주면 직선이 그려집니다. 

 

마우스 왼쪽 버튼 클릭으로 두번째 직선의 시작점을 지정해줍니다. 

 

마우스 왼쪽 버튼 클릭으로 두번째 직선의 끝점을 지정해주면 직선이 그려집니다. 

 

터미널에 두 직선의 사이각이 출력됩니다. 직선으로 생성되는 두 개의 각도 중 작은 각도가 출력됩니다. 



스페이스바 키를 누르면 화면이 지워집니다. 이제 다시 직선을 그려서 각도를 다시 출력해볼 수 있습니다. 



전체 코드입니다. 

 

import cv2
import numpy as np


def mouse_event(event, x, y, flags, param):
    global count,pre_x, pre_y
   
    if event == cv2.EVENT_FLAG_LBUTTON:

        count = count + 1

        if count % 2 == 0:
            cv2.circle(img, (x,y), 10, (255,0,0), -1)
            cv2.line(img, (pre_x, pre_y), (x, y), (255, 255, 255), 2)  

            list_vector.append(np.array([x-pre_x, y-pre_y]))

            if len(list_vector) == 2:
                radian = np.arccos(np.dot(list_vector[0], list_vector[1])/(np.linalg.norm(list_vector[0])*np.linalg.norm(list_vector[1])))
                theta = radian * 180/np.pi

                theta = np.fmin(theta, 180.0-theta)

                print(theta)
                count = 0
                list_vector.clear()
               
        else:
            pre_x = x
            pre_y = y
            cv2.circle(img, (x,y), 10, (0,0,255), -1)


img_empty = np.zeros( (500,500,3), dtype=np.uint8)
img = img_empty.copy()

count = 0
pre_x = -1
pre_y = -1
list_vector = []

while True:

    text = "Clear Screen: space bar"
    cv2.putText(img, text, (20,50), cv2.FONT_HERSHEY_SIMPLEX, 1, (255,255,255), 1 )


    cv2.imshow('set location', img)
    cv2.setMouseCallback("set location", mouse_event, img)
   
    key = cv2.waitKey(1)
    if key == 27: # esc key
        break
    elif key == 32: #spacebar key
        img = img_empty.copy()




참고

 https://darkpgmr.tistory.com/121 

 

반응형

문제 발생시 지나치지 마시고 댓글 남겨주시면 가능한 빨리 답장드립니다.

도움이 되셨다면 토스아이디로 후원해주세요.
https://toss.me/momo2024


제가 쓴 책도 한번 검토해보세요 ^^

+ Recent posts