Removing black background and make transparent from grabcut output in python open cv

Srikanth picture Srikanth · Nov 10, 2016 · Viewed 24.1k times · Source

I have been trying to remove the black background from the grabcut output using python opencv.

import numpy as np
import cv2

img = cv2.imread(r'myfile_1.png')
mask = np.zeros(img.shape[:2],np.uint8)

bgdModel = np.zeros((1,65),np.float64)
fgdModel = np.zeros((1,65),np.float64)

rect = (1,1,665,344)
cv2.grabCut(img,mask,rect,bgdModel,fgdModel,5,cv2.GC_INIT_WITH_RECT)

mask2 = np.where((mask==2)|(mask==0),0,1).astype('uint8')
img = img*mask2[:,:,np.newaxis]

cv2.imshow('img',img)
cv2.imwrite('img.png',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Above code I had written to save the grabcut output. Please suggest, How I can remove the black background and make it transparent?

enter image description here

enter image description here

Answer

Srikanth picture Srikanth · Nov 11, 2016

I have achieved this by using the following snippet.

import cv2
file_name = "grab.png"

src = cv2.imread(file_name, 1)
tmp = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
_,alpha = cv2.threshold(tmp,0,255,cv2.THRESH_BINARY)
b, g, r = cv2.split(src)
rgba = [b,g,r, alpha]
dst = cv2.merge(rgba,4)
cv2.imwrite("test.png", dst)

enter image description here