關(guān)于opencv讀取和寫入路徑有漢字的處理方式
opencv讀取和寫入路徑有漢字的處理
讀取圖片
?img_gt = cv2.imdecode(np.fromfile(path, dtype=np.uint8), -1) ?img_gt = cv2.cvtColor(img_gt, cv2.IMREAD_COLOR)
寫入圖片
write_path=f'{save_dir}/{imgname}.jpg' cv2.imencode('.jpg', output)[1].tofile(write_path) ?# 保存圖片
C++版本
#include<iostream>? #include <opencv2/core/core.hpp>? #include <opencv2/highgui/highgui.hpp> #include "opencv2/imgproc.hpp" #include "opencv2/imgcodecs.hpp" #include <opencv2/highgui/highgui_c.h> using namespace cv; int main() { ?? ?std::string image_path = samples::findFile("D:\\素材\\1.png"); ?? ?Mat img = imread(image_path, IMREAD_COLOR); ?? ?imshow("src", img);//原圖像 ?? ?waitKey(0); }
opencv的imread不支持中文路徑問題
其實(shí)嚴(yán)格來說,不是imread不支持中文路徑,而是不支持non-ascii。所以不論路徑如何轉(zhuǎn)換編碼格式,應(yīng)該都不能解決問題。
解決的思路就是先用其他支持中文的API,把圖片數(shù)據(jù)導(dǎo)入到內(nèi)存中,然后通過opencv從內(nèi)存讀入圖片的方法,讀入圖片。
實(shí)現(xiàn)很簡單
import cv2 import numpy as np def readimg(filename, mode): ?? ?raw_data = np.fromfile(filename, dtype=np.uint8) ?#先用numpy把圖片文件存入內(nèi)存:raw_data,把圖片數(shù)據(jù)看做是純字節(jié)數(shù)據(jù) ?? ?img = cv2.imdecode(raw_data, mode) ?#從內(nèi)存數(shù)據(jù)讀入圖片 ?? ?return img
這個(gè)函數(shù)就可以代替opencv的imread了,并且該函數(shù)支持中文路徑
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持本站。
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。