Skip to content

Instantly share code, notes, and snippets.

@Vadbeg
Created February 29, 2020 17:31
Show Gist options
  • Save Vadbeg/073d77fd04696e521f15dae4476bee94 to your computer and use it in GitHub Desktop.
Save Vadbeg/073d77fd04696e521f15dae4476bee94 to your computer and use it in GitHub Desktop.
def remove_background(img, threshold):
"""
This method removes background from your image
:param img: cv2 image
:type img: np.array
:param threshold: threshold value for cv2.threshold
:type threshold: float
:return: RGBA image
:rtype: np.ndarray
"""
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, threshed = cv2.threshold(gray, threshold, 255, cv2.THRESH_BINARY_INV)
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (11, 11))
morphed = cv2.morphologyEx(threshed, cv2.MORPH_CLOSE, kernel)
cnts = cv2.findContours(morphed,
cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)[0]
cnt = sorted(cnts, key=cv2.contourArea)[-1]
mask = cv2.drawContours(threshed, cnt, 0, (0, 255, 0), 0)
masked_data = cv2.bitwise_and(img, img, mask=mask)
x, y, w, h = cv2.boundingRect(cnt)
dst = masked_data[y: y + h, x: x + w]
dst_gray = cv2.cvtColor(dst, cv2.COLOR_BGR2GRAY)
_, alpha = cv2.threshold(dst_gray, 0, 255, cv2.THRESH_BINARY)
b, g, r = cv2.split(dst)
rgba = [r, g, b, alpha]
dst = cv2.merge(rgba, 4)
return dst
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment