Image Magick命令的等效OpenCV代码

时间:2019-10-31 03:26:56

标签: python-3.x opencv imagemagick image-morphology

我正在尝试对图像进行预处理,以从其中删除水平线和垂直线(某些OCR要求)。我得到了一些Image Magick代码来完成同样的工作,效果很好。以下是代码段:

magick convert ( img_name.jpg )    
( -clone 0 -morphology close rectangle:1x50 -negate +write tmp1.png )    
( -clone 0 -morphology close rectangle:50x1 -negate +write tmp2.png )    
( -clone 1 -clone 2 -evaluate-sequence add +write tmp3.png )
-delete 1,2     
-compose plus -composite    
result.jpg

这是从下面的链接获得的(对他们的完整感谢):

Remove all horizontal and vertical lines from an image

问题是,即使Image Magick运作良好,在高分辨率图像上(我最常使用的时间)也要花费很长时间。因此,我试图将上述代码片段转换为Open CV Python代码。我已经为第1步和第2步编写了部分代码。

步骤1和2:

img = cv2.imread('img_name.jpg', cv2.IMREAD_COLOR)
kernel_vertical = cv2.getStructuringElement(cv2.MORPH_RECT, (1,50))
kernel_horizontal = cv2.getStructuringElement(cv2.MORPH_RECT, (50,1))

temp_1 = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel_vertical)
#cv2.imwrite('temp_1.png',temp_1)

temp_2 = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel_horizontal)
#cv2.imwrite('temp_2.png',temp_2)

但是,由于我不确定 evaluate-sequence 运算符的确切功能,因此无法执行第3步和第4步。我在网上查询过,但了解得还不够。如果有人能够帮助我翻译其余的步骤,我将不胜感激。

1 个答案:

答案 0 :(得分:3)

这是Python / OpenCV中的等效命令。

输入:

enter image description here

import cv2
import numpy as np

img = cv2.imread('document.png')

# do morphology to locate vertical lines and invert
kernel_vertical = cv2.getStructuringElement(cv2.MORPH_RECT, (1,50))
temp1 = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel_vertical)
temp1 = (255-temp1)

# do morphology to locate horizontal lines and invert
kernel_horizontal = cv2.getStructuringElement(cv2.MORPH_RECT, (50,1))
temp2 = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel_horizontal)
temp2 = (255-temp2)

# add the two temp images together
temp = cv2.add(temp1, temp2)

# add temp to img to create result
result = cv2.add(temp, img)

# write result to disk
cv2.imwrite("document_lines_removed.png", result)

# display it
cv2.imshow("temp1", temp1)
cv2.imshow("temp2", temp2)
cv2.imshow("temp", temp)
cv2.imshow("result", result)
cv2.waitKey(0)


enter image description here