Deep Learning/vision

OpenCV 영상 처리

jiseong 2021. 8. 7. 02:57
728x90

OpenCV

https://github.com/chulminkw/DLCV/blob/master/Detection/preliminary/OpenCV%EC%9D%B4%EB%AF%B8%EC%A7%80%EC%99%80%20%EC%98%81%EC%83%81%EC%B2%98%EB%A6%AC%20%EA%B0%9C%EC%9A%94.ipynb

위의 깃허브 코드를 기반으로 작성한다.

 

OpenCV는 방대한 컴퓨터 비전 관련 라이브러리와 손쉬운 인터페이스를 제공해주는 모듈이다. 이를 활용해 아주 쉽게 영상처리를 할 수 있다.

 

이미지 로딩

import cv2
import matplotlib.pyplot as plt

img_array = cv2.imread("파일명")
plt.imshow(img_array)

imread()를 이용하여 이미지를 로드할 수 있다. 주의해야 할 점은 OpenCV가 이미지를 RGB 형태가 아닌 BGR 형태로 로딩한다는 것이다. 

왼쪽이 원본 이미지, 오른쪽이 imread()로 읽은 이미지이다. 따라서 BGR 을 RGB로 바꾸어 주어야한다.

cvtColor(원본 이미지,cv2.COLOR_BGR2RGB)를 이용해야한다.

import cv2
import matplotlib.pyplot as plt

bgr_img_array = cv2.imread("파일명")
rgb_img_array = cv2.cvtColor(bgr_img_array, cv2.COLOR_BGR2RGB)
plt.imshow(rgb_img_array)

 

파일에 이미지 쓰기

import cv2
import matplotlib.pyplot as plt

img_array = cv2.imread("파일명") 
cv2.imwrite("출력파일명", img_array)

imwrite() 함수를 이용하여 파일에 이미지를 쓸 수 있다. 여기서는 RGB로 바꿀 필요가 없다. imwrite()는 BGR 파일을 RGB 파일로 자동 변환 해준다.

 

영상처리

VideoCapture 클래스는 동영상을 개별 Frame으로 하나씩 읽어들이는 기능을 제공한다. 아주 편리한 클래스이다.

OpenCV의 VideoCapture를 이용해 영상처리를 해보자.

 

import cv2

video_input_path = '/content/data/Night_Day_Chase.mp4'
video_output_path = '/content/data/Night_Day_Chase_out.mp4'

원본 비디오의 경로와 영상 처리를 한 뒤 출력되는 비디오의 경로를 지정해준다

 

cap = cv2.VideoCapture(video_input_path)
codec = cv2.VideoWriter_fourcc(*'XVID')

vid_size = (round(cap.get(cv2.CAP_PROP_FRAME_WIDTH)),round(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
vid_fps = cap.get(cv2.CAP_PROP_FPS )
    
vid_writer = cv2.VideoWriter(video_output_path, codec, vid_fps, vid_size) 

frame_cnt = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
print('총 Frame 갯수:', frame_cnt, 'FPS:', round(vid_fps), 'Frame 크기:', vid_size)

VideoCaptuer 객체와 VideoWriter 객체를 생성하고 frame의 갯수, FPS, video Frame 크기의 정보를 읽어 출력한다.

 

import time

green_color=(0, 255, 0)
red_color=(0, 0, 255)

start = time.time()
index=0
while True:
    hasFrame, img_frame = cap.read()
    if not hasFrame:
        print('더 이상 처리할 frame이 없습니다.')
        break
    index += 1
    print('frame :', index, '처리 완료')
    
    cv2.rectangle(img_frame, (300, 100, 800, 400), color=green_color, thickness=2)
    caption = "frame:{}".format(index)
    cv2.putText(img_frame, caption, (300, 95), cv2.FONT_HERSHEY_SIMPLEX, 0.7, red_color, 1)
    
    vid_writer.write(img_frame)

print('write 완료 시간:', round(time.time()-start,4))
vid_writer.release()
cap.release()

object detection을 아직 잘 못해서... 그냥 네모를 그려주자. time 모듈을 이용해서 영상 처리를 하는데 걸린 시간을 계산한다. cap.read() 를 이용해 프레임 하나하나를 읽어들인다. 반환 값은 다음 프레임의 유무와 현재 프레임이다. cv2.rectangle() 함수를 이용해 img_frame 하나하나에 네모를 그려준다. caption은 현재 프레임의 번호를 써주는 것이다.

네모 박스 왼쪽 위에다가 표시할거다. cv2.putText() 함수를 이용하여 text를 써 줄수 있다. 마지막으로 처리가 완료된 img_frame을 파일에다 써준다.

 

 

728x90