Wednesday, 9 February 2022

Python OpenCV: Crop image to contents, and make background transparent

I have the following image:

Image 1

I want to crop the image to the actual contents, and then make the background (the white space behind) transparent. I have seen the following question: How to crop image based on contents (Python & OpenCV)?, and after looking at the answer, and trying it, I got the following code:

img = cv.imread("tmp/"+img+".png")
mask = np.zeros(img.shape[:2],np.uint8)

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

rect = (55,55,110,110)
cv.grabCut(img,mask,rect,bgdModel,fgdModel,5,cv.GC_INIT_WITH_RECT)

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

plt.imshow(img),plt.colorbar(),plt.show()

But when I try this code, I get the following result: Result

Which isn't really the result I'm searching for, expected result:

expected result



from Python OpenCV: Crop image to contents, and make background transparent

No comments:

Post a Comment