使用Python OpenCV删除图像的黑色标题部分

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

我需要使用Python CV删除图像多个部分中的变黑部分。我尝试了去噪效果不理想的问题。

例如我需要删除表格标题中的变黑部分(下图),并将标题背景转换为白色,内容为黑色。

enter image description here

任何人都可以帮助我选择正确的库或解决方案来克服这一问题吗?

python opencv image-processing deep-learning python-imaging-library
2个回答
2
投票

这是@eldesgraciado的方法的改进版本,该方法使用形态学的命中或未命中操作对Python中的目标像素进行过滤,以过滤点状图案。区别在于,我们没有用二进制图像减去掩码来降低文本质量,而是先对二进制图像进行扩展,然后按位进行扩展,并保留文本质量。

  1. 获得二进制图像。加载图像,灰度,Otsu's threshold

  2. 执行形态学命中或遗漏操作。我们用cv2.getStructuringElement创建一个点阵图形内核,然后使用cv2.getStructuringElement卷积图像

  3. [Remove points。我们用二进制图像cv2.filter2D遮罩

  4. 修复损坏的文本像素。然后,我们cv2.filter2D然后cv2.bitwise-xor使用输入图像和彩色背景像素为白色的定型蒙版


二进制图像

cv2.bitwise-xor

点罩

cv2.dilate

删除点

cv2.dilate

膨胀以修复阈值处理中损坏的文本像素

cv2.bitwise_and

结果

cv2.bitwise_and

代码

enter image description here

3
投票

如您所见,很难过滤虚线图案。它显然与文本重叠。我至少看到两个选择:1)利用模式的周期性,并执行频率滤波。 2)尝试对目标像素使用morphic hit or miss操作,目的是隔离它们。

让我们检查一下选项2。噪声的样式非常独特。如果使用所有斑点都为白色的二进制图像,则您要寻找的图案是白色像素(1)

,周围是8个黑色像素(0)
enter image description here

命中和遗漏操作可用于定位和隔离像素模式。如果您想了解更多信息,请enter image description here一篇好文章。现在,让我们来研究代码:

enter image description here

这是您得到的面具:

enter image description here

现在,只需将此蒙版减去原始(二进制)图像,即可得到:

import cv2 import numpy as np # Load image, grayscale, Otsu's threshold image = cv2.imread('1.jpg') gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1] # Perform morphological hit or miss operation kernel = np.array([[-1,-1,-1], [-1,1,-1], [-1,-1,-1]]) dot_mask = cv2.filter2D(thresh, -1, kernel) # Bitwise-xor mask with binary image to remove dots result = cv2.bitwise_xor(thresh, dot_mask) # Dilate to fix damaged text pixels # since the text quality has decreased from thresholding # then bitwise-and with input image kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (2,2)) dilate = cv2.dilate(result, kernel, iterations=1) result = cv2.bitwise_and(image, image, mask=dilate) result[dilate==0] = [255,255,255] cv2.imshow('dot_mask', dot_mask) cv2.imshow('thresh', thresh) cv2.imshow('result', result) cv2.imshow('dilate', dilate) cv2.waitKey()

如您所见,部分列标题妨碍了操作。如果您想要白色背景和黑色斑点,只需反转图像:

[ 0, 0, 0 ] [ 0, 1, 0 ] [ 0, 0, 0 ]

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