【问题标题】:how to write each Letter in random rotation on the image如何在图像上随机旋转写每个字母
【发布时间】:2021-11-13 08:09:43
【问题描述】:

我的代码在图像中写了一些字母,但我想要的是将每个字母随机旋转写为附加图像

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

【问题讨论】:

    标签: python python-imaging-library cv2


    【解决方案1】:

    不是完美的解决方案,但一种方法可以如下。

    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] 的范围在我看来是最好的结果,但您可以随意使用它(更大的范围会导致字母重叠,所以)
    • 还可以调整阈值,以便在阈值步骤中获得更好的调整和所需的结果。

    【讨论】:

    • 非常感谢,,,但是为什么如果我写更多的字母(更多的范围)它会变成模糊字母?
    • @iyad 我认为这是由 warpAffine() 引起的。我正在研究它提供的各种插值选项,如果我能够改进结果,我会告诉你。
    • @iyad 因此,每次使用 warpAffine() 以任意角度(不是 90 的倍数)旋转图像时,它通常会丢失细节,因为现在它必须映射图像的像素与屏幕的像素网格并不完全一致。当我们在同一张图像上一遍又一遍地旋转时,最早添加的字母会丢失最多的细节。幸运的是,由于我们的图像是二进制的(黑白),因此在每个旋转周期后通过阈值处理很容易获取细节。(同样不是完美的解决方案,但它有效)。我已经更新了答案。
    • 谢谢大家......这很有帮助
    • @iyad 很高兴我能帮上忙。如果您认为它回答了您的问题,请接受它作为答案并给它一个绿色勾号。
    猜你喜欢
    • 1970-01-01
    • 2015-07-03
    • 1970-01-01
    • 2012-11-10
    • 2022-12-30
    • 2023-03-30
    • 2015-10-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多