반응형

OpenCV 컨투어 내부에 점이 있는지 파악하는 Python 예제 코드입니다. 



2023. 4. 17  최초작성




아래 그림에서 컨투어는 파란 도형 주변에 파란색 선으로 검출된 상태입니다. 도형 내부를 클릭하면 양수가 출력되며 도형 외부를 클릭하면 음수가 출력됩니다. 수치는 컨투어에 근접할 수록 작은 숫자가 됩니다. 컨투어 위에선 0이 됩니다. 

 

 

전체 소스 코드입니다.

 

import cv2


def mouse_event(event, x, y, flags, param):
    global cx,cy,dist, img, img_color

    if event == cv2.EVENT_FLAG_LBUTTON:  

        img = img_color.copy()
       
        cx = x
        cy = y

        dist = cv2.pointPolygonTest(contours[1], (cx, cy), True)
        print(dist)


img_color = cv2.imread('test.jpg')


img_gray = cv2.cvtColor(img_color, cv2.COLOR_BGR2GRAY)
ret, img_binary = cv2.threshold(img_gray, 200, 255, 0)
contours, hierarchy = cv2.findContours(img_binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
print('컨투어 개수', len(contours))

cx=0
cy=0
dist = 0


img = img_color.copy()


while(1):

    cv2.drawContours(img, [contours[1]], 0, (255, 0, 0), 3# blue

    cv2.circle(img, (cx, cy), 10, (0, 255, 0), -1)
    cv2.putText(img, str(int(dist)), (100,100), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,255,0), 2)

    cv2.imshow('test', img)
    cv2.setMouseCallback("test", mouse_event)
    key = cv2.waitKey(1)
    if key == 27: #esc key
        break



참고

 

 https://stackoverflow.com/questions/50670326/how-to-check-if-point-is-placed-inside-contour 








반응형

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

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


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

+ Recent posts