使用 opencv 扫描文本角度修复 python
scanned text angle fix python using opencv
我不明白为什么转换不起作用,输出图像是:
所以阈值操作工作正常,但一定有某种问题
我似乎没有注意到转变。提前致谢!
import cv2
import numpy as np
#read the image, do binary processing
im = cv2.imread('scanned.png')
grey = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
cv2.imshow('gray', grey)
#the pixels are reversed to white and black
# gray = cv2.bitwise_not(gray)
ret, thresh = cv2.threshold(grey, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)
cv2.imshow('thresh', thresh)
#calculate the minimum border that contains rotated text
coords = np.column_stack(np.where(thresh > 0))
print(coords)
#unction gives the rectangle border containing the whole text area, and the rotation angle of this border is the same as that of the text in the figure
angle = cv2.minAreaRect(coords)[-1]
print(angle)
#adjust the angle
if angle < -45:
angle = -(90+ angle)
else:
angle = -angle
#transformation
h, w = im.shape[:2]
center = (w//2, h//2)
print(angle)
M = cv2.getRotationMatrix2D(center, angle, 1.0)
rotated = cv2.warpAffine(im, 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))
cv2.imshow('Input', im)
cv2.imshow('Rotated', rotated)
cv2.waitKey(0)
cv2.destroyAllWindows()
应用 5x5 形态膨胀会产生大斑点,可以非常精确地找到其方向。试试最大的。
我不明白为什么转换不起作用,输出图像是:
所以阈值操作工作正常,但一定有某种问题 我似乎没有注意到转变。提前致谢!
import cv2
import numpy as np
#read the image, do binary processing
im = cv2.imread('scanned.png')
grey = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
cv2.imshow('gray', grey)
#the pixels are reversed to white and black
# gray = cv2.bitwise_not(gray)
ret, thresh = cv2.threshold(grey, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)
cv2.imshow('thresh', thresh)
#calculate the minimum border that contains rotated text
coords = np.column_stack(np.where(thresh > 0))
print(coords)
#unction gives the rectangle border containing the whole text area, and the rotation angle of this border is the same as that of the text in the figure
angle = cv2.minAreaRect(coords)[-1]
print(angle)
#adjust the angle
if angle < -45:
angle = -(90+ angle)
else:
angle = -angle
#transformation
h, w = im.shape[:2]
center = (w//2, h//2)
print(angle)
M = cv2.getRotationMatrix2D(center, angle, 1.0)
rotated = cv2.warpAffine(im, 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))
cv2.imshow('Input', im)
cv2.imshow('Rotated', rotated)
cv2.waitKey(0)
cv2.destroyAllWindows()
应用 5x5 形态膨胀会产生大斑点,可以非常精确地找到其方向。试试最大的。