如何在图像上随机旋转写每个字母
how to write each Letter in random rotation on the image
我的代码在图像中写了一些字母,但我想要的是随机旋转地写每个字母作为附加图像
import numpy as np
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):
cv2.putText(img, char[i], (150 + i*30, 250), font, 1, (255, 255, 255), 2)
#Display the image
cv2.imshow("img",img)
cv2.waitKey(0)
see the image to see what the result that I want
这不是完美的解决方案,但可以按照以下方式实现。
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]
给出了最好的结果,但你可以尝试一下(更大的范围导致字母重叠,所以)
- 还可以尝试调整阈值,以便在阈值步骤中获得更好的调整和期望的结果。
我的代码在图像中写了一些字母,但我想要的是随机旋转地写每个字母作为附加图像
import numpy as np
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):
cv2.putText(img, char[i], (150 + i*30, 250), font, 1, (255, 255, 255), 2)
#Display the image
cv2.imshow("img",img)
cv2.waitKey(0)
see the image to see what the result that I want
这不是完美的解决方案,但可以按照以下方式实现。
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]
给出了最好的结果,但你可以尝试一下(更大的范围导致字母重叠,所以) - 还可以尝试调整阈值,以便在阈值步骤中获得更好的调整和期望的结果。