簡體   English   中英

從圖像中刪除嘈雜的線條

[英]Remove noisy lines from an image

我的圖像帶有一些隨機線條,如下所示:
在此處輸入圖片說明
我想對它們進行一些預處理,以去除不需要的噪音(扭曲書寫的線條),以便我可以將它們與 OCR(Tesseract)一起使用。
我想到的想法是使用擴張來消除噪音,然后在第二步中使用侵蝕來修復寫作的缺失部分。
為此,我使用了以下代碼:

import cv2
import numpy as np

img = cv2.imread('linee.png', cv2.IMREAD_GRAYSCALE)
kernel = np.ones((5, 5), np.uint8)
img = cv2.dilate(img, kernel, iterations=1)
img = cv2.erode(img, kernel, iterations=1)
cv2.imwrite('delatedtest.png', img)

不幸的是,擴張效果不佳,噪聲線仍然存在。

在此處輸入圖片說明
我嘗試更改內核形狀,但情況變得更糟:文字被部分或完全刪除。
我還找到了一個答案,說可以通過以下方式刪除這些行

將具有兩個或更少相鄰黑色像素的所有黑色像素變為白色。

這對我來說似乎有點復雜,因為我是計算機視覺和 opencv 的初學者。
任何幫助將不勝感激,謝謝。

像這樣的檢測線就是路徑開口的發明目的。 DIPlib有一個實現(披露:我在那里實現了它)。 作為替代方案,您可以嘗試使用我上面鏈接的論文 作者的實現 該實現沒有我在下面使用的“約束”模式

這是一個關於如何使用它的快速演示:

import diplib as dip
import matplotlib.pyplot as pp

img = 1 - pp.imread('/home/cris/tmp/DWRTF.png')
lines = dip.PathOpening(img, length=300, mode={'constrained'})

在這里,我們首先反轉圖像,因為這使以后的其他事情更容易。 如果不反轉,請改用路徑閉合。 lines圖:

線

接下來我們減去線條。 一個小區域的開口去除了被路徑開口過濾掉的線的幾個孤立像素:

text = img - lines
text = dip.AreaOpening(text, filterSize=5)

文本

但是,我們現在在文本中出現了空白。 填寫這些並非易事。 這是一個快速而骯臟的嘗試,您可以將其用作起點:

lines = lines > 0.5
text = text > 0.5
lines -= dip.BinaryPropagation(text, lines, connectivity=-1, iterations=3)
img[lines] = 0

最后結果

您可以使用來自 opencv 的函數createLineSegmentDetector()來做到這一點

import cv2

#Read gray image
img = cv2.imread("lines.png",0)

#Create default parametrization LSD
lsd = cv2.createLineSegmentDetector(0)

#Detect lines in the image
lines = lsd.detect(img)[0] #Position 0 of the returned tuple are the detected lines

#Draw the detected lines
drawn_img = lsd.drawSegments(img,lines)

#Save the image with the detected lines
cv2.imwrite('lsdsaved.png', drawn_img)

在此處輸入圖片說明
代碼的下一部分將僅刪除長度超過 50 像素的行:

for element in lines:

  #If the length of the line is more than 50, then draw a white line on it
  if (abs(int(element[0][0]) - int(element[0][2])) > 50 or abs(int(element[0][1]) - int(element[0][3])) > 50): 

    #Draw the white line
    cv2.line(img, (int(element[0][0]), int(element[0][1])), (int(element[0][2]), int(element[0][3])), (255, 255, 255), 12)

#Save the final image
cv2.imwrite('removedzz.png', img)

在此處輸入圖片說明

好吧,它不能與當前圖像完美配合,但它可能會為不同的圖像提供更好的結果。 您可以調整要刪除的線的長度和要繪制的白線的粗細,以代替已刪除的線。
我希望它有幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM