Path: blob/master/Getting-Started-OpenCV-CUDA-Module/demo.py
3119 views
import argparse1import time23import cv24import numpy as np567def main(video, device):89# init dict to track time for every stage at each iteration10timers = {11"full pipeline": [],12"reading": [],13"pre-process": [],14"optical flow": [],15"post-process": [],16}1718# init video capture with video19cap = cv2.VideoCapture(video)2021# get default video FPS22fps = cap.get(cv2.CAP_PROP_FPS)2324# get total number of video frames25num_frames = cap.get(cv2.CAP_PROP_FRAME_COUNT)2627# read the first frame28ret, previous_frame = cap.read()2930if device == "cpu":3132# proceed if frame reading was successful33if ret:34# resize frame35frame = cv2.resize(previous_frame, (960, 540))3637# convert to gray38previous_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)3940# create hsv output for optical flow41hsv = np.zeros_like(frame, np.float32)4243# set saturation to 144hsv[..., 1] = 1.04546while True:47# start full pipeline timer48start_full_time = time.time()4950# start reading timer51start_read_time = time.time()5253# capture frame-by-frame54ret, frame = cap.read()5556# end reading timer57end_read_time = time.time()5859# add elapsed iteration time60timers["reading"].append(end_read_time - start_read_time)6162# if frame reading was not successful, break63if not ret:64break6566# start pre-process timer67start_pre_time = time.time()68# resize frame69frame = cv2.resize(frame, (960, 540))7071# convert to gray72current_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)7374# end pre-process timer75end_pre_time = time.time()7677# add elapsed iteration time78timers["pre-process"].append(end_pre_time - start_pre_time)7980# start optical flow timer81start_of = time.time()8283# calculate optical flow84flow = cv2.calcOpticalFlowFarneback(85previous_frame, current_frame, None, 0.5, 5, 15, 3, 5, 1.2, 0,86)87# end of timer88end_of = time.time()8990# add elapsed iteration time91timers["optical flow"].append(end_of - start_of)9293# start post-process timer94start_post_time = time.time()9596# convert from cartesian to polar coordinates to get magnitude and angle97magnitude, angle = cv2.cartToPolar(98flow[..., 0], flow[..., 1], angleInDegrees=True,99)100101# set hue according to the angle of optical flow102hsv[..., 0] = angle * ((1 / 360.0) * (180 / 255.0))103104# set value according to the normalized magnitude of optical flow105hsv[..., 2] = cv2.normalize(106magnitude, None, 0.0, 1.0, cv2.NORM_MINMAX, -1,107)108109# multiply each pixel value to 255110hsv_8u = np.uint8(hsv * 255.0)111112# convert hsv to bgr113bgr = cv2.cvtColor(hsv_8u, cv2.COLOR_HSV2BGR)114115# update previous_frame value116previous_frame = current_frame117118# end post-process timer119end_post_time = time.time()120121# add elapsed iteration time122timers["post-process"].append(end_post_time - start_post_time)123124# end full pipeline timer125end_full_time = time.time()126127# add elapsed iteration time128timers["full pipeline"].append(end_full_time - start_full_time)129130# visualization131cv2.imshow("original", frame)132cv2.imshow("result", bgr)133k = cv2.waitKey(1)134if k == 27:135break136137else:138139# proceed if frame reading was successful140if ret:141# resize frame142frame = cv2.resize(previous_frame, (960, 540))143144# upload resized frame to GPU145gpu_frame = cv2.cuda_GpuMat()146gpu_frame.upload(frame)147148# convert to gray149previous_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)150151# upload pre-processed frame to GPU152gpu_previous = cv2.cuda_GpuMat()153gpu_previous.upload(previous_frame)154155# create gpu_hsv output for optical flow156gpu_hsv = cv2.cuda_GpuMat(gpu_frame.size(), cv2.CV_32FC3)157gpu_hsv_8u = cv2.cuda_GpuMat(gpu_frame.size(), cv2.CV_8UC3)158159gpu_h = cv2.cuda_GpuMat(gpu_frame.size(), cv2.CV_32FC1)160gpu_s = cv2.cuda_GpuMat(gpu_frame.size(), cv2.CV_32FC1)161gpu_v = cv2.cuda_GpuMat(gpu_frame.size(), cv2.CV_32FC1)162163# set saturation to 1164gpu_s.upload(np.ones_like(previous_frame, np.float32))165166while True:167# start full pipeline timer168start_full_time = time.time()169170# start reading timer171start_read_time = time.time()172173# capture frame-by-frame174ret, frame = cap.read()175176# upload frame to GPU177gpu_frame.upload(frame)178179# end reading timer180end_read_time = time.time()181182# add elapsed iteration time183timers["reading"].append(end_read_time - start_read_time)184185# if frame reading was not successful, break186if not ret:187break188189# start pre-process timer190start_pre_time = time.time()191192# resize frame193gpu_frame = cv2.cuda.resize(gpu_frame, (960, 540))194195# convert to gray196gpu_current = cv2.cuda.cvtColor(gpu_frame, cv2.COLOR_BGR2GRAY)197198# end pre-process timer199end_pre_time = time.time()200201# add elapsed iteration time202timers["pre-process"].append(end_pre_time - start_pre_time)203204# start optical flow timer205start_of = time.time()206207# create optical flow instance208gpu_flow = cv2.cuda_FarnebackOpticalFlow.create(2095, 0.5, False, 15, 3, 5, 1.2, 0,210)211# calculate optical flow212gpu_flow = cv2.cuda_FarnebackOpticalFlow.calc(213gpu_flow, gpu_previous, gpu_current, None,214)215216# end of timer217end_of = time.time()218219# add elapsed iteration time220timers["optical flow"].append(end_of - start_of)221222# start post-process timer223start_post_time = time.time()224225gpu_flow_x = cv2.cuda_GpuMat(gpu_flow.size(), cv2.CV_32FC1)226gpu_flow_y = cv2.cuda_GpuMat(gpu_flow.size(), cv2.CV_32FC1)227cv2.cuda.split(gpu_flow, [gpu_flow_x, gpu_flow_y])228229# convert from cartesian to polar coordinates to get magnitude and angle230gpu_magnitude, gpu_angle = cv2.cuda.cartToPolar(231gpu_flow_x, gpu_flow_y, angleInDegrees=True,232)233234# set value to normalized magnitude from 0 to 1235gpu_v = cv2.cuda.normalize(gpu_magnitude, 0.0, 1.0, cv2.NORM_MINMAX, -1)236237# get angle of optical flow238angle = gpu_angle.download()239angle *= (1 / 360.0) * (180 / 255.0)240241# set hue according to the angle of optical flow242gpu_h.upload(angle)243244# merge h,s,v channels245cv2.cuda.merge([gpu_h, gpu_s, gpu_v], gpu_hsv)246247# multiply each pixel value to 255248gpu_hsv.convertTo(cv2.CV_8U, 255.0, gpu_hsv_8u, 0.0)249250# convert hsv to bgr251gpu_bgr = cv2.cuda.cvtColor(gpu_hsv_8u, cv2.COLOR_HSV2BGR)252253# send original frame from GPU back to CPU254frame = gpu_frame.download()255256# send result from GPU back to CPU257bgr = gpu_bgr.download()258259# update previous_frame value260gpu_previous = gpu_current261262# end post-process timer263end_post_time = time.time()264265# add elapsed iteration time266timers["post-process"].append(end_post_time - start_post_time)267268# end full pipeline timer269end_full_time = time.time()270271# add elapsed iteration time272timers["full pipeline"].append(end_full_time - start_full_time)273274# visualization275cv2.imshow("original", frame)276cv2.imshow("result", bgr)277k = cv2.waitKey(1)278if k == 27:279break280281# release the capture282cap.release()283284# destroy all windows285cv2.destroyAllWindows()286287# print results288print("Number of frames : ", num_frames)289290# elapsed time at each stage291print("Elapsed time")292for stage, seconds in timers.items():293print("-", stage, ": {:0.3f} seconds".format(sum(seconds)))294295# calculate frames per second296print("Default video FPS : {:0.3f}".format(fps))297298of_fps = (num_frames - 1) / sum(timers["optical flow"])299print("Optical flow FPS : {:0.3f}".format(of_fps))300301full_fps = (num_frames - 1) / sum(timers["full pipeline"])302print("Full pipeline FPS : {:0.3f}".format(full_fps))303304305if __name__ == "__main__":306307# init argument parser308parser = argparse.ArgumentParser(description="OpenCV CPU/GPU Comparison")309310parser.add_argument(311"--video", help="path to .mp4 video file", required=True, type=str,312)313314parser.add_argument(315"--device",316default="cpu",317choices=["cpu", "gpu"],318help="device to inference on",319)320321# parsing script arguments322args = parser.parse_args()323video = args.video324device = args.device325326# output passed arguments327print("Configuration")328print("- device : ", device)329print("- video file : ", video)330331# run pipeline332main(video, device)333334335