이진 영상 (Binary Image)
그레이 레벨 영상(Gray-Level Image)
컬러 영상(Color Image)
### Packages
import cv2
import numpy as np
from matplotlib import pyplot as plt
import os
### 출력 영상 크기
plt.rcParams["figure.figsize"] = (16,9)
### 한글 표시
plt.rcParams['font.family'] = "Gulim" # 'AppleGothic' in mac
### 영상 읽기
img_raw = cv2.imread(r'D:\image\lena.png')
if img_raw is None:
print("Could not read the image.")
### 자료 구조
type(img_raw), img_raw.dtype, img_raw.shape
(numpy.ndarray, dtype('uint8'), (512, 512, 3))
### Blue
img_raw[:,:,0]
array([[125, 125, 133, ..., 122, 110, 90],
[125, 125, 133, ..., 122, 110, 90],
[125, 125, 133, ..., 122, 110, 90],
...,
[ 60, 60, 58, ..., 84, 76, 79],
[ 57, 57, 62, ..., 79, 81, 81],
[ 57, 57, 62, ..., 79, 81, 81]], dtype=uint8)
### BGR → RGB 변환
img_rgb = cv2.cvtColor(img_raw, cv2.COLOR_BGR2RGB)
plt.imshow(img_rgb)
plt.show()
### 영상 분리
B, G, R = cv2.split(img_raw)
### RGB 영상으로 출력
titles = ["BGR", "Blue", "Green", "Red"]
images = [img_raw, B, G, R]
for i in range(len(images)):
plt.subplot(1,4,i+1)
img_rgb = cv2.cvtColor(images[i], cv2.COLOR_BGR2RGB)
plt.imshow(img_rgb)
plt.title(titles[i])
plt.axis('off')
plt.show()
### 영상 분리
B = np.zeros(img_raw.shape, dtype="uint8")
G = B.copy()
R = B.copy()
B[:,:,0] = img_raw[:,:,0]
G[:,:,1] = img_raw[:,:,1]
R[:,:,2] = img_raw[:,:,2]
### RGB 영상으로 출력
titles = ["BGR", "Blue", "Green", "Red"]
images = [img_raw, B, G, R]
for i in range(len(images)):
plt.subplot(1,4,i+1)
img_rgb = cv2.cvtColor(images[i], cv2.COLOR_BGR2RGB)
plt.imshow(img_rgb)
plt.title(titles[i])
plt.axis('off')
plt.show()
### BGR → YCrCb 변환
img_ycc = cv2.cvtColor(img_raw, cv2.COLOR_BGR2YCrCb)
### 영상 분리
Y, Cr, Cb = cv2.split(img_ycc)
### 영상 출력
titles = ["BGR", "Y", "Cr", "Cb"]
images = [img_raw, Y, Cr, Cb]
for i in range(len(images)):
plt.subplot(1,4,i+1)
img_rgb = cv2.cvtColor(images[i], cv2.COLOR_BGR2RGB)
plt.imshow(img_rgb)
plt.title(titles[i])
plt.axis('off')
plt.show()
### Grayscale
img_gray = cv2.cvtColor(img_raw, cv2.COLOR_BGR2GRAY)
img_gray.shape
(512, 512)
### 영상 출력 - grayscale
plt.imshow(img_gray, 'gray')
plt.show()
### 조각 영상(1) - grayscale
img_gray_sub = img_gray[240:290, 240:290]
plt.imshow(img_gray_sub, "gray")
plt.show()
### 조각 영상(2) - grayscale
img_gray_sub = img_gray[240:290, 310:360]
plt.imshow(img_gray_sub, "gray")
plt.show()
### 조각 영상(3) - color
img_raw_sub = img_raw[240:290, 310:360, :]
plt.imshow(cv2.cvtColor(img_raw_sub, cv2.COLOR_BGR2RGB))
plt.show()