Home > OS >  How to remove blue from an image using opencv?
How to remove blue from an image using opencv?

Time:11-12

I have this map with a blue square I would like to remove: sample here

I've tried using open cv to do so but I've been wildly unsuccessful. I used the solution here to no avail. The output looks exactly like the original. The blue square is the one intersecting with the red one at the bottom right. That's what I want to remove.

Here is my latest attempt:

from PIL import Image
import PIL.ImageOps    
import numpy as np
from skimage.io import imsave
import cv2
    
in_path  = 'map.jpeg'
out_path = 'new_output.jpeg'
       
Image = cv2.imread(in_path)
Image2 = np.array(Image, copy=True)
    
white_px = np.asarray([0, 0, 255])
black_px = np.asarray([255  , 255  , 255  ])
    
(row, col, _) = Image.shape
    
for r in range(row):
    for c in range(col):
        px = Image[r][c]
        if all(px == white_px):
           Image2[r][c] = black_px
    
imsave(out_path, Image2)

CodePudding user response:

just assign blue channel to zeros

src = cv2.imread('D:/original.png', cv2.IMREAD_UNCHANGED)
src[:,:,0] = np.zeros([src.shape[0], src.shape[1]])
cv2.imwrite('D:/no-blue-channel.png',src) 

CodePudding user response:

I made a test image like this:

magick -size 400x200 gradient:magenta-lime -stroke blue -fill none  antialias -draw "rectangle 10,10 390,190" a.png

enter image description here

Now there are a couple of ways you can approach this. You could replace all blue pixels with white:

import numpy as np
import cv2

# Load image
filename = 'a.png'
im  = cv2.imread(filename)

# Method 1: Simplistic overpaint blue with white
im[np.all(im == (255, 0, 0), axis=-1)] = np.uint8([255,255,255])
cv2.imwrite('result-white.png', im)

enter image description here

Or, maybe slightly better suited to the upper half of this image, replace blue with magenta:

enter image description here


Or you could "inpaint" - what Photoshop calls "Content Aware Fill" - which means that replacement pixels are guesstimated using the surrounding area:

# Method 2: Inpaint - or Photoshop "Content Aware Fill"
im  = cv2.imread(filename)
# Make mask of blue pixels - True where blue, False elsewhere
mask = np.all(im == (255, 0, 0), axis=-1)

# Inpaint white areas and save
# Options are: cv2.INPAINT_TELEA or cv2.INPAINT_NS
result = cv2.inpaint(im,np.uint8(mask)*255,3,cv2.INPAINT_TELEA)
cv2.imwrite('result-TELEA.png',result)
result = cv2.inpaint(im,np.uint8(mask)*255,3,cv2.INPAINT_NS)
cv2.imwrite('result-NAVIER-STOKES.png',result)

That gives this result:

enter image description here

  • Related