如果存在白色和黑色背景,如何将整个图像的背景转换为白色?

问题描述 投票:1回答:2

表单图像包含不同背景的文本。图像需要转换为一个背景(此处为白色),因此标题需要转换为黑色。

输入图像:

enter image description here

输出图片:enter image description here

我的方法是检测网格(水平线和垂直线并将它们相加),然后将网格的每个部分裁剪成新的子图像,然后检查多数像素颜色并相应地进行变换。但在实现之后,蓝色背景图像没有被检测到并被裁剪为:

enter image description here

所以我试图将整个表单图像转换为一个背景,以便我可以避免这样的结果。

python-3.x opencv
2个回答
1
投票

这是一种可能的方法。如果转换为HSV色彩空间,蓝色阴影将显示比黑色和白色更高的饱和度,所以......

  • 转换为HSV
  • 找到每行的平均饱和度,并选择平均饱和度超过阈值的行
  • 灰度化那些行,反转并阈值它们

如果反向(突出)背景是除黑色或白色之外的任何颜色,则此方法应该有效。它假设您根据示例将图像偏斜为真正的垂直/水平。

在Python中看起来像这样:

#!/usr/bin/env python3

import cv2
import numpy as np

# Load image
im = cv2.imread('form.jpg')

# Make HSV and extract S, i.e. Saturation
hsv = cv2.cvtColor(im, cv2.COLOR_BGR2HSV)
s=hsv[:,:,1]
# Save saturation just for debug
cv2.imwrite('saturation.png',s)

# Make greyscale version and inverted, thresholded greyscale version
gr = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
_,grinv = cv2.threshold(gr,127,255,cv2.THRESH_BINARY_INV)

# Find row numbers of rows with colour in them
meanSatByRow=np.mean(s,axis=1)
rows = np.where(meanSatByRow>50)

# Replace selected rows with those from the inverted, thresholded image
gr[rows]=grinv[rows]

# Save result
cv2.imwrite('result.png',gr)

结果如下:

enter image description here

饱和度图像如下所示 - 请注意饱和色(即蓝色)显示为浅色,其他一切显示为黑色:

enter image description here

灰度,倒像图像如下所示:

enter image description here


0
投票

这是一种不同的方式,可以应对“反向视频”是黑色的,而不是依靠一些颜色饱和来找到它。

#!/usr/bin/env python3

import cv2
import numpy as np

# Load image, greyscale and threshold
im = cv2.imread('form.jpg',cv2.IMREAD_GRAYSCALE)

# Threshold and invert
_,thr = cv2.threshold(im,127,255,cv2.THRESH_BINARY)
inv   = 255 - thr

# Perform morphological closing with square 7x7 structuring element to remove details and thin lines
SE = np.ones((7,7),np.uint8)
closed = cv2.morphologyEx(thr, cv2.MORPH_CLOSE, SE)
# DEBUG save closed image
cv2.imwrite('closed.png', closed)

# Find row numbers of dark rows
meanByRow=np.mean(closed,axis=1)
rows = np.where(meanByRow<50)

# Replace selected rows with those from the inverted image
im[rows]=inv[rows]

# Save result
cv2.imwrite('result.png',im)

结果如下:

enter image description here

中间的closed图像看起来像这样 - 我人为添加了一个红色边框,因此您可以在Stack Overflow的白色背景上看到它的范围:

enter image description here

你可以阅读关于形态学here和Anthony Thyssen,here的精彩描述。

© www.soinside.com 2019 - 2024. All rights reserved.