使用Python OpenCV删除图像的黑色标题部分 [英] Remove black header section of image using Python OpenCV
问题描述
我需要使用Python CV删除图像多个部分中的变黑部分. 我尝试了去噪效果不佳的问题.
I need to remove the blackened section in multiple parts of image using Python CV. I tried with denoising which doesn't give satisfactory results.
例如.我需要删除表格标题中的变黑的部分(下图),并将标题背景转换为白色,内容为黑色.
Eg. I need to remove the blackened part in Table Header (below image) and convert the header background to white with contents as black.
有人可以帮助我选择正确的库或解决方案来解决这个问题吗?
推荐答案
这是@eldesgraciado方法的修改版本,该方法使用形态学的命中或未命中操作对Python中的目标像素进行过滤,以对点状图案进行过滤.区别在于,我们没有用二进制图像减去掩码来降低文本质量,而是先对二进制图像进行扩展,然后按位进行扩展,以保持文本质量.
Here's a modified version of @eldesgraciado's approach to filter the dotted pattern using a morphological hit or miss operation on the target pixels in Python. The difference is that instead of subtracting the mask with the binary image which decreases text quality, we dilate the binary image then bitwise-and to retain the text quality.
-
获取二进制图像.加载灰度图像, 执行形态学命中或未命中操作.我们使用
cv2.filter2D
对图像进行卷积Perform morphological hit or miss operation. We create a dot pattern kernel with
cv2.getStructuringElement
then usecv2.filter2D
to convolve the image删除点..我们
cv2.bitwise-xor
具有二进制图像的蒙版Remove dots. We
cv2.bitwise-xor
the mask with the binary image修复损坏的文本像素..我们
cv2.bitwise_and
带有输入图像和彩色背景像素为白色的最终蒙版Fix damaged text pixels. We
cv2.dilate
thencv2.bitwise_and
the finalized mask with the input image and color background pixels white
二进制图片
Binary image
点罩
删除点
膨胀以修复阈值处理过程中损坏的文本像素
Dilate to fix damaged text pixels from the thresholding process
结果
代码
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()
这篇关于使用Python OpenCV删除图像的黑色标题部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!