How do I read an image from a path with Unicode characters?

前端 未结 4 610
广开言路
广开言路 2020-12-03 05:13

I have the following code and it fails, because it cannot read the file from disk. The image is always None.

# -*- coding: utf-8 -*-
import cv2
         


        
4条回答
  •  情深已故
    2020-12-03 06:01

    Inspired by Thomas Weller's answer, you can also use np.fromfile() to read the image and convert it to ndarray and then use cv2.imdecode() to decode the array into a three-dimensional numpy ndarray (suppose this is a color image without alpha channel):

    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)
    

    np.fromfile() will convert the image on disk to numpy 1-dimensional ndarray representation. cv2.imdecode can decode this format and convert to the normal 3-dimensional image representation. cv2.IMREAD_UNCHANGED is a flag for decoding. Complete list of flags can be found here.

    PS. For how to write image to a path with unicode characters, see here.

提交回复
热议问题