파이썬에서 사진 파일을 흑백으로 변경하는 방법을 알아보겠습니다.
흑백 사진으로 변경하기 위해 OpenCV의 함수 cv2.cvtColor()를 사용해서 변환해보겠습니다.
흑백으로 변경하고 싶은 사진 파일을 준비합니다.
변경전 사진

사진 정보 취득 소스
import cv2
import numpy as np
im = cv2.imread('C:/Users/Administrator/Desktop/python/origin/python.png')
print(im.shape)
# (500, 900, 3)
사진 파일을 불러와 간단히 정보를 출력해봤습니다.
본격적으로 사진을 흑백으로 변환해 저장을 해보겠습니다.
import cv2
import numpy as np
im = cv2.imread('C:/Users/Administrator/Desktop/python/origin/python.png')
im_gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
cv2.imwrite('C:/Users/Administrator/Desktop/python/origin/python_gray.png', im_gray)
사진을 흑백으로 변경해 다른 이름 저장했습니다.
변경후 사진

cv2.cvtColor() 함수에 cv2.COLOR_BGR2GRAY를 지정해 사진을 흑백으로 변경했습니다.
NumPy 배열인 ndarray로 값을 직접 입력해 흑백 사진으로도 변경할 수도 있지만, 넘파이를 사용하지 않는 경우에는 OpenCV를 사용해서도 흑백으로 변경 가능합니다.
댓글