【问题标题】:Improving image deskew using Python and OpenCV使用 Python 和 OpenCV 改善图像偏斜
【发布时间】:2022-02-25 00:02:15
【问题描述】:

我为检测和纠正偏斜而生成的代码给了我不一致的结果。我目前正在开展一个项目,该项目利用图像上的 OCR 文本提取(通过 Python 和 OpenCV),因此如果需要准确的结果,消除偏斜是关键。我的代码使用cv2.minAreaRect 来检测歪斜。

我使用的图像都是相同的(将来也会如此),所以我不确定是什么导致了这些不一致。我在其中应用了我的代码时包含了两组前后图像(包括来自cv2.minAreaRect 的偏斜值),其中一组显示成功移除偏斜并且未移除偏斜(看起来它增加了更多偏斜)。

图片 1 之前 (-87.88721466064453)

图像 1 之后(成功的纠偏)

图片 2 之前 (-5.766754150390625)

图像 2 之后(不成功的纠偏)

我的代码如下。注意:我使用的图像比此处包含的图像要多得多。到目前为止,检测到的偏差一直在 [-10, 0) 或 (-90, -80] 范围内,因此我试图在我的代码中考虑这一点。

    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    img_gray = cv2.bitwise_not(img_gray)
    
    thresh = cv2.threshold(img_gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
    coords = np.column_stack(np.where(thresh > 0))
    angle = cv2.minAreaRect(coords)[-1] 
      
    if (angle < 0 and angle >= -10):
        angle = -angle #this was intended to undo skew for values in [-10, 0) by simply rotating using the opposite sign
    else:
        angle = (90 + angle)/2  
     
    (h, w) = img.shape[:2]
    center = (w // 2, h // 2)
    
    M = cv2.getRotationMatrix2D(center, angle, 1.0)
    deskewed = cv2.warpAffine(img, M, (w, h), flags = cv2.INTER_CUBIC, borderMode = cv2.BORDER_REPLICATE)

我浏览了各种帖子和文章以找到适当的解决方案,但没有成功。 This post 对理解偏差值最有帮助,但即便如此我也无法走得太远。

【问题讨论】:

标签: python opencv image-processing skew


【解决方案1】:

可以在 Python Wand 中找到一个非常好的文本校正工具,它使用 ImageMagick。它基于 Radon 变换。

表格一:

表格2:

from wand.image import Image
from wand.display import display


with Image(filename='form1.png') as img:
    img.deskew(0.4*img.quantum_range)
    img.save(filename='form1_deskew.png')
    display(img)

with Image(filename='form2.png') as img:
    img.deskew(0.4*img.quantum_range)
    img.save(filename='form2_deskew.png')
    display(img)

表格 1 去偏:

表格 2 偏斜:

【讨论】:

    【解决方案2】:

    我已经在这里回答了这个问题:How to deskew a scanned text page with ImageMagick?

    以下是可以帮助您歪斜图像的代码:

    import numpy as np
    from skimage import io
    from skimage.transform import rotate
    from skimage.color import rgb2gray
    from deskew import determine_skew
    from matplotlib import pyplot as plt
    
    def deskew(_img):
        image = io.imread(_img)
        grayscale = rgb2gray(image)
        angle = determine_skew(grayscale)
        rotated = rotate(image, angle, resize=True) * 255
        return rotated.astype(np.uint8)
    
    def display_before_after(_original):
        plt.subplot(1, 2, 1)
        plt.imshow(io.imread(_original))
        plt.subplot(1, 2, 2)
        plt.imshow(deskew(_original))
    
    display_before_after('img_35h.jpg')
    
    

    之前:

    之后:

    参考及来源:http://aishelf.org/deskew/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-17
      • 2011-02-03
      • 1970-01-01
      • 1970-01-01
      • 2020-09-30
      • 2018-06-20
      • 2018-04-14
      • 1970-01-01
      相关资源
      最近更新 更多