def imread_ex(filename, flags=cv2.IMREAD_COLOR):
return cv2.imdecode(np.fromfile(filename, np.uint8), flags)
def imwrite_ex(filename, img, params=None):
r, eimg = cv2.imencode(os.path.splitext(filename)[1], img, params)
if r:
with open(filename, mode="wb") as f:
eimg.tofile(f)
return r
Python 의 cv2.imread 함수는 unicode 경로를 다루지 못한다고 한다.
따라서, 해당 경로의 파일(이미지파일)을 바이트 덩어리로 읽어온다음, 이미지 포맷에 맞게 decode 하는 방식으로 해결 할 수 있다.
다만, WebP 포맷의 경우 이름경로에 한글이 있으면 조건문에서 걸려 imread가 아닌 imdecode를 사용하게 되는데 이때 예외가 발생한다.
python에서 CV_Assert로 던져지는 예외가 잡히지도 않고, 발생하는 이유도 없는데 발생한다.
한시적으로는 아래와 같이 처리한다.
import cv2
import numpy as np
import re
import tempfile
import shutil
def imreadEX(image_path):
if re.compile('[^ㄱ-ㅣ가-힣]+').sub('', image_path):
stream = open(image_path, "rb")
bytes = bytearray(stream.read())
numpyarray = np.asarray(bytes, dtype=np.uint8)
img = cv2.imdecode(numpyarray, cv2.IMREAD_UNCHANGED)
if not img is None:
return img
else:
file_tmp=tempfile.NamedTemporaryFile().name
shutil.copy(image_path,file_tmp)
image_path=file_tmp
img = cv2.imread(image_path, cv2.IMREAD_UNCHANGED)
return img
def imwriteEX(image_path, img, params=None):
ext = os.path.splitext(image_path)[1]
result, n = cv2.imencode(ext, img, params)
if result:
with open(image_path, mode='w+b') as f:
n.tofile(f)
return True
else:
return False
또한 C++에서 python으로 문자열을 passing 할때 한글이 있을땐 아래와 같은 방법으로 처리한다.
img_path = shm.read(256).decode('cp949');
img_path = img_path.split('\0', 1)[0]