Encodings do not work in a file with OpenCV in Python 3


I followed the face detection tutorial using OpenCV and wrote in Python 3. In this file, print is not used. I already know that Python 3 is international, is UTF-8 compatible and does not need encodings. But even so, no accent appeared on an image. Note that the file is saved in UTF-8.

I put it like this:

# -*- coding: utf-8 -*-
# -*- coding: latin-1 -*-
# -*- coding: iso-8859-15 -*-
import os
import sys

# import the necessary packages
import argparse
import cv2

I put three encodings to work on three different operating systems.

I changed from English to Portuguese, writing a sentence "It's a cat":

# loop over the cat faces and draw a rectangle surrounding each
for (i, (x, y, w, h)) in enumerate(rects):
    cv2.rectangle(image, (x, y), (x + w, y + h), (140, 175, 84), 2)
    cv2.putText(image, "É um gato  # {}".format(i + 1), (x, y - 10),
             cv2.FONT_HERSHEY_SIMPLEX, 0.55, (0, 0, 255), 2)  #5faf54

I ran on the Visual Studio Code integrated terminal in Ubuntu 16.04. It is no use suggesting that you run on the native terminal because the same thing happened.

I've also tried:


And it did not work.

A "# 1 cat" appeared in an image while executing and compiling:

asked by anonymous 18.03.2018 / 15:51

1 answer


As far as I know, there is no implementation in the PutText function to support unicode and special characters, so the problem is not with python.

A widely used feature, however, for this and other special character prints is the draw.text function of Pillow (PIL) .

Using a default unicode font .

PS: The encode function of OpenCV (now imencode) refers only to the encoding of the image itself. Documentation: Here

18.03.2018 / 16:57