简体   繁体   English

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

[英]How to remove blue from an image using opencv?

I have this map with a blue square I would like to remove:我有一张带有蓝色方块的地图,我想删除它:样品在这里

I've tried using open cv to do so but I've been wildly unsuccessful.我试过使用 open cv 来做到这一点,但我一直很不成功。 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)

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) 

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

在此处输入图片说明

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)

在此处输入图片说明

Or, maybe slightly better suited to the upper half of this image, replace blue with magenta:或者,也许更适合这张图片的上半部分,用洋红色替换蓝色:

在此处输入图片说明


Or you could "inpaint" - what Photoshop calls "Content Aware Fill" - which means that replacement pixels are guesstimated using the surrounding area:或者你可以“补绘” -什么Photoshop中所说的“内容感知填充” -这意味着替代像素使用周边地区guesstimated:

# 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:这给出了这个结果:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM