Skip to content

Instantly share code, notes, and snippets.

@Davi0k
Last active June 23, 2020 10:49
Show Gist options
  • Select an option

  • Save Davi0k/d1eaaa5780176098a9050461e47eb80c to your computer and use it in GitHub Desktop.

Select an option

Save Davi0k/d1eaaa5780176098a9050461e47eb80c to your computer and use it in GitHub Desktop.
A simple Python utility to remove the Background of an Image that falls within a certain shade of gray.
import cv2, argparse # pip install opencv-python argparse
import numpy as np # pip install numpy
BLUR = 21
CANNY_THRESH = (10, 200)
MASK_DILATE_ITER, MASK_ERODE_ITER = 10, 10
MASK_COLOR = (0.0, 0.0, 1.0)
def remove_background_from_image(image: str, output: str) -> None:
"""
Removes the Background of an Image that falls within a certain shade of gray.
Parameters:
image (str): The path of the image to be processed
output (str): The path and name of the file with which to save the final result
"""
img = cv2.imread(image)
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray, CANNY_THRESH[0], CANNY_THRESH[1])
edges = cv2.dilate(edges, None); edges = cv2.erode(edges, None)
contour_info = list()
contours, note = cv2.findContours(edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)
for c in contours:
contour_info.append((
c,
cv2.isContourConvex(c),
cv2.contourArea(c),
))
contour_info = sorted(contour_info, key=lambda c: c[2], reverse=True)
max_contour = contour_info[0]
mask = np.zeros(edges.shape)
cv2.fillConvexPoly(mask, max_contour[0], 255)
mask = cv2.dilate(mask, None, iterations=MASK_DILATE_ITER)
mask = cv2.erode(mask, None, iterations=MASK_ERODE_ITER)
mask = cv2.GaussianBlur(mask, (BLUR, BLUR), 0)
mask_stack = np.dstack([mask] * 3)
mask_stack = mask_stack.astype('float32') / 255.0
img = img.astype('float32') / 255.0
masked = (mask_stack * img) + ((1 - mask_stack) * MASK_COLOR)
masked = (masked * 255).astype('uint8')
red, green, blue = cv2.split(img)
result = cv2.merge((red, green, blue, mask.astype('float32') / 255.0))
cv2.imwrite(output, result * 255)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Add some information about the convertion...")
parser.add_argument("image", nargs=1, help="Insert the path of the image you want to convert...")
parser.add_argument("-o", "--output", type=str, help="Insert a valid name for the converted image...", required=False, default="result.png")
arguments = parser.parse_args()
remove_background_from_image(arguments.image[0], arguments.output)
print("The image has been converted successfully, the background has been removed...")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment