如何使用opencv从图像中去除蓝色?

How to remove blue from an image using opencv?

我有一张带有蓝色方块的地图,我想将其删除:

我试过使用 open cv 来这样做,但我一直非常不成功。我在这里使用解决方案无济于事。输出看起来和原来的一模一样。蓝色方块是与右下角红色方块相交的那个。这就是我要删除的内容。

这是我最近的尝试:

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)

只需将蓝色通道分配给零

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) 

我做了这样一张测试图:

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

现在有几种方法可以解决这个问题。您可以将所有蓝色像素替换为白色:

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)

或者,也许更适合这张图片的上半部分,将蓝色替换为洋红色:


或者您可以 “修复” - Photoshop 调用 “内容感知填充” - 这意味着使用周围区域猜测替换像素:

# 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)

结果如下: