본문 바로가기
영상처리 프로그래밍/OpenCV-Python

OpenCV Python 영상 파일 I/O 처리

by Glory_Choi 2022. 10. 6.
반응형

이미지 파일 처리

 

함수 설명

cv2.imread(filename[, flags]) >> retval
  • 지정한 영상 파일로 부터 영상을 적재한 후, 행렬로 반환한다.
인수 설명
  • filename                     적재할 영상 파일 이름(디렉터리 구조(폴더 위치) 포함)
  • flags                           적재한 영상을 행렬로 반환될 때 컬러 타입을 결정하는 상수
cv2.imwrite(filename, img[, params]) >> retval
  • 설명 : img 행렬을 지정한 영상파일로 저장한다.
인수 설명
  • filename  저장할 영상파일 이름(디렉터리 구조(폴더 위치) 포함), 확장자명에 따라 영상파일 형식 결정
  • img 저장하고자 하는 행렬(영상)
  • params 압축 방식에 사용되는 인수 쌍(paramld, paramValue)

 

영상파일 읽기

소스 코드

import cv2

def print_matInfo(name, image):
    if image.dtype == 'uint8':  mat_type = 'CV_8U'
    elif image.dtype == 'int8': mat_type = 'cv_8S'
    elif image.dtype == 'uint16': mat_type = 'cv_16U'
    elif image.dtype == 'int16': mat_type = 'cv_16S'
    elif image.dtype == 'float32': mat_type = 'cv_32F'
    elif image.dtype == 'float64': mat_type = 'cv_64F'
    nchannel = 3 if image.ndim == 3 else 1
   
    print("%12s: depth(%s), channels(%s) -> mat_type(%sC%d)"
          % (name, image.dtype, nchannel, mat_type, nchannel))
   
title1, title2 = "gray2gray", "gray2color"
gray2gray = cv2.imread("cat.jpg", cv2.IMREAD_GRAYSCALE)
gray2color = cv2.imread("cat.jpg", cv2.IMREAD_COLOR)

if gray2gray is None or gray2color is None :
    raise Exception("영상파일 읽기 에러")

print("행렬 좌표 (100, 100) 화소값")
print("%s %s"% (title1, gray2gray[100, 100]))
print("%s %s\n" % (title2, gray2color[100, 100]))

print_matInfo(title1, gray2gray)
print_matInfo(title2, gray2color)

cv2.imshow(title1, gray2gray)
cv2.imshow(title2, gray2color)
cv2.waitKey(0)
cv2.destroyAllWindows()

실행 결과

행렬 좌표 (100, 100) 화소값
gray2gray 110
gray2color [ 53 118 116]

gray2gray: depth(uint8), channels(1) -> mat_type(CV_8UC1)
gray2color: depth(uint8), channels(3) -> mat_type(CV_8UC3)

영상파일 저장

소스 코드

import numpy as np
import cv2

image = cv2.imread("cat.jpg", cv2.IMREAD_COLOR)
if image is None: raise Exception("영상처리 읽기 에러")

params_jpg = (cv2.IMWRITE_JPEG_QUALITY,10)
params_png = [cv2.IMWRITE_PNG_COMPRESSION,9]

cv2.imwrite("write_test1.jpg", image)
cv2.imwrite("write_test2.jpg", image,params_jpg)
cv2.imwrite("write_test3.png", image,params_png)
cv2.imwrite("write_test4.bmp", image)
print("저장 완료")
 

실행 결과

 

 

비디오파일 처리

 

VideoCapture 클래스 

cv2.VideoCapture() >> <VideoCapture object>
cv2.VideoCapture(filename) >> <VideoCapture object>
cv2.VideoCapture(device) >> <VideoCapture object>
  • 설명 : 생성자, 3가지 VideoCapture 객체 선언 방법을 지원한다.
인수 설명
  • filename 개방할 동영상 파일의 이름 혹은 영상 시퀀스
  • devide 개방할 동영상 캡처 장치의 ID(카메라 한대만 연결되면 0을 지정)
cv2.VideoCapture.open(filename) >> retval
cv2.VideoCapture.open(device) >> retval
  • 설명 : 동영상 캡처를 위한 동영상 파일 혹은 캡처 장치를 개방한다.
cv2.VideoCapture.isOpened() >> retval
  • 설명 : 캡처 장치의 연결 여부를 반환한다.
cv2.VideoCapture.release() >> None
  • 설명 : 동영상 파일이나 캡처 장치를 해제한다. (클래스 소멸자에 의해서 자동으로 호출되므로 명시적으로 수행하지 않아도 됨)
cv2.VideoCapture.get(propld) >> retval
  • 설명 : 비디오 캡처의 속성 식별자로 지정된 속성의 값을 반환한다. 캡처 장치가 제공하지 않는 속성은 0을 반환한다.
인수 설명
  • propld 속성 식별자 
cv2.VideoCapture.set(propld, value) >> retval
  • 설명 : 지정된 속성 식별자로 비디오 캡처의 속성을 설정한다.
인수 설명
  • propld 속성 식별자
  • value 속성 값
cv2.VideoCapture.release() >> None
  • 캡처 장치나 동영상 파일에서 다음 프레임을 잡는다.
retrueve([, image[, flag]]) >> retval, image
  • 설명 : grab()으로 잡은 프레임을 디코드해서 image 행렬로 전달한다.
인수 설명
  • image 잡은 프레임이 저장되는 행렬
  • flag 프레임 인덱스
cv2.VideoCapture.read([image]) >> retval, image
  • 설명 : 캡처 장치나 동영상 파일에서 다음 프레임을 잡아 디코드해서 image 행렬로 전달한다.

 

 

VideoWriter 클래스 

cv2.VideoWriter([filename, fourcc, fps, frameSize[, isColor]]) >> <VideoWriter object>
cv2.VideoWriter.open(filename, fourcc, fps, frameSize[, isColor]) >> retval

인수 설명
  • filename 출력 동영상 파일의 이름
  • fourcc 프레임 압축에 사용되는 코덱의 4-문자
  • fps 생성된 동영상 프레임들의 프레임률(초당 프레임수)
  • frameSize 동영상 프레임의 크기(가로 x 세로)
  • isColor True면 컬러 프레임으로 인코딩, False면 명암도 프레임으로 인코딩
cv2.VideoWriter.isOpened() >>retval
  • 설명 : 캡처 장치나 동영상 파일이 열려있는지 확인한다.
cv2.VideoWriter.write(image) >> None
  • 설명 : image 프레임을 파일로 저장한다.
cv2.VideoWriter.isOpen()
  • 설명 : 영상을 동영상 파일의 프레임으로 저장하기 위해 동영상 파일을 개방한다. 인수는 생성자 인수와 동일하다.
cv2.VideoWriter.isOpened()
  • 설명 : 동영상 파일 저장을 위해 VideoWriter 객체의 개방 여부를 확인한다.

소스 코드

import cv2

capture = cv2.VideoCapture("catvideo.mp4")
if capture.isOpened() == False:
    raise Exception("카메라 연결 안됨")

while True:
    ret, frame = capture.read()
    if not ret: break
    if cv2.waitKey(30) >= 0: break
    cv2.imshow('frame', frame)
   
capture.release()

실행 결과(동영상 캡처본)

 

웹캠을 사용하여 코드를 작성할 경우에는 

import cv2

capture = cv2.VideoCapture(장치 번호)
if capture.isOpened() == False:
    raise Exception("카메라 연결 안됨")

while True:
    ret, frame = capture.read()
    if not ret: break
    if cv2.waitKey(30) >= 0: break
    cv2.imshow('frame', frame)
   
capture.release()

장치 번호를 VideoCapture()에 입력해야 한다. 

반응형

'영상처리 프로그래밍 > OpenCV-Python' 카테고리의 다른 글

관심 영역(ROI)  (0) 2022.11.16
논리(비트) 연산  (0) 2022.11.16
OpenCV 채널 처리 함수  (0) 2022.11.03