我有几百张图片(扫描文档),其中大部分都被倾斜了。我想用Python对它们进行去斜校正。
这是我使用的代码:
import numpy as np
import cv2
from skimage.transform import radon
filename = 'path_to_filename'
# Load file, converting to grayscale
img = cv2.imread(filename)
I = cv2.cvtColor(img, COLOR_BGR2GRAY)
h, w = I.shape
# If the resolution is high, resize the image to reduce processing time.
if (w > 640):
I = cv2.resize(I, (640, int((h / w) * 640)))
I = I - np.mean(I) # Demean; make the brightness extend above and below zero
# Do the radon transform
sinogram = radon(I)
# Find the RMS value of each row and find "busiest" rotation,
# where the transform is lined up perfectly with the alternating dark
# text and white lines
r = np.array([np.sqrt(np.mean(np.abs(line) ** 2)) for line in sinogram.transpose()])
rotation = np.argmax(r)
print('Rotation: {:.2f} degrees'.format(90 - rotation))
# Rotate and save with the original resolution
M = cv2.getRotationMatrix2D((w/2,h/2),90 - rotation,1)
dst = cv2.warpAffine(img,M,(w,h))
cv2.imwrite('rotated.jpg', dst)
这段代码在大多数文档中运行良好,但对于一些角度(180和0)以及(90和270),经常被检测为相同的角度(即不区分(180和0)和(90和270))。因此我得到了很多倒置的文档。
得到的图像与输入图像相同。
有没有建议使用Opencv和Python检测图像是否倒置?
PS:我尝试使用EXIF数据检查方向,但没有解决方案。
编辑:
可以使用Tesseract(Python的pytesseract)检测方向,但仅当图像包含大量字符时才可能。对于可能需要此功能的任何人:
import cv2
import pytesseract
print(pytesseract.image_to_osd(cv2.imread(file_name)))
如果文档包含足够多的字符,Tesseract可以检测方向。然而,当图像只有几行时,Tesseract建议的方向角度通常是错误的。因此,这并不能是一个100%的解决方案。
如果文档包含足够多的字符,Tesseract可以检测方向。然而,当图像只有几行时,Tesseract建议的方向角度通常是错误的。因此,这并不能是一个100%的解决方案。