Python - replicating the GIMP's "Erase color" blend mode

197 Views Asked by At

I'm looking for a way to recreate the GIMP's Erase color blending mode in Python 3 & OpenCV2.

I know it's possible to erase color using the that library, but the code I run works on exactly one of them. Furthermore, I don't believe such small amount of code could do that advanced thing.

Looking for a solution, I found the blend-modes by flrs, but it also doesn't include the option I want.


Sadly, I have no experience in OpenCV2 at the moment, but I think developing such thing could be very helpful.

Can someone guide me how to make this more reliable, or is it even possible to do with things that I've got already?


OpenCV2 color removal

Code

import cv2
from PIL import Image

#-=-=-=-#

File_Name = r"Spectrogram.png"
SRC = cv2.imread(File_Name, 1)
TMP = cv2.cvtColor(SRC, cv2.COLOR_BGR2GRAY)
_, A = cv2.threshold(TMP, 0, 255, cv2.THRESH_BINARY)
B, G, R = cv2.split(SRC)
Colors = [B, G, R, A]
Picture = cv2.merge(Colors, 4)

#-=-=-=-#

# My CV2 image display doesn't include transparency
im = cv2.cvtColor(Picture, cv2.COLOR_BGR2RGB)
im = Image.fromarray(im)

im.show()

Result

Original Result

GIMP Erase color blending-mode

Type Background Foreground Result
Image
Blending Normal Erase color Normal
1

There are 1 best solutions below

1
On

Here is one simple way in Python/OpenCV.

  • Read the input
  • Choose a color range
  • Apply range to threshold the image
  • Invert the range as a mask to be used later for the alpha channel
  • Convert the image from BGR to BGRA
  • Put mask into the alpha channel of the BGRA image
  • Save the result

Input:

enter image description here

import cv2
import numpy as np

# load image and set the bounds
img = cv2.imread("red_black.png")

# choose color range
lower =(0,0,0) # lower bound for each BGR channel
upper = (140,0,190) # upper bound for each BRG channel

# create the mask
mask = cv2.inRange(img, lower, upper)

# invert mask
mask = 255 - mask

# convert image to BGRA
result = cv2.cvtColor(img, cv2.COLOR_BGR2BGRA)

# put mask into alpha channel
result[:,:,3] = mask

# write result to disk
cv2.imwrite("red_black_color_removed.png", result)

# display it (though does not display transparency properly)
cv2.imshow("mask", mask)
cv2.imshow("results", result)
cv2.waitKey(0)

Result:

enter image description here