Created
February 29, 2020 17:31
-
-
Save Vadbeg/073d77fd04696e521f15dae4476bee94 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
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