0(검정) 또는 255(흰색)로 변환되어 단순한 형태를 취하게 됨import cv2
image = cv2.imread("data/sunset.jpg") # 원본 용량: 11.9MB
# 그레이스케일 변환
image_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 이진화
_, image_binary = cv2.threshold(
image_gray,
127, # 임계값
255, # 최대값
cv2. THRESH_BINARY
)
cv2.imwrite("data/susnet_binary.jpg", image_binary) # 이진화 후 용량: 3MB

import cv2
import numpy as np
bg = np.full((500, 500), 0, dtype=np.uint8)
cv2.putText(bg,
"ABC",
(50,300),
cv2.FONT_HERSHEY_SIMPLEX,
7,
255,
20,
cv2.LINE_AA)
noise = np.random.randint(0, 2, (500, 500)).astype(np.uint8) * 255
img_bwor = cv2.bitwise_or(bg, noise)
img_bwand = cv2.bitwise_and(bg, noise)
cv2.imwrite("data/abc_bwor.jpg", img_bwor)
cv2.imwrite("data/abc_bwand.jpg", img_bwand)
abc_bwor.jpg
abc_bwand.jpg
kernel = np.ones((5, 5), np.uint8)
# erosion은 검은색이 우세 (흰색이 줄어듬)
erosion = cv2.erode(img_bwor, kernel, iterations=1)
# dilation은 흰색이 우세 (검은색이 줄어듬)
dilation = cv2.dilate(img_bwand, kernel, iterations=1)
opening = cv2.morphologyEx(img_bwor, cv2.MORPH_OPEN, kernel)
closing = cv2.morphologyEx(img_bwand, cv2.MORPH_OPEN, kernel)
cv2.imwrite("data/abc_erosion.jpg", erosion)
cv2.imwrite("data/abc_dilation.jpg", dilation)
cv2.imwrite("data/abc_opening.jpg", opening)
cv2.imwrite("data/abc_closing.jpg", closing)
abc_erosion.jpg
abc_dilation.jpg
abc_opening.jpg
abc_closing.jpg
*이 글은 제로베이스 데이터 취업 스쿨의 강의 자료 일부를 발췌하여 작성되었습니다.