본문 바로가기

카테고리 없음

OpenCV 카메라 pixel format MJPG 변경 및 FPS 확인

카메라 양식에는 분명히 fps가 60이라고 써져있는데, fps를 직접 찍어보면 30fps로 나오는 등의 이상현상을 볼 수 있다.

 

카메라 픽셀 형식에 따라 압축된 형태의 MJPG 일때만 그런 경우가 있다.

YUV에서는 30 fps이고,  MJPG일때는 다른 경우가 있다.

 

핵심은 밑에처럼 cap.set을 활용하여 fourcc를 설정해주는 것이다.

capture.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'))

 

전체 코드이다.

fps가 변경되는 것을 확인할 수 있다.

반드시 본인 카메라에 지원되는 형식이 무엇이 있는 지 확인해보고 사용하자.

 

import cv2
import time
import argparse

def camera_test(camera_number, frame_width, frame_height, pixel_format):
	# get camera and set properties
    cap = cv2.VideoCapture(camera_number, cv2.CAP_V4L2) # you can set CAP_DSHOW or CAP_ANY
	print("camera number ", camera_number)

	# check open
    if not cap.isOpened():
    	raise FileNotFoundError("Camera is not opened")
    
    # set properties
    camera_fourcc = cv2.VideoWriter_fourcc(*pixel_format)
    cap.set(cv2.CAP_PROP_FOURCC,camera_fourcc) # you can use *'MJPG'
    cap.set(cv2.CAP_PROP_FRAME_WIDTH,frame_width)
    cap.set(cv2.CAP_PROP_FRAME_HEIGHT,frame_height)
	print("[camera property] frame width ", frame_width)
	print("[camera property] frame height ", frame_height)
    print("[camera property] pixel format ", pixel_format)
    
	# get fps
    camera_fps = cap.get(cv2.CAP_PROP_FPS)
    print("[camera property] fps = ",fps)
    while(True):
    	process_start = time.time()
        success, frame = cap.read()
        
        if not success :
        	print("Frame End or Fail")
            break
        
        if frame is None :
			raise ValueError("frame is none.. check the camera")
        
		print("[FPS check] ", time.time() - process_start)        
		cv2.imshow('show',frame)
        cv2.waitKey(1)        
	cap.release()
    
if __name__ == "__main__" :
	parser = argparse.ArgumentParser(decription="Opencv Camera Pixel Format Test")
    parser.add_argument('--cam_num',type=int,default=0,help="set your camera number")
    parser.add_argument('--width',type=int,default=640,help="set frame width")
    parser.add_argument('--height',type=int,default=480,help="set frame height")
    args = parser.parse_args()
    camera_test(args.cam_num, args.width, args.height)

 

티스토리 코드가 이상하게 되어서 지금 단차가 안맞는데, 원래 잘 된다.