Search code examples
pythonimage-processing

How to Remove Residuals in Images using Python


Image1 contains rectangles with residuals Image1

and Image2 represents the desired result. Image2

I want to achieve the same result as Image2 using Image1 in Python, but I'm unsure if it's possible and have no idea about the necessary methods.

I tried to use the transparency of the image to remove it, but I'm not sure if that's even possible.


Solution

  • Your "residual" images are less saturated than the "core" images, so you can separate the "resiiduals" from the "cores" in HSV colourspace, see Wikipedia HSV article.

    Using ImageMagick, I can convert your image to HSV colourspace, discard the H and V channels and then threshold the Saturation channel to find the most saturated areas like this:

    magick INPUT.PNG -colorspace HSV -separate -delete 0,2 -threshold 75% rssult.png
    

    enter image description here


    Using Python and OpenCV, that looks roughly like this:

    import cv2 as cv
    import numpy as np
    
    # Load image
    im = cv.imread(YOURIMAGE)
    
    # Convert to HSV colourspace and split channels
    hsv = cv.cvtColor(im, cv.COLOR_BGR2HSV)
    H, S, V = cv.split(hsv)
    
    # Make mask of areas of high saturation 
    coreMask = S > 200
    
    # Scale up from range 0..1 to range 0..255 and save as PNG
    cv.imwrite('result.png', coreMask * 255)
    

    If I split the image into its H, S and V components and plot H (Hue) on the left, S (Saturation) in the centre and V (Value, i.e. brightness) on the right, you can see in the central S (Saturation) image that the pixel values are higher for your "core" shapes and lower for your "residuals":

    enter image description here