개요
python으로 구현하는 opencv 라이브러리를 이용할 때 파일명을 포함한 경로에 한글이 포함된 경우 문제가 발생하는데 이것을 해결하는 방법을 설명한다.

opencv 파일 읽기 및 쓰기
다음과 같이 이미지 파일을 읽고 쓸 수 있다.
import cv2
# 이미지 파일 읽기
file_path = r"D:\DATA\image1.jpg"
img = cv2.imread(file_path)
new_file_path = r"D:\DATA\image2.jpg"
# 이미지 파일 쓰기
cv2.imwrite(new_file_path, img)
하지만 이 때 파일 경로에 한글이 들어간 상태에서 파일을 읽거나 쓸려고 하면 다음과 같은 경고가 발생하며 None을 리턴한다.
[ WARN:[email protected]] global loadsave.cpp:244 cv::findDecoder imread_('D:\TEMP\미니\25642133_004.jpg'): can't open/read file: check file path/integrity
따라서 opencv를 쓸때 가급적 한글 파일명이나 경로를 이용하지 않는것이 좋으며 어쩔 수 없이 사용을 해야하는 경우에는 다음과 같이 파일 읽기, 쓰기 코드를 직접 구현한 cv2_util.py를 사용하면 된다.
cv2_util.py
import cv2
# 한글 경로 이미지 파일 읽기
def imread( file_path ) :
stream = open( file_path.encode("utf-8") , "rb")
bytes = bytearray(stream.read())
np_array = np.asarray(bytes, dtype=np.uint8)
return cv2.imdecode(np_array , cv2.IMREAD_UNCHANGED)
# 한글 경로 이미지 파일 쓰기
def imwrite(file_path, img, params=None):
try:
ext = os.path.splitext(file_path)[1]
result, n = cv2.imencode(ext, img, params)
if result:
with open(file_path, mode='w+b') as f:
n.tofile(f)
return True
else:
return False
except Exception as e:
print(e)
return False
다음과 같은 코드로 위의 유틸 모듈을 이용하면 된다.
import cv2_util
# 이미지 파일 읽기
file_path = r"D:\데이터\image1.jpg"
img = cv2_util.imread(file_path)
new_file_path = r"D:\데이터\image2.jpg"
# 이미지 파일 쓰기
cv2_util.imwrite(new_file_path, img)