user3960019 user3960019 - 3 months ago 13
Python Question

how to use mask to remove the background in python

I want to remove the background by using the mask image. Now, I have already get the mask image.I try to let the value of the original image's background become 0 where the value of mask is 0. But the result is very bad. How can I solve this problem. Thank you

from skimage import io
import numpy as np
img = io.imread("GT06.jpg")
mask = io.imread("GT03.png")
mask2 = np.where((mask==0),0,1).astype('uint8')
img = img*mask2[:,:,np.newaxis]


enter image description here


enter image description here

This results in:
enter image description here

I want to get the foreground like this:

enter image description here


The problem is that your mask isn't pure black and white, i.e. all 0 or 255 changing you mask two generation to:

mask2 = np.where((mask<200),0,1).astype('uint8')

results in:


You could either play with the mask or the threshold number - I used 200.