Home > database >  Method to invert background color and retain foreground in OpenCV?
Method to invert background color and retain foreground in OpenCV?

Time:06-06

I have a binary image where I am trying to identify the shape inside of a black blob. Both the background and the object of interest are white. I am trying to find a solution to inverting only the white background such that the only white pixels remaining is the shape inside of the black blob. Is there a way to separate identifying all the white pixels from the background from the white pixels of the object?

Sample Input:

white arrow in black blob

Desired Output:

white arrow with black background

CodePudding user response:

It's clear that the background is not "surrounded" anywhere by the black object. Then you can use cv2.floodFill to fill the white background with new_color:

# assuming `img` is binary image
seed = (0,0)            # a point in the background, here I choose top-left corner
new_color = (0,0,0)     # since you want to make it black
cv2.floodFill(img, None, seedPoint=seed, newVal=new_color)
cv2.imshow('flood', img)

Note that this function is an in-place operation, which means changes are applied directly to img. If you want to keep your old img, consider copying it:

backup_img = np.copy(img)
  • Related