将文本写入OpenCV图像

huangapple go评论85阅读模式
英文:

writing text to an image in opencv

问题

I'm trying to write text I've converted from an image to an ascii art into a different image, but for some reason I keep getting strange shapes and not the letters (in English) that were converted.

Here is the result of my function so far:

将文本写入OpenCV图像

I suspect it has something to do with the font.

Here is the relevant code:

def saveTxtAsPicute(file_path, width, height, currentframe):
    """
    converts txt file to picture then saves it
    :param file: txt file to convert
    :return: the filtered ascii image
    """

    # Open text file and read content
    with open(file_path, 'r') as file:
       text = file.read()

    # Define image size and font size
    font_size = 14

    # Create a new image
    img = np.zeros((int(height), int(width), 3), dtype=np.uint8)
    img.fill(255)

    # Set font and get text size
    font = cv2.FONT_HERSHEY_SIMPLEX
    text_width, text_height = cv2.getTextSize(text, font, font_size, 2)[0]

    # Calculate the number of columns and rows
    cols = int(width / font_size)
    rows = int(text_height / font_size)

    # Draw text on the image
    x = y = 0
    for i in range(len(text)):
        cv2.putText(img, text[i], (x, y+font_size), font, font_size/2, (0, 0, 0), 1, cv2.LINE_AA)
        x += font_size
        if x >= width:
            x = 0
            y += font_size

    # Save the image
    cv2.imwrite('./txtFilesPic/text_image' + str(currentframe) + '.jpg', img)
英文:

I'm trying to write text I've converted from an image to an ascii art into a different image, but for some reason I keep getting strange shapes and not the letters (in english) the were converted.

Here is the result of my function so far:

将文本写入OpenCV图像

I suspect it has something to do with the font.

Here is the relevant code:

def saveTxtAsPicute(file_path, width, height, currentframe):
    """
    converts txt file to picture then saves it
    :param file: txt file to convert
    :return: the filtered ascii image
    """

    # Open text file and read content
    with open(file_path, 'r') as file:
       text = file.read()

    # Define image size and font size
    font_size = 14

    # Create new image
    img = np.zeros((int(height), int(width), 3), dtype=np.uint8)
    img.fill(255)

    # Set font and get text size
    font = cv2.FONT_HERSHEY_SIMPLEX
    text_width, text_height = cv2.getTextSize(text, font, font_size, 2)[0]

    # Calculate number of columns and rows
    cols = int(width / font_size)
    rows = int(text_height / font_size)

    # Draw text on image
    x = y = 0
    for i in range(len(text)):
        cv2.putText(img, text[i], (x, y+font_size), font, font_size/2, (0, 0, 0), 1, cv2.LINE_AA)
        x += font_size
        if x >= width:
            x = 0
            y += font_size

    # Save image
    cv2.imwrite('./txtFilesPic/text_image' + str(currentframe) + '.jpg', img)

答案1

得分: 1

以下是翻译好的部分:

1- cv2.FONT_HERSHEY_SIMPLEX使用的默认字体不是等宽的。这意味着每个字符的宽度不相等,一些字符如'i'可能占据较少的空间,而其他字符如'k'可能占据更多的空间。因此,如果您在每次迭代时以相同的值增加起始x位置,它将看起来像这样:

要避免这种间距,您可以使用等宽字体,比如roberto mono等。

2- 字体大小不会精确地转化为像素值。例如,字体大小为12的字体不一定在图像中是12像素。因此,如果您只是增加在每次迭代中增加x和y的比例,您的图像应该看起来更清晰。

希望这些翻译能对您有所帮助。

英文:

you are in the right direction however there are few things you should keep in mind
1- The default font used by cv2.FONT_HERSHEY_SIMPLEX is not monospaced. Which means, every character does not take equal width, some characters like 'i' can take less space whereas others like 'k' can take more. Thus if you increase your starting x position by the same value at each iteration, it would look something like this
将文本写入OpenCV图像

To avoid this type of spacing, you can use monospace fonts like roberto mono etc
2- The font size does not translate exactly into pixel values. For example, a font size of 12 will not necessarily be 12 pixels in the image. Thus if u just increase the scale with which u are increasing the x and y in each iteration, your image should look a lot cleaner


def saveTxtAsPicute(file_path, width, height ):
    """
    converts txt file to picture then saves it
    :param file: txt file to convert
    :return: the filtered ascii image
    """

    # Open text file and read content
    with open(file_path, 'r') as file:
       text = file.read()

    # Define image size and font size
    font_size = 2

    # Create new image
    img = np.zeros((int(height), int(width), 3), dtype=np.uint8)
    img.fill(255)

    # Set font and get text size
    font = cv2.FONT_HERSHEY_SIMPLEX
    text_width, text_height = cv2.getTextSize(text, font, font_size, 2)[0]

    # Calculate number of columns and rows
    #cols = int(width / font_size)
    #rows = int(text_height / font_size)

    text =text.strip()
    print (text)
    # Draw text on image
    x = y = 0
    y = 80
    for i in range(len(text)):
        cv2.putText(img, text[i], (x,y+6*font_size), font, font_size, (0, 0, 0))
        x += font_size*19
        if x >= width:
            x = 0
            y += 25*font_size

    # Save image
    cv2.imwrite('./text_image' + '.jpg', img)

saveTxtAsPicute('./foo.txt',100,500)

This code with "hit it up" as the text in the file would give you the following output
将文本写入OpenCV图像

huangapple
  • 本文由 发表于 2023年4月10日 23:02:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/75978225.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定