본문 바로가기

카테고리 없음

opencv - 16일차

 Canny Edge Detection in OpenCV

 

: Canny edge detector is an edge detection operator that uses a multi-stage algorithm to detect a wide range of edge in images. It was developed by John F. Canny in 1986

 

5 단계

 

1. noise reduction

2. gradient calculation

3. non-maximum suppression

4. double threshold

5. edge tracking by hysteresis

 

과정이 복잡해보이지만 opencv 는 이를 아주 단순하게 실행할 수 있다.

 

import cv2
import numpy as np
from matplotlib import pyplot as plt

img = cv2.imread('messi5.jpg',0)
canny = cv2.Canny(img, 100, 200)

titles=['images','canny']
images=[img, canny]

for i in range(2):
    plt.subplot(1,2, i+1), plt.imshow(images[i], 'gray')
    plt.title(titles[i])
    plt.xticks([]), plt.yticks([])

plt.show()

cv2.Canny 함수의 첫번째 파라미터는 이미지, 두번째 세번째는 threshold로 지정할 수 있다.

 

여기서 각각 100 200으로 지정한다. 

 

 

이전 시간에 작성한 여러가지 operator 들과 비교했을 때 canny operator의 효과가 훨씬 좋음을 알 수 있다.  

 

import cv2
import numpy as np
from matplotlib import pyplot as plt

img = cv2.imread('messi5.jpg', cv2.IMREAD_GRAYSCALE)
lap = cv2.Laplacian(img, cv2.CV_64F, ksize =3)
lap = np.uint8(np.absolute(lap))
sobelX = cv2.Sobel(img, cv2.CV_64F, 1,0)
sobelY = cv2.Sobel(img, cv2.CV_64F, 0,1)
canny = cv2.Canny(img, 100, 200)

sobelX = np.uint8(np.absolute(sobelX))
sobelY = np.uint8(np.absolute(sobelY))

sobelCombined = cv2.bitwise_or(sobelX, sobelY)

titles = ['image', 'Laplacian', 'sobelX', 'sobelY', 'sobelCombined','canny' ]
images = [img, lap, sobelX, sobelY, sobelCombined, canny]

for i in range(6):
    plt.subplot(2,3,i+1), plt.imshow(images[i], 'gray')
    plt.title(titles[i])
    plt.xticks([]), plt.yticks([])

plt.show()

 

 

라플라시안, sobel 마스크에는 여전히 noise가 있는 반면 canny에는 noise가 거의 없음.

 

 

Image Pyramids with Python and OpenCV