使用 Python 从图像中删除所有特定颜色(具有颜色变化容差)

Bas*_*asj 3 python opencv colors image-processing python-imaging-library

我在 PNG 图像(白色背景)上有一些蓝色文本 #00a2e8 和一些黑色文本。

如何使用Python PIL或OpenCV删除图像上的蓝色所有内容(包括蓝色文本),并对颜色变化有一定的容忍度?

事实上,文本的每个像素的颜色并不完全相同,存在变化,蓝色深浅不同。

这就是我的想法:

  • 从 RGB 转换为 HSV
  • h0找到蓝色的色调
  • 在间隔中为 Hue 做一个 Numpy 掩码[h0-10, h0+10]
  • 将这些像素设置为白色

在编码之前,是否有更标准的方法使用 PIL 或 OpenCV Python 来执行此操作?

示例PNG 文件:应删除foobar

在此输入图像描述

Mar*_*ell 7

你的头像有一些问题。首先,它有一个完全多余的 alpha 通道,可以忽略不计。其次,蓝色周围的颜色与蓝色相差很远!

我使用了您计划的方法,发现删除效果非常差:

#!/usr/bin/env python3

import cv2
import numpy as np

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

# Define lower and upper limits of our blue
BlueMin = np.array([90,  200, 200],np.uint8)
BlueMax = np.array([100, 255, 255],np.uint8)

# Go to HSV colourspace and get mask of blue pixels
HSV  = cv2.cvtColor(im,cv2.COLOR_BGR2HSV)
mask = cv2.inRange(HSV, BlueMin, BlueMax)

# Make all pixels in mask white
im[mask>0] = [255,255,255]
cv2.imwrite('DEBUG-plainMask.png', im)
Run Code Online (Sandbox Code Playgroud)

这给出了:

在此输入图像描述

如果扩大范围,为了获得粗糙的边缘,就会开始影响绿色字母,因此我扩大了蒙版,使空间上靠近蓝色的像素变成白色,并且在色彩上靠近蓝色的像素也变成白色:

# Try dilating (enlarging) mask with 3x3 structuring element
SE   = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3,3))
mask = cv2.dilate(mask, kernel, iterations=1)

# Make all pixels in mask white
im[mask>0] = [255,255,255]
cv2.imwrite('result.png', im)
Run Code Online (Sandbox Code Playgroud)

这会给你带来这个:

在此输入图像描述

您可能希望修改其他图像的实际值,但原理是相同的。