检测图像中文字的旋转角度

时间:2019-04-02 19:05:18

标签: python opencv

因此,我有一个图像,该图像的文字位置不合适,无法从中提取信息,因此我需要找到某种旋转方法。

我尝试了太多的库和理论,但是没有什么特别的 OpenCV。 我将加入一个需要旋转的图像示例。 非常感谢。

https://drive.google.com/open?id=1gzF1VLtb8Q7gOQ6u0IzrB98Ae1VC3TPF

我尝试了例如:

import numpy as np
import cv2

image = cv2.imread("test1.jpg")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray = cv2.bitwise_not(gray)

thresh = cv2.threshold(gray, 0, 255,cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]

coords = np.column_stack(np.where(thresh > 0))
print coords
angle = cv2.minAreaRect(coords)[-1]
print angle 
if angle < -45:
    angle = -(90 + angle)
else:
    angle = -angle

(h, w) = image.shape[:2]
center = (w // 2, h // 2)
M = cv2.getRotationMatrix2D(center, angle, 1.0)
rotated = cv2.warpAffine(image, M, (w, h),flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE)   


cv2.putText(rotated, "Angle: {:.2f} degrees".format(angle),(10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)

print("[INFO] angle: {:.3f}".format(angle))

我也尝试了这个理论: 以特定的方向扫描文档,并总结每条扫描线上“黑色”像素的数量(创建一维计数数组,每个索引代表Y坐标,即轮廓)。 计算计数(配置文件)的方差。 重复多个角度(可以通过二进制搜索的方式来减少处理) 导致最大差异的角度是正确的角度(由于文本行从打印的文本中产生了较大的峰值,而由于行之间缺少文本而导致了低谷) 然后,在找到该角度之后,您可以相应地调整图像并进行出色的OCR。 下面的代码:

from PIL import Image

from resizeimage import resizeimage

jpgfile = Image.open("test.jpg")

#size = jpgfile.size[0]/5 , jpgfile.size[1]/5

#cover = resizeimage.resize_cover(jpgfile, size)

#cover.show()

for i in range(0,360):
#a reviser
    rotated = jpgfile.rotate(i)
    rotated.save("out.jpg")
    image = cv2.imread("out.jpg")
    gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
    ret,thresh = cv2.threshold(gray,127,255,cv2.THRESH_BINARY_INV)
#cv2.imshow('binary',thresh)
#cv2.waitKey(0)

    thresh_sum = thresh.sum(axis=1)
#thresh_sum.show

    a = []

    a = np.append(a,thresh_sum)
    variance = 0
    variance = np.var(thresh_sum,0)

    print(variance,i)

rotated.show() 

0 个答案:

没有答案
相关问题