• python opencv 读取mp4,上一帧,下一帧


    目录

    安装pynput:

    python opencv 读取mp4, 有上一帧,下一帧的功能

    队列 缓存最新版,有帧号

    队列封装成类版本:


    安装pynput:

    pip install pynput

    python opencv 读取mp4, 有上一帧,下一帧的功能

    这个每次读取self.cap.set(cv2.CAP_PROP_POS_FRAMES, frame_index),后退读取稍微有点慢,

    1. import cv2
    2. from pynput import keyboard
    3. class VideoPlayer:
    4. def __init__(self, video_path):
    5. self.cap = cv2.VideoCapture(video_path)
    6. self.frame_index = -1
    7. self.total_frames = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT))
    8. self.new_frame_flag = False
    9. self.last_frame_i=0
    10. def show_frame(self, frame_index):
    11. if 0 <= frame_index < self.total_frames:
    12. if frame_index
    13. self.cap.set(cv2.CAP_PROP_POS_FRAMES, frame_index)
    14. self.last_frame_i = frame_index
    15. ret, frame = self.cap.read()
    16. if ret:
    17. cv2.imshow('Video', frame)
    18. self.frame_index = frame_index
    19. self.new_frame_flag = False
    20. def next_frame(self):
    21. if self.frame_index + 1 < self.total_frames:
    22. self.frame_index += 1
    23. self.new_frame_flag = True
    24. def prev_frame(self):
    25. if self.frame_index - 1 >= 0:
    26. self.frame_index -= 1
    27. self.new_frame_flag = True
    28. def on_press(self, key):
    29. if key == keyboard.Key.right: # Right arrow key
    30. self.next_frame()
    31. elif key == keyboard.Key.left: # Left arrow key
    32. self.prev_frame()
    33. elif str(key) == "'q'": # Press 'q' to exit
    34. return False
    35. def play(self):
    36. listener = keyboard.Listener(on_press=self.on_press)
    37. listener.start()
    38. self.show_frame(0) # Show the first frame
    39. while True:
    40. if self.new_frame_flag:
    41. self.show_frame(self.frame_index)
    42. if cv2.waitKey(1) & 0xFF == ord('q'): # Press 'q' to exit
    43. break
    44. cv2.destroyAllWindows()
    45. if __name__ == "__main__":
    46. player = VideoPlayer(rf'F:\data\9.mp4')
    47. player.play()

    队列 缓存最新版,有帧号

    1. import cv2
    2. from collections import deque
    3. from pynput import keyboard
    4. def on_press(key):
    5. global queue_index, load_new_frame
    6. if key == keyboard.Key.right or key == keyboard.Key.space: # Right arrow key
    7. if queue_index < len(frame_buffer) - 1:
    8. queue_index += 1
    9. else:
    10. load_new_frame = True
    11. elif key == keyboard.Key.left: # Left arrow key
    12. if queue_index > 0:
    13. queue_index -= 1
    14. load_new_frame = False
    15. elif str(key) == "'q'": # Press 'q' to exit
    16. return False
    17. listener = keyboard.Listener(on_press=on_press)
    18. listener.start()
    19. if __name__ == '__main__':
    20. cap = cv2.VideoCapture(r'C:\Users\Administrator\Documents\youjie\zhuanchang\11.mp4')
    21. deque_len = 300
    22. frame_buffer = deque(maxlen=deque_len)
    23. queue_index = -1
    24. load_new_frame = True
    25. frame_index = -1
    26. while cap.isOpened():
    27. if load_new_frame:
    28. ret, frame = cap.read()
    29. if not ret:
    30. print('video end')
    31. continue
    32. frame_index += 1
    33. cv2.putText(frame, str(frame_index), (20, 70), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 2)
    34. frame_buffer.append(frame)
    35. queue_index = len(frame_buffer) - 1
    36. # print('load frame_i', frame_index, "queue_i", queue_index, 'queue len', len(frame_buffer))
    37. load_new_frame = False
    38. # Show the current frame
    39. if len(frame_buffer) > 0:
    40. view_index = frame_index - len(frame_buffer) + queue_index + 1
    41. imshow = frame_buffer[queue_index]
    42. # print('show frame_i', frame_index, "queue_i", queue_index, 'view_i', view_index)
    43. if max(imshow.shape[:2])>1280:
    44. imshow = cv2.resize(imshow, (1280, 720))
    45. cv2.imshow('Video', imshow)
    46. if cv2.waitKey(1) & 0xFF == ord('q'): # Press 'q' to exit
    47. break
    48. # Release the video and close windows
    49. cap.release()
    50. cv2.destroyAllWindows()

    队列封装成类版本:

    1. import glob
    2. import os
    3. import re
    4. import cv2
    5. from collections import deque
    6. import yaml
    7. from pynput import keyboard
    8. from a2_jupter_check.ip_result.track_tool import get_box_dict, get_color
    9. def show_box(track_id, box, black_image):
    10. color = get_color(box['sku'])
    11. cv2.rectangle(black_image, (box['box'][0], box['box'][1]), (box['box'][2], box['box'][3]), color, 1)
    12. cv2.putText(black_image, f"p:{(box['prob']):.3f}", (box['box'][0], box['box'][1] + 20), cv2.FONT_HERSHEY_SIMPLEX, 0.6, color, 2)
    13. cv2.putText(black_image, "t:" + str(track_id), (box['box'][0], box['box'][1] + 40), cv2.FONT_HERSHEY_SIMPLEX, 0.6, color, 2)
    14. cv2.putText(black_image, "s:" + str(box['sku']), (box['box'][0], box['box'][1] + 60), cv2.FONT_HERSHEY_SIMPLEX, 0.6, color, 2)
    15. class VideoPlayer:
    16. def __init__(self, video_path,video_path2,track_txt):
    17. self.cap = cv2.VideoCapture(video_path)
    18. if door_type==1:
    19. self.cap2 = cv2.VideoCapture(video_path2)
    20. self.frame_index = -1
    21. self.total_frames = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT))
    22. if door_type == 1:
    23. self.total_frames2 = int(self.cap2.get(cv2.CAP_PROP_FRAME_COUNT))
    24. self.total_frames=min(self.total_frames,self.total_frames2)
    25. self.top_dict, self.bot_dict, self.end_index = get_box_dict(track_txt)
    26. self.queue_index = -1
    27. def save_cls_err(self,cam_id):
    28. if cam_id==0:
    29. box_id=0
    30. for box in self.top_boxes:
    31. img_crop=self.top_image_o[box['box'][1]:box['box'][3],box['box'][0]:box['box'][2]]
    32. save_path=f"{cls_dir}/{box['sku']}_{(box['prob']):.2f}_{self.frame_index}_0_{box_id}.jpg"
    33. cv2.imwrite(save_path,img_crop)
    34. print('cls top save img',save_path)
    35. box_id+=1
    36. elif cam_id==1:
    37. box_id = 0
    38. for box in self.bot_boxes:
    39. img_crop = self.bot_image_o[box['box'][1]:box['box'][3], box['box'][0]:box['box'][2]]
    40. save_path=f"{cls_dir}/{box['sku']}_{(box['prob']):.2f}_{self.frame_index}_1_{box_id}.jpg"
    41. cv2.imwrite(save_path, img_crop)
    42. print('cls bot save img',save_path)
    43. box_id += 1
    44. def on_press(self, key):
    45. global box_offset
    46. if key == keyboard.Key.right or key == keyboard.Key.space: # Right arrow key
    47. if self.queue_index < len(frame_buffer) - 1:
    48. self.queue_index += 1
    49. else:
    50. self.load_new_frame = True
    51. elif key == keyboard.Key.left: # Left arrow key
    52. if self.queue_index > 0:
    53. self.queue_index -= 1
    54. self.load_new_frame = False
    55. elif key == keyboard.KeyCode.from_char('+'): # Numpad +
    56. box_offset+=1
    57. print("box_offset +1", box_offset)
    58. self.new_frame_flag = True
    59. elif key == keyboard.KeyCode.from_char('-'): # Numpad -
    60. box_offset-=1
    61. print("box_offset -1", box_offset)
    62. self.new_frame_flag = True
    63. elif hasattr(key, 'char') and key.char =='1':
    64. self.save_cls_err(0)
    65. elif hasattr(key, 'char') and key.char =='2':
    66. self.save_cls_err(1)
    67. elif hasattr(key, 'char') and key.char =='3':
    68. save_path = f"{det_dir}/{sw_name}_{self.frame_index}_0.jpg"
    69. cv2.imwrite(save_path, self.top_img_big)
    70. print('save det err cam 0', save_path)
    71. elif hasattr(key, 'char') and key.char =='4':
    72. save_path = f"{det_dir}/{sw_name}_{self.frame_index}_1.jpg"
    73. cv2.imwrite(save_path, self.bot_img_big)
    74. print('save det err cam 1',save_path)
    75. elif str(key) == "'c'": # 's' key
    76. print('c')
    77. elif str(key) == "'d'": # 's' key
    78. print('d')
    79. elif str(key) == "'q'": # Press 'q' to exit
    80. return False
    81. else:
    82. try:
    83. if key.char == '/': # 检查按键字符
    84. print('Numpad / key pressed')
    85. elif key.char=='*':
    86. print('Numpad * key pressed')
    87. except AttributeError:
    88. pass
    89. def show_frame(self):
    90. listener = keyboard.Listener(on_press=self.on_press)
    91. listener.start()
    92. self.load_new_frame = True
    93. while self.cap.isOpened():
    94. if self.load_new_frame:
    95. ret, frame = self.cap.read()
    96. if not ret:
    97. print('video end')
    98. continue
    99. self.frame_index += 1
    100. cv2.putText(frame, str(self.frame_index), (20, 70), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 2)
    101. frame_buffer.append(frame)
    102. self.queue_index = len(frame_buffer) - 1
    103. # print('load frame_i', self.frame_index, "queue_i", queue_index, 'queue len', len(frame_buffer))
    104. self.load_new_frame = False
    105. # Show the current frame
    106. if len(frame_buffer) > 0:
    107. view_index = self.frame_index - len(frame_buffer) + self.queue_index + 1
    108. imshow = frame_buffer[self.queue_index]
    109. # print('show frame_i', self.frame_index, "queue_i", queue_index, 'view_i', view_index)
    110. cv2.imshow('Video', imshow)
    111. if cv2.waitKey(1) & 0xFF == ord('q'): # Press 'q' to exit
    112. break
    113. # Release the video and close windows
    114. self.cap.release()
    115. cv2.destroyAllWindows()
    116. if __name__ == '__main__':
    117. sbbh='2212311106000040'
    118. dir_a= r'F:\data\jupiter\err_nos\0912\569'
    119. dir_a= r'D:\data\err_orders\jupter_pair_09\SW0031423091206302824557'
    120. dir_a= r'D:\data\err_orders\jupter_pair_09\SW0031423091206323752502'
    121. cooler_path = rf'F:\data\jupiter\configs/{sbbh}/config/config_cooler.yaml'
    122. with open(cooler_path, 'r') as file:
    123. yaml_dict = yaml.safe_load(file)
    124. img_x=yaml_dict['img_x']
    125. # img_x = 1920 - 1240 - img_x
    126. img_y=yaml_dict['img_y']
    127. top_line=yaml_dict['top_line']
    128. bot_line=yaml_dict['bot_line']
    129. img_height, img_width = 744, 1240
    130. door_type = 1
    131. cls_dir=dir_a+'/cls'
    132. det_dir=dir_a+'/det'
    133. os.makedirs(cls_dir,exist_ok=True)
    134. os.makedirs(det_dir,exist_ok=True)
    135. mp4_files = glob.glob(dir_a + '/high_*.mp4')
    136. # img_x=300+75
    137. # img_y= 202
    138. box_offset= 0
    139. video_path=video_path2=None
    140. for file in mp4_files:
    141. if "high_" in file and "_0_" in file:
    142. video_path=file
    143. elif "high_" in file and "_1_" in file:
    144. video_path2=file
    145. elif "high_" in file and "_2_" in file:
    146. video_path=file
    147. door_type = 2
    148. print("door_type=2")
    149. if door_type==1 and (video_path is None or video_path2 is None):
    150. print("cap1 or cap2 is None")
    151. exit(0)
    152. txt_path = video_path.replace(".mp4", "_tracks.txt")
    153. pattern = r'SW\d+'
    154. match = re.search(pattern, txt_path)
    155. sw_name = ""
    156. if match:
    157. sw_name = match.group()
    158. if door_type==2:
    159. img_x = 1920 - 1240 - img_x
    160. deque_len = 30
    161. frame_buffer = deque(maxlen=deque_len)
    162. save_width = 1000
    163. save_height = save_width *(img_height * 2) // img_width
    164. mp4_path=os.path.dirname(txt_path)+'/'+sw_name+'_tracks.mp4'
    165. fourcc = cv2.VideoWriter_fourcc(*'mp4v') # 或者使用 'X264'
    166. out_writer = cv2.VideoWriter(mp4_path, fourcc, 25.0, (save_width, save_height))
    167. print('save track mp4 ',mp4_path,'w',save_width,'h',save_height)
    168. player = VideoPlayer(video_path,video_path2, txt_path)
    169. player.show_frame()

  • 相关阅读:
    如何更改代理ip,变更代理ip怎么实现?
    Allegro只给孔或pin加背钻属性操作指导
    Day19:属性封装详解
    xxl-job 数据库由mysql替换为postgre
    如何利用Python中实现高效的网络爬虫
    【freertos】002-posix模拟器设计与cortex m3异常处理
    年轻人应该做长期并能提升自己的兼职副业
    【ICLR 2021】半监督目标检测:Unbiased Teacher For Semi-Supervised Object Detection
    431. 将 N 叉树编码为二叉树 DFS
    Kubernetes k8s 平台部署常用命令
  • 原文地址:https://blog.csdn.net/jacke121/article/details/132843821