pythonencodingopencvsave-image

cv2 imwrite and german letters ("ä, ü, ö")


I wrote a script to manipulate some pictures with cv2 in python.
Now I need to save these files, but some of the filenames contain german letters ("ä, ü, ö").
Unfortunately it seems the cv2function imwrite() can't handle this and writes the filenames as Bögen instead of Bögen.
I tried to convert the pathname to UTF-8 and other encodings via

path.encode("utf-8")

but this just leads to a

"TypeError: bad argument type for built-in operation"

Has anyone any experience with problems like that?


Solution

  • Unfortunately, OpenCV imwrite method only supports ASCII characters.

    To display UTF-8 characters, we need to use PIL Library.

    See the example below, implementing a new function print_utf8 is a simple solution for this task:

    import numpy as np
    import cv2
    from PIL import Image, ImageDraw, ImageFont
    
    def print_utf8(image, text, color):  
        fontName = 'FreeSerif.ttf'
        font = ImageFont.truetype(fontName, 18)  
        img_pil = Image.fromarray(image)  
        draw = ImageDraw.Draw(img_pil)  
        draw.text((0, image.shape[0] - 30), text, font=font,
               fill=(color[0], color[1], color[2], 0)) 
        image = np.array(img_pil) 
        return image
    
    img = cv2.imread("myImage.png")
    
    color = (255, 0, 0) #red text
    img_with_text = print_utf8(img, "ä, ü, ö",color)
    cv2.imshow('IMAGE', img_with_text)
    cv2.waitKey(0)