不是完美的解决方案,但一种方法可以如下。
import numpy as np
import random
import cv2
font = cv2.FONT_HERSHEY_SIMPLEX
# Create a black image
img = np.zeros((500,500,3), np.uint8)
char = "ABCDEFG"
for i in range (0,7,1):
text_location = (150 + i*30, 250) # Location of the letter
angle = random.randint(0,90) # angle of rotation
# Rotate the image to put the letter at an angle
M = cv2.getRotationMatrix2D(text_location, angle, 1)
img = cv2.warpAffine(img, M, (img.shape[1], img.shape[0]))
# Put the letter.
cv2.putText(img, char[i], text_location, font, 1, (255, 255, 255), 2)
# Undo the initial rotation of image for the next letter.
M = cv2.getRotationMatrix2D(text_location, -1*angle, 1)
img = cv2.warpAffine(img, M, (img.shape[1], img.shape[0]))
# Thresholding to keep the image sharp
(thresh, img) = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
#Display the image
cv2.imshow("img",img)
cv2.waitKey(0)
输出
注意
-
[0-90] 的范围在我看来是最好的结果,但您可以随意使用它(更大的范围会导致字母重叠,所以)
- 还可以调整阈值,以便在阈值步骤中获得更好的调整和所需的结果。