1

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?

Lactose
  • 13
  • 6

1 Answers1

1

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)
isydmr
  • 649
  • 7
  • 16
  • Thank you! Converting to a PIL-image and then using the ".save()"-Method solved my Problem! – Lactose Jan 14 '19 at 22:57
  • Glad it helped! – isydmr Jan 15 '19 at 15:56
  • 3
    And for anyone using the same method to solve a problem like this, remember: cv2 uses BGR for encoding color, while PIL uses RGB. To solve this use: `cv2_im = cv2.cvtColor(img,cv2.COLOR_BGR2RGB) img_pil = Image.fromarray(cv2_im) img_pil.save(spath)` – Lactose Jan 15 '19 at 20:15