opencv-python imread does not support Chinese path solution

imread in the opencv library is used to read image files, but this does not support Chinese paths.
For the Chinese path, you need to use the imdecode method.

1. Read pictures with Chinese characters

Both imdecode and imread read pictures in the way of bgr. opencv performs image processing, also bgr.

I saw someone on the Internet saying that imdecode reads images in rgb, and when using opencv for image processing, you need to do some conversion (rgb to bgr);
but I tested it myself, and it is actually bgr.

# 读取带中文的图片,bgr
def cv_imread(file_path):
    cv_img = cv.imdecode(np.fromfile(file_path, dtype=np.uint8), -1)
    return cv_img

There is a problem with the following method I found on the Internet:
# 报错: 'utf-8' codec can't decode byte 0xb2 in position 24: invalid start byte
def cv_imread2(file_path=""):
    file_path_gbk = file_path.encode('gbk')  # unicode转gbk,字符串变为字节数组
    img_mat = cv.imread(file_path_gbk.decode())  # 字节数组直接转字符串,不解码
    return img_mat

2. Verify that imdecode is stored in bgr

As we all know, cv2.imread is stored in bgr, so here we use cv2.imread for comparison, and you can see the final gray value of BGR.

# cv.imdecode 和 cv.imread,读图都是bgr方式。以下可证明两者方式一样。
img = cv_imread("./彩色图像.tiff")
B, G, R = cv.split(img)
img2 = cv.imread("./color.tiff")
B2, G2, R2 = cv.split(img2)  # 拆分通道,opencv存储图片是bgr方式

3. Save pictures with Chinese characters

# 保存带中文的图片
def cv_imwrite(file_path):
    cv.imencode('.tiff', img)[1].tofile(out_path)  # 保存带中文的图片,opencv保存的tiff,默认是lzw压缩

4. Call

if __name__ == "__main__":
    img = cv_imread("./彩色图像.tiff")
    # cv.namedWindow('ReadImgCN', cv.WINDOW_AUTOSIZE)  # 图片太大,不采用自适应
    cv.namedWindow('ReadImgCN', cv.WINDOW_NORMAL)
    cv.resizeWindow('ReadImgCN', 1000, 1000)
    cv.imshow("ReadImgCN", img)
    cv.waitKey(0)
    cv.destroyAllWindows()

    out_path = './测试.tiff'
    cv_imwrite(out_path)

appendix

Help documents for official imread and imdecode

Guess you like

Origin blog.csdn.net/gdxb666/article/details/128636569