Search code examples
pythonopencvimage-processingcolorsopacity

How to do transparent color inside the boundry in python


I have the images of brain tumor detection I want to do the transparent color inside the boundary of detection in python.

Transparent color will be same as the boundary color (122, 160, 255) with low opacity.

Image of Brain Tumor Detection

Expected Output: Expected Image


Solution

  • Here's a way of doing this:

    • load boundary image in greyscale and threshold
    • find approximate centre of tumour
    • flood-fill tumour interior with value=64, leaving boundary=255
    • create a peachy overlay same size as original
    • push the greyscale into the peachy overlay as alpha layer
    • paste the overlay onto original

    #!/usr/bin/env python3
    
    from PIL import Image, ImageDraw
    
    # Open boundary image and ensure greyscale
    im = Image.open('boundary.png').convert('L')
    
    # Get the bounding box so we can guesstimate its centre for flood-filling
    bbox = im.getbbox()
    cx = int((bbox[0]+bbox[1])/2)
    cy = int((bbox[2]+bbox[3])/2)
    print(f'DEBUG: cx={cx}, cy={cy}')
    
    # Threshold the boundary image to pure black and white
    thresh = im.point(lambda p: 255 if p>128 else 0)
    
    # Flood-fill with 64 starting from the centre and proceeding to a pure white boundary border
    ImageDraw.floodfill(thresh, (cx,cy), 64, border=255)
    thresh.save('DEBUG-flood-filled.png')
    
    # Open the original image
    scan = Image.open('a0pMX.png')
    
    # Create a peachy overlay, then push in the alpha layer
    overlay = Image.new('RGB', scan.size, 'rgb(255,160,122)')
    overlay.putalpha(thresh)
    overlay.save('DEBUG-overlay.png')
    
    # Paste the overlay onto the scan
    scan.paste(overlay, mask=overlay)
    scan.save('result.png')
    

    Here are the intermediate images:

    DEBUG-flood-filled.png

    enter image description here

    DEBUG-overlay.png

    enter image description here

    result.png

    enter image description here