don't stop believing

auto canny function 만들어 사용하기 본문

Python/OpenCV

auto canny function 만들어 사용하기

Tongchun 2017. 11. 21. 23:36

OpenCV의 canny에 대해 search하다 괜찮은 post를 봤습니다. 괜찮으면 바로 따라해 봐야죠.

https://www.pyimagesearch.com/2015/04/06/zero-parameter-automatic-canny-edge-detection-with-python-and-opencv/


바로 소스코드부터 확인해 보겠습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# import the necessary packages
import numpy as np
import argparse
import glob
import cv2
def auto_canny(image, sigma=0.33):
# compute the median of the single channel pixel intensities
v = np.median(image)
# apply automatic Canny edge detection using the computed median
lower = int(max(0, (1.0 - sigma) * v))
upper = int(min(255, (1.0 + sigma) * v))
edged = cv2.Canny(image, lower, upper)
print('lower: %d upper: %d' % (lower, upper))
# return the edged image
return edged
# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--images", required=True, help="path to input dataset of images")
args = vars(ap.parse_args())
# loop over the images
for imagePath in glob.glob(args["images"] + "/*.jpg"):
# load the image, convert it to grayscale, and blur it slightly
image = cv2.imread(imagePath)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (3, 3), 0)
# apply Canny edge detection using a wide threshold, tight
# threshold, and automatically determined threshold
wide = cv2.Canny(blurred, 10, 200)
tight = cv2.Canny(blurred, 225, 250)
auto = auto_canny(blurred)
# show the images
cv2.imshow("Original", image)
cv2.imshow("Edges", np.hstack([wide, tight, auto]))
cv2.waitKey(0)
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

auto_canny는 이미지에 대한 median을 확인하고 lower와 upper에 적용해는 방식입니다.

위 소스코드를 auto_canny.py로 저장합니다.

비교할 이미지 파일을 images폴더에 넣고 아래와 같이 실행해 줍니다.

1
$ python auto_canny.py -i images
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

그럼 원본 이미지와, wide한 값(10, 200), tight한 값(225, 250) 그리고 auto_canny한 값으로 변환한 이미지가 보여 집니다.




Comments