1장 - OpenCV¶


▶ OpenCV¶

  • 영상 처리를 위한 Python library
  • OpenCV는 C ++, Python, Java, R 등과 같은 다양한 프로그래밍 언어를 지원
  • Windows, Linux, OS X, Android 및 iOS를 포함한 다양한 플랫폼에서 사용
  • OpenCV-Python Tutorials
    • https://docs.opencv.org/master/d6/d00/tutorial_py_root.html
  • 설치
    • !pip install opencv-python
In [1]:
### OpenCV 설치
#!pip install opencv-python
In [2]:
### easygui 설치
#pip install easygui
In [3]:
### Packages
import cv2
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
#from easygui import fileopenbox, filesavebox
In [4]:
### 출력 영상 크기
plt.rcParams["figure.figsize"] = (16,9)  # 그림(figure)의 크기. (가로,세로) 인치 단위

▶ 영상 읽기¶

  • cv2.imread(fileName, flag)
    • fileName: 파일 경로 및 이름. 한글 지원 안됨
    • flag
      • cv2.IMREAD_COLOR (or 1): color
      • cv2.IMREAD_GRAYSCALE (or 0): grayscale
      • cv2.IMREAD_UNCHANGED (or -1): color + alpha channel
In [5]:
### 파일 선택
img_file = r'D:\image\sample-color.png'
#img_file = fileopenbox()
img_file
Out[5]:
'D:\\image\\sample-color.png'
In [6]:
### 영상 읽기
img_raw = cv2.imread(img_file)
In [7]:
### 영상 확인
if img_raw is None:
    print("Could not read the image.")
else:
    print(img_raw.shape)
(512, 768, 3)

▶ 영상 출력¶

  • OpenCV window
    • cv2.imshow( winname, mat)
      • winname: Name of the window
      • mat: Image to be shown
In [8]:
### OpenCV window
cv2.imshow("Display window", img_raw)
cv2.waitKey(0)
cv2.destroyAllWindows()
  • matplotlib.pyplot
    • plt.imshow(X, cmap=None)
      • X: array-like or PIL image
      • cmap: str or Colormap
In [9]:
### 영상 출력 - color
img_rgb = cv2.cvtColor(img_raw, cv2.COLOR_BGR2RGB)
plt.imshow(img_rgb)
plt.show()

▶ Grayscale 영상¶

In [10]:
### Color 영상을 Grayscale 영상으로 변환
img_gray = cv2.cvtColor(img_raw, cv2.COLOR_BGR2GRAY)
img_gray.shape
Out[10]:
(512, 768)
In [11]:
### 영상 출력 - gray
plt.imshow(img_gray, 'gray')
plt.show()

▶ 영상 저장¶

  • Write an image to a file
    • cv2.imwrite(filename, img)
      • filename: Name of the file
      • img: (Mat or vector of Mat) Image or Images to be saved
In [12]:
### 저장할 파일명 및 확장자
out_file = r'D:\image\sample-gray.png'
cv2.imwrite(out_file, img_gray)
Out[12]:
True