Python/OpenCV
auto canny function 만들어 사용하기
Tongchun
2017. 11. 21. 23:36
OpenCV의 canny에 대해 search하다 괜찮은 post를 봤습니다. 괜찮으면 바로 따라해 봐야죠.
바로 소스코드부터 확인해 보겠습니다.
# 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)
auto_canny는 이미지에 대한 median을 확인하고 lower와 upper에 적용해는 방식입니다.
위 소스코드를 auto_canny.py로 저장합니다.
비교할 이미지 파일을 images폴더에 넣고 아래와 같이 실행해 줍니다.
$ python auto_canny.py -i images
그럼 원본 이미지와, wide한 값(10, 200), tight한 값(225, 250) 그리고 auto_canny한 값으로 변환한 이미지가 보여 집니다.