Skip to content

Instantly share code, notes, and snippets.

@kidapu
Last active November 13, 2019 00:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kidapu/395326bec6c5a1e9c2a91ab1ae747691 to your computer and use it in GitHub Desktop.
Save kidapu/395326bec6c5a1e9c2a91ab1ae747691 to your computer and use it in GitHub Desktop.
floodfill image
import numpy as np
import matplotlib.pyplot as plt
import cv2
import glob
pathes = glob.glob('./datas/input/*.jpg')
for path in pathes:
print(path)
im_in = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
im = cv2.imread(path)
th, im_th = cv2.threshold(im_in, 245, 255, cv2.THRESH_BINARY_INV)
im_floodfill = im_th.copy()
h, w = im_th.shape[:2]
mask = np.zeros((h+2, w+2), np.uint8)
cv2.floodFill(im_floodfill, mask, (0,0), 255)
im_floodfill_inv = cv2.bitwise_not(im_floodfill)
im_mask = im_th | im_floodfill_inv
b_channel, g_channel, r_channel = cv2.split(im)
img_BGRA = cv2.merge((b_channel, g_channel, r_channel, im_mask))
new_image = Image.fromarray(cv2.cvtColor(img_BGRA,cv2.COLOR_BGRA2RGBA))
bbox = new_image.split()[-1].getbbox()
new_image = new_image.crop(bbox)
outpath = path.replace("input","output")
new_image.save(outpath+".png")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment