Created
January 12, 2020 14:29
-
-
Save yptheangel/fe302f61c76fbd76875bc3156e419223 to your computer and use it in GitHub Desktop.
get convex hull of an image
This file contains hidden or 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
#Original source from https://github.com/opencv/opencv/blob/master/samples/python/tutorial_code/ShapeDescriptors/hull/hull_demo.py | |
from __future__ import print_function | |
import cv2 as cv | |
import numpy as np | |
import argparse | |
import random as rng | |
rng.seed(12345) | |
def thresh_callback(val): | |
threshold = val | |
# Detect edges using Canny | |
canny_output = cv.Canny(src_gray, threshold, threshold * 2) | |
# Find contours | |
contours, _ = cv.findContours(canny_output, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE) | |
# Find the convex hull object for each contour | |
hull_list = [] | |
contourArea_list=[] | |
maxHull=[] | |
for i in range(len(contours)): | |
# print(type(contours)) | |
# for index,i in enumerate(contours): | |
# print(contours) | |
# print(len(contours)) | |
hull = cv.convexHull(contours[i]) | |
area=cv.contourArea(hull) | |
contourArea_list.append(area) | |
hull_list.append(hull) | |
print(max(contourArea_list)) | |
# print(contourArea_list.index(max(contourArea_list))) | |
# print(hull_list[contourArea_list.index(max(contourArea_list))]) | |
maxHull.append(hull_list[contourArea_list.index(max(contourArea_list))]) | |
# print(maxHull[0]) | |
# print(hull_list[343]) | |
# Draw contours + hull results | |
drawing = np.zeros((canny_output.shape[0], canny_output.shape[1], 3), dtype=np.uint8) | |
for i in range(len(contours)): | |
color = (rng.randint(0,256), rng.randint(0,256), rng.randint(0,256)) | |
cv.drawContours(drawing, contours, i, color) | |
# cv.drawContours(drawing, hull_list, i, color) | |
for i in range(len(maxHull)): | |
cv.drawContours(drawing, maxHull, i, color) | |
# Show in a window | |
cv.imshow('Contours', drawing) | |
src = cv.imread("ic_sample.jpg") | |
if src is None: | |
print('Could not open or find the image:', args.input) | |
exit(0) | |
# Convert image to gray and blur it | |
src_gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY) | |
src_gray = cv.blur(src_gray, (3,3)) | |
# Create Window | |
source_window = 'Source' | |
cv.namedWindow(source_window) | |
cv.imshow(source_window, src) | |
max_thresh = 255 | |
# thresh = 100 # initial threshold | |
thresh = 96 # initial threshold | |
cv.createTrackbar('Canny thresh:', source_window, thresh, max_thresh, thresh_callback) | |
thresh_callback(thresh) | |
cv.waitKey() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment