Avinash
Avinash

Reputation: 133

Text within image in OpenCV

I was trying to get some text on an image using OpenCV. But the text is too long for one line and goes out of the image, instead of the next line. I could hardcode the spaces, but I was looking for a more dynamic solution. How do I work around this issue?

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

Upvotes: 0

Views: 1119

Answers (2)

Sanket Jagani
Sanket Jagani

Reputation: 36

in this code i simply split string into parts according image width.

     # 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)

Upvotes: 1

Lukashou-AGH
Lukashou-AGH

Reputation: 123

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

Try this, may require some adjustment, but the idea is to use textwrap.wrap(text, width=35).

Upvotes: 1

Related Questions