Python OpenCV - 채널, 컬러

BANG·2020년 11월 28일
0

OpenCV

목록 보기
14/16

특정 채널만 가져와 배경 칠하기

import cv2
import numpy as np
 
# GRAYSCALE로 이미지 읽어오기, 채널이 없음
src = cv2.imread('./data/lena.jpg', cv2.IMREAD_GRAYSCALE)
#print(src, type(src))   # <class 'numpy.ndarray'>
 
# height, width, channel
shape = src.shape[0], src.shape[1], 3
print(shape, type(shape))   # (512, 512, 3), <class 'tuple'>
 
# 해당 이미지의 3개의 channel에 모두 0 입력하기
dst = np.zeros(shape, dtype=np.uint8)
#print(dst, type(dst))   # <class 'numpy.ndarray'>
 
# numpy 형식 채널 분리
dst[:, :, 0] = src      # B-채널만 가져오기
##dst[:, :, 1] = src    # G-채널 
##dst[:, :, 2] = src    # R-채널 
 
# 해당 좌표의 3개의 channel에 모두 255를 입력(white)
dst[100:400, 200:300, :] = [255, 255, 255]
#print(dst, type(dst))   # <class 'numpy.ndarray'>
 
cv2.imshow('src', src)
cv2.imshow('dst', dst)
 
cv2.waitKey()    
cv2.destroyAllWindows()

채널 분리하기

  • 채널을 B(Blue), G(Green), R(Red)로 분리
  • 분리된 채널들은 단일 채널이므로 흑백의 색상으로만 표현
import cv2
src = cv2.imread('./data/lena.jpg')
 
# 채널을 분리
dst = cv2.split(src) 
#print(type(dst))    # <class 'list'>
#print(type(dst[0])) # <class 'numpy.ndarray'>
 
cv2.imshow('blue',  dst[0])
cv2.imshow('green', dst[1])
cv2.imshow('red',   dst[2])
 
cv2.waitKey()    
cv2.destroyAllWindows()

채널 병합하기

import cv2
src = cv2.imread('./data/lena.jpg')
 
# 채널을 분리하여 채널에 순서의 맞게 각 변수에 대입
b, g, r = cv2.split(src)
print(b, type(b))   # <class 'numpy.ndarray'>
 
# 나눠진 채널을 병합
dst = cv2.merge([b, g, r]) # cv2.merge([r, g, b])
 
print(type(dst))    # <class 'numpy.ndarray'>
print(dst.shape)    # (512, 512, 3)
 
cv2.imshow('dst',  dst)
cv2.waitKey()    
cv2.destroyAllWindows()
profile
Record Everything!!

0개의 댓글