python - 如何根据用户操作有选择地切换 OpenCV 的 VideoWriter

标签 python opencv

假设我有一些视频剪辑,它们应该显示特定的步骤序列,但在创建剪辑时,它们可能包含事件前后不需要的 Action 。

是否可以使用 OpenCV 逐帧自动播放视频,以便运算符(operator)在看到所需 Action 开始时按下一个键,在序列完成时按下另一个键并保存该部分视频作为序列的新的更小更准确的视频。

The code below will read in the webcam frame by frame, flip the frame before writing to a video until the user hits the qkey on their keyboard.

我如何确保用户可以在帧流进来时观看它们,然后当他们看到他们感兴趣的事件时,他们可以切换 VideoWriter 以开始将这些帧写入磁盘,但运算符(operator)不需要不断按下一个键将每一帧发送到 VideoWriter,当运算符(operator)看到事件结束时,他们可以再次关闭 VideoWriter

import numpy as np
import cv2

cap = cv2.VideoCapture(0)

# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))

while(cap.isOpened()):
    ret, frame = cap.read()
    if ret==True:
        frame = cv2.flip(frame,0)

        # write the flipped frame
        out.write(frame)

        cv2.imshow('frame',frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    else:
        break

# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()

最佳答案

考虑之后,逐帧编写视频不会很好地利用资源并且可能无法扩展。

我将扩展此代码以将事件数据写入 CSV 文件,并将其与 MoviePy 结合使用,以根据按下鼠标左键时记录的时间戳提取子剪辑

如果其他人可以改进解决方案,我欢迎他们的意见

import cv2
import numpy as np
cap = cv2.VideoCapture('YourVideoFile.mp4')

#Define the Mouse Callback Function
def record_action(event,x,y,flags,param):
    if event == cv2.EVENT_LBUTTONDOWN:
        print "Left Button Down @ " + str(cap.get(cv2.CAP_PROP_POS_MSEC)) + " milliseconds into video \n"
    elif event == cv2.EVENT_LBUTTONUP:
        print "Left Button Up @ " + str(cap.get(cv2.CAP_PROP_POS_MSEC)) + " milliseconds into video \n"

#Need to use a Named Window so it can be referenced in the mouse definition 
#and used when outputting the frames from the video in the imshow call later on
cv2.namedWindow("RecordMe")
#Bind the function above to the window
cv2.setMouseCallback("RecordMe",record_action)

while True:
    ret, frame = cap.read()
    #Use NamedWindow we created earlier to show the frames
    cv2.imshow('RecordMe',frame)
    if cv2.waitKey(30) & 0xff == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

关于python - 如何根据用户操作有选择地切换 OpenCV 的 VideoWriter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37864445/

相关文章:

python - 什么是 PasteDeploy,如果认为 Python 中的 Eggs 消失了,我还需要学习它吗?

python - 如何从python API azure sdk获取azure规模集实例的公共(public)IP?

python - 扩展 xlsxwriter.Worksheet() 类

python - 尝试调整由matplotlib.pyplot打印出的图像的大小

python - 使用scikit-image读取图像时出现以下错误 “AttributeError: ' PngImageFile'对象没有属性 '_PngImageFile__frame'”

c++ - 如何修复 OpenCV 中的 "Exception Thrown"错误?

c++ - 使用 OpenCV 计算网格上的对象

python - 使用 Python 3 更新 MySQL 数据库

python - 如何更改 Sublime Text 2 中的内置 python?

opencv - NVIDIA CUDA Toolkit 5.0 Visual Profiler "Enable concurrent kernels profiling"应用程序要求