OpenCV中图像中的文本

2024-03-28 09:16:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着用OpenCV在图像上获取一些文本。但是文本对于一行来说太长,超出了图像,而不是下一行。我可以硬编码的空间,但我正在寻找一个更动态的解决方案。如何解决这个问题?你知道吗

def get_text(img, text):
    sh = img.shape
    txt = np.ones(shape=sh)

    fontface = cv2.FONT_HERSHEY_SIMPLEX
    fontscale = 1
    thickness = 2
    color = (0, 0, 0)
    orig = (10, 100)
    linetype = cv2.LINE_AA
    txt = cv2.putText(txt, text, orig, fontface, fontscale, color, thickness, linetype)
    txt = txt.astype("uint8")
    return txt

Tags: text图像文本txtimgshcv2opencv
2条回答

在这段代码中,我只是根据图像宽度将字符串分割成几个部分。你知道吗

     # Python program to explain cv2.putText() method  
    import cv2 
    import math
    import textwrap
    path = r'YOUR PATH OF IMAGE'
    image = cv2.imread(path) 
    window_name = 'Image'
    font = cv2.FONT_HERSHEY_SIMPLEX 
    zero= 5
    one =50
    org = (zero, one)  
    fontScale = 1 
    color = (255, 0, 0)  
    thickness = 2
    imageHeight = image.shape[0]
    imageWidth = image.shape[1]
    print(f"width:",imageWidth)
    sizeofnumpix=min(imageWidth,imageHeight)/(25/fontScale)
    stringputt = 'YOUR STRING'
    i=len(stringputt)
    print(i)    
    if i*sizeofnumpix > imageWidth*2:
        n=math.ceil(i*sizeofnumpix/(imageWidth*2))
        part_size = math.ceil(i/n)
        txt = textwrap.wrap(stringputt, part_size)
        for l in txt:
            image = cv2.putText(image, l, org, font,fontScale, color, thickness, cv2.LINE_AA)
        zero= 5
        one = one+math.ceil(sizeofnumpix)
        org = (zero, one) 

    else:
       image = cv2.putText(image, stringputt, org, font,fontScale, color, thickness, cv2.LINE_AA)

    # Displaying the image 
    cv2.imwrite('IMGWITHTXT.png',image)
import textwrap 
def get_text(img, text):
    sh = img.shape
    txt = np.ones(shape=sh)

    fontface = cv2.FONT_HERSHEY_SIMPLEX
    fontscale = 1
    thickness = 2
    color = (0, 0, 0)
    orig = (10, 100)
    linetype = cv2.LINE_AA
    wrapped_text = textwrap.wrap(text, width=35)
x, y = 10, 40
font_size = 1
font_thickness = 2

i = 0
for line in wrapped_text:
    textsize = cv2.getTextSize(line, font, font_size, font_thickness)[0]

    gap = textsize[1] + 10

    y = int((img.shape[0] + textsize[1]) / 2) + i * gap
    x = int((img.shape[1] - textsize[0]) / 2)

    cv2.putText(img, line, (x, y), font,
                font_size, 
                (0,0,0), 
                font_thickness, 
                lineType = cv2.LINE_AA)
    txt = txt.astype("uint8")
    return txt

尝试这个,可能需要一些调整,但是想法是使用textwrap.wrap(text, width=35)。你知道吗

相关问题 更多 >