opencv 中 OCR 的 90 度倾斜校正 python
90 degree Skew Correction for OCR in opencv python
偏斜校正在 OCR 中很常见,我使用 houghLinesP() 的偏斜校正代码发现偏斜图像的角度工作正常。我想问的是 你如何处理倾斜 90 度的图像? 因为角度可能是 0 度并且 tesseract 不会提取任何文本。
那么如何处理这个问题呢?
您可以使用tesseract
的osd
功能进行偏斜校正。即使对于正常图像,使用传统图像处理进行倾斜校正可能有效,但对于扫描图像和低质量图像,传统方法可能会失败。所以最好使用 tesseract
提供的 osd 功能
import pytesseract
import cv2
import numpy as np
###function to rotate image
def rotate_bound(image, angle):
"""Rotate image with the given angle
:param type image: input image
:param type angle: Angle to be rotated
:return: rotated image
:rtype: numpy.ndarray
"""
(h, w) = image.shape[:2]
### centroid
(cX, cY) = (w // 2, h // 2)
### creating rotation matrix
M = cv2.getRotationMatrix2D((cX, cY), -angle, 1.0)
cos = np.abs(M[0, 0])
sin = np.abs(M[0, 1])
nW = int((h * sin) + (w * cos))
nH = int((h * cos) + (w * sin))
M[0, 2] += (nW / 2) - cX
M[1, 2] += (nH / 2) - cY
return cv2.warpAffine(image, M, (nW, nH))
###read input image
image=cv2.imread('path/to/image.jpg')
###getting orientation info
newdata=pytesseract.image_to_osd(image)
###filter angle value
angle=re.search('(?<=Rotate: )\d+', newdata).group(0)
print('osd angle:',angle)
### rotating image with angle
skew_corrected_image=rotate_bound(image,float(angle))
### you can add tesseract OCR call here
偏斜校正在 OCR 中很常见,我使用 houghLinesP() 的偏斜校正代码发现偏斜图像的角度工作正常。我想问的是 你如何处理倾斜 90 度的图像? 因为角度可能是 0 度并且 tesseract 不会提取任何文本。
那么如何处理这个问题呢?
您可以使用tesseract
的osd
功能进行偏斜校正。即使对于正常图像,使用传统图像处理进行倾斜校正可能有效,但对于扫描图像和低质量图像,传统方法可能会失败。所以最好使用 tesseract
import pytesseract
import cv2
import numpy as np
###function to rotate image
def rotate_bound(image, angle):
"""Rotate image with the given angle
:param type image: input image
:param type angle: Angle to be rotated
:return: rotated image
:rtype: numpy.ndarray
"""
(h, w) = image.shape[:2]
### centroid
(cX, cY) = (w // 2, h // 2)
### creating rotation matrix
M = cv2.getRotationMatrix2D((cX, cY), -angle, 1.0)
cos = np.abs(M[0, 0])
sin = np.abs(M[0, 1])
nW = int((h * sin) + (w * cos))
nH = int((h * cos) + (w * sin))
M[0, 2] += (nW / 2) - cX
M[1, 2] += (nH / 2) - cY
return cv2.warpAffine(image, M, (nW, nH))
###read input image
image=cv2.imread('path/to/image.jpg')
###getting orientation info
newdata=pytesseract.image_to_osd(image)
###filter angle value
angle=re.search('(?<=Rotate: )\d+', newdata).group(0)
print('osd angle:',angle)
### rotating image with angle
skew_corrected_image=rotate_bound(image,float(angle))
### you can add tesseract OCR call here