[cv2.imread] and [cv2.imdecode] usage

For images containing Chinese in the path, if you read them directly with cv2.imread, an error will be reported. Last time I saw that some big guys can use cv2.imdecode to read normally. I am a little curious, so today I will record the usage and difference between the two.

Table of contents

 1. Comparison of two ways to read images

 2. Comparison of two ways to save images

 


 1. Comparison of two ways to read images

  • cv2.imread reads images normally
import cv2
path = '/data/北京/beijing.png'
img = cv2.imread(path)

Running the above code will report an error!

  • cv2.imdecode reads images from memory
import cv2
path = '/data/北京/beijing.png'
arr = np.fromfile(path, dtype=np.uint8)
img = cv2.imdecode(arr, flags=cv2.IMREAD_COLOR)

Run the above code, success!

And the order of image bands obtained by imdecode is RGB, not BGR, which is the difference from opencv.

Function description:

np.decode   reads an image from a buffer in memory

np.fromfile  constructs the data in the text or binary file into an array


 2. Comparison of two ways to save images

  • cv2.imwrite reads images normally
import cv2
out_path = '/data/北京/beijing.png'
cv2.imwrite(out_path,img)

Running the above code will report an error!

  • cv2.imdecode reads images from memory
import cv2
out_path = '/data/北京/beijing.png'
arr = cv2.imencode('png',img)
out[1].tofile(out_path)

Run the above code, success!

 Function description:

cv2.encode  encodes the image into a memory buffer

np.tofile  writes the data in the array to the file in binary format

It's not easy to organize, welcome to one-click three links! ! !

Guess you like

Origin blog.csdn.net/qq_38308388/article/details/129199454