Created
December 21, 2018 09:13
-
-
Save neerajvashistha/f933bc1373d84612b68464847af0893a 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 cv2 | |
#reading the image | |
image = cv2.imread("000001.jpg") | |
edged = cv2.Canny(image, 10, 250) | |
#cv2.imshow("Edges", edged) | |
#cv2.waitKey(0) | |
#applying closing function | |
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (30, 30)) | |
closed = cv2.morphologyEx(edged, cv2.MORPH_CLOSE, kernel) | |
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) | |
gray = cv2.GaussianBlur(gray, (5, 5), 0) | |
# threshold the image, then perform a series of erosions + | |
# dilations to remove any small regions of noise | |
thresh = cv2.threshold(gray, 45, 255, cv2.THRESH_BINARY)[1] | |
thresh = cv2.erode(thresh, None, iterations=2) | |
thresh = cv2.dilate(thresh, None, iterations=2) | |
#cv2.imshow("Closed", closed) | |
#cv2.waitKey(0) | |
#finding_contours | |
(_,cnts, _) = cv2.findContours(closed.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) | |
idx = 0 | |
for c in cnts: | |
peri = cv2.arcLength(c, True) | |
approx = cv2.approxPolyDP(c, 0.01 * peri, True) | |
cv2.drawContours(image, [approx], -1, 255, 3) | |
x,y,w,h = cv2.boundingRect(c) | |
if w>50 and h>50: | |
idx+=1 | |
new_img=image[y:y+h,x:x+w] | |
cv2.imwrite(str(idx) + '.png', new_img) | |
cv2.imshow("Output", image) | |
cv2.waitKey(0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment