By default, OpenCV only accepts ASCII characters for image paths when reading and writing images. There are ways to work around this problem.

Read images with unicode paths

First, we can read the image with the help of Numpy fromfile() method, and then use cv2.imdecode() to read the image.

import numpy as np

# img is in BGR format if the underlying image is a color image
img = cv2.imdecode(np.fromfile('测试目录/test.jpg', dtype=np.uint8), cv2.IMREAD_UNCHANGED)

In the above script, the image is read with numpy and converted to a one-dimensional numpy ndarray of type np.uint8. Then we use imdecode() to decode the ndarray to OpenCV image format. cv2.IMREAD_UNCHANGED is a flag for imdecode. The complete list of flags available and their description can be found here.

Write images with unicode paths

To write images with unicode paths, we can first encode the image in OpenCV format to one dimension numpy ndarray format. Then we convert this numpy ndarray to image on disk with the tofile() method.

h, w = img.shape[:2]

im_resize = cv2.resize(img, (w//2, h//2))

# encode the im_resize into the im_buf_arr, which is a one-dimensional ndarray
is_success, im_buf_arr = cv2.imencode(".jpg", im_resize)