# # Opencv imdecode solve the problem function to open the picture, the picture discoloration

Most people use imdecode function to open image files because of imread function opencv image file can not be opened in the Chinese path estimated online using imdecode function to open the picture there are a lot of grammar Here are some simple:

method one:

def cv_imread(file_path = ""):
    file_path_gbk = file_path.encode('gbk')        # unicode转gbk,字符串变为字节数组
    img_mat = cv2.imread(file_path_gbk.decode())  # 字节数组直接转字符串,不解码
    return img_mat

Method Two:

import os
def cv_imread(file_path):
    root_dir, file_name = os.path.split(file_path)
    pwd = os.getcwd()
    if root_dir:
        os.chdir(root_dir)
    cv_img = cv2.imread(file_name)
    os.chdir(pwd)
    return cv_img

Method three:

def cv_img_rgb(path):
    #用matplotlib的路径
    img=plt.imread(path)
    #因为opencv读取是按照BGR的顺序,所以这里转换一下即可
    img_rgb=cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
    return img_rgb

Method four:

def cv_imread(filePath):
    cv_img = cv2.imdecode(np.fromfile(filePath, dtype=np.uint8), -1)
    return cv_img

However, these methods have a problem. Picture file is read there are color cast problems, if it is gray picture will be completely different picture of the situation arise. Until I found this method the following:

import cv2
import numpy as np
cv2.imdecode(np.fromfile("D:\\haha哈哈.png",dtype=np.uint8),,cv2.IMREAD_COLOR)

Read image files using this method not only can read image files under the Chinese path and does not appear the phenomenon of distortion.
Reference:
[. 1] https://www.zhihu.com/question/67157462
[2] https://blog.csdn.net/u011311291/article/details/81457278

Published 59 original articles · won praise 2 · Views 4667

Guess you like

Origin blog.csdn.net/lch551218/article/details/104565240