Search code examples
python-3.xdicomimage-segmentation

Subtracting image background defined by segmentation masks in python


I want to segment the liver from medical images in python. My approach is organizing the images into folders (one folder for every patient ID) and combining every 2D image with its corresponding mask. The resulting image should be written so the same folder.

I already generated the masks. Adding the two images does not give the desired result, though, it should be some kind of 'inverse subtraction' but I don't know how to implement this.

I also do not know how to automate the process so that I don't have to always specify the folder - I want the program to be able to automatically switch between folders.

For example typing image1 = imread("/Downloads/image1"); image1_mask = imread("/Downloads/image1_mask"); result = image1 + image1_mask

requires me to specify the path for every image combination. Is there a good naming strategy to make the process easier? I tried to implement it with a for loop, but it doesn't work.

And as I said, addition does also not produce the desired result (neither does image subtraction)

Thank you in advance! Maria


Solution

  • You asked in fact several questions.

    If you want to display only these pixels, whos corresponding pixels of the mask are non-zero, then you need to multiplicate, not add. E.g.

    import numpy as np
    image = np.random.randint(1,255,(5,5))
    mask = np.zeros((5,5))
    mask[1:,2:4]=10
    newImage = image * (mask!=0)
    print(image, mask, newImage,sep='\n')
    

    Automating of passing directories is a completely different problem, there is a lot of similar questions on SO.