图像预处理
在ocr处理时候,可能遇到的图片会是倾斜的,导致检测不全问题,进而影响后续识别问题。
常见的倾斜矫正方法
- 霍夫变换轮廓检测
- randon 变换
- 基于PCA的方法
radon变换
本节说下randon变换
-
基本原理
Radon(拉东)算法是一种通过定方向投影叠加,找到最大投影值时角度,从而确定图像倾斜角度的算法。具体过程如图所示
-
实现
import cv2
import sys
import time
import numpy as np
from skimage.transform import radon
filename = sys.argv[1]
# Load file, converting to grayscale
t1 = time.time()
img = cv2.imread(filename)
I = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
h, w = I.shape
# If the resolution is high, resize the image to reduce processing time.
# lower resolution, lower process time.
"""
if (w > 640):
I = cv2.resize(I, (640, int((h / w) * 640)))
"""
if (w > 240):
I = cv2.resize(I, (240, int((h / w) * 240)))
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)
t2 = time.time()
print(t2-t1)
dst = cv2.warpAffine(img, M, (w, h))
cv2.imwrite('rotated.jpg', dst)
cv2.imshow('dst', dst)
cv2.waitKey()