• 【Opencv工程开发所用类】VideoTracker 视频摄像头


    前言

            本文提供一个功能完备的OpenCv视频播放处理类,供大家使用。(支持,保存视频、日志打印、视频裁剪、Q键退出、是否播放,选择使用摄像头或者视频


    【Opencv工程开发所用类】VideoTracker 视频摄像头

    前言

    VideoTracker.py

    Camer

    #using camer

    Video 

    #using video

    # save video

    # crop video  

    【OUTPUT】 


    VideoTracker.py

    1. # --time**2022.8.13
    2. # --** worker:江子良
    3. import cv2
    4. import time
    5. import torch
    6. import warnings
    7. import numpy as np
    8. from PIL import Image
    9. from loguru import logger
    10. import os
    11. os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
    12. class VideoTracker(object):
    13. def __init__(self, cam=-1, video_path='', save_path='', use_frame=[0, -1], display=True):
    14. self.display = display
    15. self.use_frame = use_frame
    16. self.video_path = video_path
    17. self.cam = cam
    18. if self.cam != -1:
    19. print("Using webcam :" + str(self.cam))
    20. self.vdo = cv2.VideoCapture(self.cam)
    21. else:
    22. print("Using video :" + str(self.video_path))
    23. self.vdo = cv2.VideoCapture()
    24. self.save_path = save_path
    25. self.frame_interval = 1
    26. self.use_cuda = True
    27. use_cuda = self.use_cuda and torch.cuda.is_available()
    28. if not use_cuda:
    29. warnings.warn("Running in cpu mode which maybe very slow!", UserWarning)
    30. def __enter__(self):
    31. if self.cam != -1:
    32. ret, frame = self.vdo.read()
    33. assert ret, "Error: Camera error"
    34. self.im_width = frame.shape[0]
    35. self.im_height = frame.shape[1]
    36. self.count_frame = int(-1)
    37. else:
    38. assert os.path.isfile(self.video_path), "Path error"
    39. self.vdo.open(self.video_path)
    40. self.im_width = int(self.vdo.get(cv2.CAP_PROP_FRAME_WIDTH))
    41. self.im_height = int(self.vdo.get(cv2.CAP_PROP_FRAME_HEIGHT))
    42. self.count_frame = int(self.vdo.get(cv2.CAP_PROP_FRAME_COUNT))
    43. assert self.vdo.isOpened()
    44. if self.save_path != '':
    45. os.makedirs(self.save_path, exist_ok=True)
    46. # path of saved video and results
    47. self.save_video_path = os.path.join(self.save_path, "results.avi")
    48. # create video writer
    49. fourcc = cv2.VideoWriter_fourcc(*'MJPG')
    50. self.writer = cv2.VideoWriter(self.save_video_path, fourcc, 24, (self.im_width, self.im_height))
    51. # logging
    52. logger.info("Save results to {}".format(self.save_path))
    53. return self
    54. def __exit__(self, exc_type, exc_value, exc_traceback):
    55. if exc_type:
    56. print(exc_type, exc_value, exc_traceback)
    57. def run(self):
    58. idx_frame = 0
    59. all_costTime = 0
    60. while self.vdo.grab():
    61. idx_frame += 1
    62. if idx_frame % self.frame_interval:
    63. continue
    64. if idx_frame < self.use_frame[0]:
    65. continue
    66. if idx_frame > self.use_frame[1] and self.use_frame[1] != -1:
    67. break
    68. start = time.time()
    69. ref, ori_im = self.vdo.retrieve()
    70. if ref is True:
    71. # start your code from here
    72. # -----------end-----------
    73. if self.display:
    74. cv2.imshow("frame", ori_im)
    75. if cv2.waitKey(1) & 0xFF == ord('q'):
    76. break
    77. if self.save_path:
    78. self.writer.write(ori_im)
    79. # logging
    80. end = time.time()
    81. all_costTime += end - start
    82. if self.display:
    83. if self.cam != -1:
    84. logger.info("frame schedule:<{}/-1> ({:.2f} ms), fps: {:.03f}"
    85. .format(idx_frame, end - start, 1 / (end - start)))
    86. else:
    87. logger.info("frame schedule:<{}/{}> ({:.2f} ms), fps: {:.03f}"
    88. .format(idx_frame, self.count_frame, end - start, 1 / (end - start)))
    89. logger.info("ALL_COST_TIME:{:.3f}s".format(all_costTime))

    Camer

    #using camer

    1. from VideoCapture import VideoTracker
    2. if __name__ == '__main__':
    3. # select the camer you want to use
    4. with VideoTracker(cam=0) as vdo_trk:
    5. vdo_trk.run()

    Video 

    #using video

    1. from VideoCapture import VideoTracker
    2. if __name__ == '__main__':
    3. # select the video you want to use
    4. with VideoTracker(video_path='test.mp4',use_frame=[0, -1]) as vdo_trk:
    5. vdo_trk.run()

    # save video

            只需要在VideoTracker中设置参数save_path,save_path是要存放保存视频的位置,如:'datasets/out_video/'

    1. from VideoCapture import VideoTracker
    2. if __name__ == '__main__':
    3. # select the video you want to use
    4. with VideoTracker(video_path='test.mp4',save_path='database/output/', use_frame=[0, -1]) as vdo_trk:
    5. vdo_trk.run()

    # crop video  

            use_frame=[0,-1],默认播放所有视频。

            裁剪视频的原理非常简单,比如将use_frame=[10,100],且设置save_path,就是只处理视频[10,100]帧,并且保存视频。也就是说最后的输出视频是只有[10,100]帧的视频。

    1. from VideoCapture import VideoTracker
    2. if __name__ == '__main__':
    3. # select the video you want to use
    4. with VideoTracker(video_path='test.mp4',save_path='database/output/', use_frame=[10, 100]) as vdo_trk:
    5. vdo_trk.run()

    【OUTPUT】 

    一些关于OpenCv的参数:

  • 相关阅读:
    puttygen工具ppk文件版本配置
    深入理解ElasticSearch集群:架构、高可用性与数据一致性
    【学生个人网页设计作品】使用HMTL制作一个超好看的保护海豚动物网页
    服务器远程管理-Windows远程桌面协议实操
    【C++笔试强训】第二十二天
    Fiddler工具 — 18.Fiddler抓包HTTPS请求(一)
    Casein-PEG-Indocyanine green 络蛋白-聚乙二醇-吲哚菁绿 Casein-ICG
    八股文-面向对象的理解
    Python 算法设计(2) - 大数运算 - 基于字符串的数字运算和进位
    如何理解ROS的ros::NodeHandle,学习ROS一年后的体会
  • 原文地址:https://blog.csdn.net/qq_51831335/article/details/126555452