Skip to content
Advertisement

How to extract a segmented object or change the background of the original image?

I am doing a detection with Mask R-CNN of one model available at Train Mask R-CNN for Image Segmentation.

  • Code I
JavaScript
  • First attempt

After training I tried to change the background color of the image using the code available at Change the Background of Any Image with 5 Lines of Code. Although it is working, it is not worth it for me to use another model to change the background.

  • Second attempt

Using a suggestion that is also available at Can anyone tell me how can I change mask the foreground if I know the color range of background in RGB?. I added the following line of code img2[ ~mask ] = [0,0,0].

This solution works if for the detected object is only one mask, otherwise it will not work so well. Example:

Example

To solve this problem I created an empty list and did the operation inside of the for loop, but it didn’t work.

I noticed that in the current way, only the last mask is taken. Is there a way to get all masks? because if there is more than one object in the image this code doesn’t work either.

Advertisement

Answer

I can’t test it but if you have mask as numpy.array with the same size as image then you can use it to replace pixels in image

JavaScript

For example

python – Can anyone tell me how can I change mask the foreground if I know the color range of background in RGB? – Stack Overflow

Finding red color in image using Python & OpenCV – Stack Overflow


If you have more masks then you can use operation OR on all masks to create one mask

JavaScript

In your code it could be

JavaScript

or using loop (to make it more universal)

JavaScript

If you would have list of masks then you could use

JavaScript

or you could use function functools.reduce() (to make it more universal)

JavaScript

or shorter

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement