OpenCV (1)

Myeongsu Moon·2024년 11월 30일

제로베이스

목록 보기
28/95
post-thumbnail

OpenCV 소개

  • Open Computer Vision Library
  • 실시간 이미지 처리부터 머신러닝 까지
  • 얼굴인식, 객체탐지, 영상추적, 특징 추출 등.. 작업 수행 가능
  • 이미지, 영상에 대한 다양한 처리 가능

Chapter1 OpenCV 기초

이미지 읽기

  • jpg, png 등의 확장자 파일 준비
  • OpenCV 사용 준비: cv2 그대로 사용해도 되지만 편의상 cv로 바꿔서 사용하는 경우 많음
# import 하기

import cv2 as cv
print(cv.__version__)
  • 현재 작업 디렉토리 구조 확인하기
# 현재 경로 확인

import os
cwd = os.getcwd()
print(cwd)
# 현재 경로의 파일 확인

filelist = os.listdir(cwd)
print(filelist)
  • 이미지 읽어서 새 창에 띄우기
img_path = cwd + "/파일명.png"
img = cv.imread(img_path)
cv.imshow('window_MyImage', img)  # (이미지 창 이름, 이미지)

cv.waitKey(0) # 무한 대기, 이미지가 화면에 고정되어, 사용자가 키를 누를 때까지 넘어가지 않음
cv.destroyAllWindows()
  • 종료할때는 아무키나 누르면 됨
  • 종료시간 정해주기
cv.waitKey(5000) # 5초를 기다린 후 자동 종료
  • 상대경로 가지고 진행
img_path = "./파일명.png"

이미지 쓰기

  • 이미지 저장하기: 파일명 및 확장자 변경 가능
cv.imwrite('./저장할 파일명.png', img)
cv.imwrite('./저장할 파일명.jpg', img)

동영상 불러오기

  • 동영상은 움직이는 영상, 영상은 사진도 포함된 의미
  • 동영상은 여러 이미지의 연속 재생
  • 동영상 정보 읽어오기
import cv2 as cv

# 동영상 파일 경로
video_path = "./영상이름.mp4"

# 동영상 파일 불러오기
cap = cv.VideoCapture(video_path)

# 동영상 기본 정보 가져오기
frame_count = int(cap.get(cv.CAP_PROP_FRAME_COUNT))
fps = cap.get(cv.CAP_PROP_FPS)
width = int(cap.get(cv.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv.CAP_PROP_FRAME_HEIGHT))

print("동영상 정보 :" + str(width) + "x" + str(height) + ", " + str(frame_count) + " 프레임, " + str(fps) + "FPS")
  • 동영상을 프레임 단위로 토막 내서 저장하기
import cv2 as cv
import os

save_folder = "./frames"
os.makedirs(save_folder, exist_ok=True)

video_path = "./oneshot.mp4"

cap = cv.VideoCapture(video_path)

# 전체 프레임 수를 구하고 필요한 zero padding 계산
total_frames = int(cap.get(cv.CAP_PROP_FRAME_COUNT))
padding_length = len(str(total_frames))

frame_idx = 0
while True:
    ret, frame = cap.read()
    if not ret:
        break

    # Zero padding을 포함한 파일명 생성
    padded_frame_idx = str(frame_idx).zfill(padding_length) # -> frame_000.jpg 형식으로
    save_path = f"{save_folder}/frame_{padded_frame_idx}.jpg"
    cv.imwrite(save_path, frame)

    frame_idx += 1

동영상 만들기

  • 동영상 파일 생성
# ----- 비디오 파일 파라미터 설정 ----- #
import cv2 as cv
import os

# 이미지 프레임이 저장된 폴더
frame_folder = './frames'

# 동영상을 저장할 파일 경로
output_video_path = 'output_video.avi'

# 동영상의 해상도와 FPS 설정
frame_width = 1920
frame_height = 1080
fps = 30

# VideoWriter 객체 생성
fourcc = cv.VideoWriter_fourcc(*'XVID')
out = cv.VideoWriter(output_video_path, fourcc, fps, (frame_width, frame_height))

# ----- 이미지를 모아서 동영상 파일로 저장하는 부분 -----# 

# 프레임 파일 목록을 가져옵니다
frame_files = [f for f in os.listdir(frame_folder) if f.endswith('.jpg')]
frame_files.sort()  # 파일명 순서대로 정렬

# 각 프레임 파일에서 동영상 프레임 추가
for file in frame_files:
    frame_path = os.path.join(frame_folder, file)
    frame = cv.imread(frame_path)

    if frame is not None:
        # 프레임 크기 조정
        frame = cv.resize(frame, (frame_width, frame_height))
        out.write(frame)

# 동영상 파일 저장 완료
out.release()

print("동영상 저장 완료")
  • 부메랑 비디오 만들기
import cv2 as cv
import os

frame_folder = './frames_edit'
output_video_path = 'boomerang_video.avi'

frame_width = 1920
frame_height = 1080
fps = 30

fourcc = cv.VideoWriter_fourcc(*'XVID')
out = cv.VideoWriter(output_video_path, fourcc, fps, (frame_width, frame_height))

frame_files = [f for f in os.listdir(frame_folder) if f.endswith('.jpg')]
frame_files.sort()

# 2초 분량의 프레임만 사용
frames = []
for file in frame_files[:60]:
    frame_path = os.path.join(frame_folder, file)
    frame = cv.imread(frame_path)

    if frame is not None:
        frame = cv.resize(frame, (frame_width, frame_height))
        frames.append(frame)

for _ in range(5):
    for frame in frames:
        out.write(frame)
    for frame in reversed(frames):
        out.write(frame)

out.release()

print("부메랑 비디오 저장 완료")

카메라 사용하기

  • 웹캠 사용하기
import cv2 as cv
import time

cap = cv.VideoCapture(1)

fourcc = cv.VideoWriter_fourcc(*'XVID')
out = cv.VideoWriter('output.avi', fourcc, 20.0, (640, 480))

time.sleep(5)

while True:
    ret, frame = cap.read()
    if not ret:
        break

    cv.imshow('Camera', frame)
    out.write(frame)

    if cv.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
out.release()
cv.destroyAllWindows()
  • 이미지만 가져오기 (한 프레임만)
import cv2 as cv

cap = cv.VideoCapture(1)

ret, frame = cap.read()

if ret:
    cv.imwrite('captured_image.jpg', frame)
    print("이미지가 저장되었습니다.")
else:
    print("이미지 캡처 실패")

cap.release()

이 글은 제로베이스 데이터 취업 스쿨의 강의 자료 일부를 발췌하여 작성되었습니다

0개의 댓글