簡體   English   中英

使用 Python 和 OpenCV 改善圖像偏移

[英]Improving image deskew using Python and OpenCV

我生成的用於檢測和糾正偏斜的代碼給出了不一致的結果。 我目前正在開展一個項目,該項目利用圖像上的 OCR 文本提取(通過 Python 和 OpenCV),因此如果需要准確的結果,消除傾斜是關鍵。 我的代碼使用cv2.minAreaRect來檢測偏斜。

我使用的圖像都是相同的(將來也會如此),所以我不確定是什么導致了這些不一致。 我在應用代碼的地方包含了兩組前后圖像(包括來自cv2.minAreaRect的偏斜值),其中一組顯示成功去除偏斜並顯示偏斜未被去除(看起來它增加了更多偏斜)。

圖 1 之前 ( -87.88721466064453 )圖 1 之前

圖 1 之后(成功去歪斜)圖 1 之后

圖 2 之前 ( -5.766754150390625 )圖 2 之前

圖 2 之后(去歪斜不成功)圖 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)

我瀏覽了各種帖子和文章以找到合適的解決方案,但沒有成功。 這篇文章對理解偏斜值最有幫助,但即便如此我也無法深入了解。

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 去偏:

在此處輸入圖像描述

我已經在這里回答了這個問題: 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/

暫無
暫無

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

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