Created
June 29, 2017 20:33
-
-
Save toverux/150578cdf0d71dd4700993b6fb73b387 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
import argparse | |
import glob | |
import cv2 | |
import json | |
def auto_canny(image, sigma=0.33): | |
otsu_thresh_val, ret = cv2.threshold(image, 0, 255, cv2.THRESH_BINARY|cv2.THRESH_OTSU) | |
lower = otsu_thresh_val * 0.3 | |
upper = otsu_thresh_val * 1 | |
edged = cv2.Canny(image, lower, upper) | |
return edged | |
ap = argparse.ArgumentParser() | |
ap.add_argument("-i", "--images", required=True, | |
help="path to input dataset of images") | |
args = vars(ap.parse_args()) | |
for imagePath in glob.glob(args["images"] + "/*.jpg"): | |
image = cv2.imread(imagePath) | |
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) | |
blurred = cv2.GaussianBlur(gray, (3, 3), 0) | |
edged = auto_canny(gray) | |
kernel = np.ones((20, 20), np.uint8) | |
morphed = cv2.morphologyEx(edged, cv2.MORPH_CLOSE, kernel) | |
(_, contours, _) = cv2.findContours(morphed.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) | |
main_contour = sorted(contours, key = cv2.contourArea, reverse = True)[0] | |
peri = cv2.arcLength(main_contour, False) | |
approx = cv2.approxPolyDP(main_contour, 0.0015 * peri, True) | |
cv2.drawContours(image, [approx], -1, (0, 255, 0), 2) | |
print(json.dumps(approx.tolist())); | |
cv2.imshow("Result", image) | |
cv2.waitKey(0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment