Skip to content

Instantly share code, notes, and snippets.

@hirocarma
Last active February 6, 2021 13:27
Show Gist options
  • Save hirocarma/2950a9ef4b9ddf063602f1ad6941a3c5 to your computer and use it in GitHub Desktop.
Save hirocarma/2950a9ef4b9ddf063602f1ad6941a3c5 to your computer and use it in GitHub Desktop.
Fill in areas that are not closed areas
import sys
import numpy as np
import cv2
def dilate(src, ksize=3):
h, w = src.shape
dst = src.copy()
d = int((ksize-1)/2)
for y in range(0, h):
for x in range(0, w):
roi = src[y-d:y+d+1, x-d:x+d+1]
if np.count_nonzero(roi) > 0:
dst[y][x] = 255
return dst
def erode(src, ksize=3):
h, w = src.shape
dst = src.copy()
d = int((ksize-1)/2)
for y in range(0, h):
for x in range(0, w):
roi = src[y-d:y+d+1, x-d:x+d+1]
if roi.size - np.count_nonzero(roi) > 0:
dst[y][x] = 0
return dst
_, infile, outfile = sys.argv
img = cv2.imread(infile)
#decolor
img_gray, _ = cv2.decolor(img);
#thresh/inverse
ret,thresh = cv2.threshold(img_gray,127,255,cv2.THRESH_BINARY_INV)
#Dilation
dilate_img = dilate(thresh, ksize=20)
#Erosion
erode_img = erode(dilate_img, ksize=16)
#inverse
img1 = cv2.bitwise_not(erode_img)
#findCountours
contours,hierarchy = cv2.findContours(img1,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
cnt = contours[0]
#Find the coordinates of both ends.
h, w = img1.shape
leftmin = w
leftup = h
for i in cnt:
(x,y)=i[0]
if 0 < x < leftmin:
leftmin = x
if 0 < y < leftup:
leftup = y
rightmax = 0
rightup = h
for i in cnt:
(x,y)=i[0]
if w - 1 > x > rightmax:
rightmax = x
if 0 < y < rightup:
rightup = y
#draw line
img1 = cv2.line(img1,(leftmin,leftup),(rightmax,rightup),(0,0,255),2)
cv2.imwrite(outfile, img1)
img1 = cv2.imread(outfile)
#Points are left on purpose !
img1 = cv2.drawContours(img1, cnt, -1, (255,0,0), 2)
#paint out
mask = cv2.Canny(img1, 100, 200)
mask = cv2.copyMakeBorder(mask, 1, 1, 1, 1, cv2.BORDER_REPLICATE)
cv2.floodFill( img1, mask, (120,120), (0,255,255))
sz = img1.shape[:2]
cv2.floodFill( img1, mask, (int(sz[0]/2), int(sz[1]/2)), (0,255,0))
cv2.imwrite(outfile, img1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment