简体   繁体   English

OpenCV和Python:如果源不是来自网络摄像头,则视频输出为空

[英]OpenCV and Python: Video output is empty if the source is not coming from the webcam

I'm currently struggling with opencv in python 2.7 我目前在python 2.7中正在与opencv挣扎

The aim of the program I'm trying to write is to open a source video with VideoCapture (is a mp4 with H264 codec), apply some filters (background removal, object tracking, stuff like that), display the result in a frame with imshow function, and save the result as another output video. 我要编写的程序的目的是使用VideoCapture(带有H264编解码器的mp4)打开源视频,应用一些过滤器(背景移除,对象跟踪等),并使用imshow功能,并将结果另存为另一个输出视频。

The output frame is shown as it should, but the problem is that the output saved is an empty .avi (or mp4, or whatever I put as argument of VideoWriter function). 输出帧按原样显示,但问题是保存输出 一个空的 .avi(或mp4,或我作为VideoWriter函数的参数输入的任何内容)。 Just a nutshell of few Bytes . 简而言之就是几个字节

So far you could just answer that I'm not using the appropriate combination of codec-format. 到目前为止,您可以回答我没有使用编解码器格式的适当组合。 But the odd thing is that if I change the VideoCapture to stream from webcam (so just changing VideoCaputure("source.mp4") to VideoCapture(webcamindex) and leaving every settings as they are), it works fine ! 但是奇怪的是,如果我将VideoCapture更改为从网络摄像头流式传输(因此只需将VideoCaputure(“ source.mp4”)更改为VideoCapture(webcamindex)并保留所有设置), 一切正常

My program is something like that, I just omitted the functions 我的程序就是这样,我只是省略了函数

import cv2
import numpy as np

#VIDEO INPUT: SWITCHING THE TWO LINES BELOW IT WORKS!
#cap = cv2.VideoCapture(1)
cap = cv2.VideoCapture('input.mp4')

fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi', fourcc, 30, (640,480), True)

while True:
    ret, frame = cap.read()

    #A BACKGROUND REMOVAL FUNCTION
    maskedMotion = justMotion(frame)

    #A FUNCTION THAT FINDS CIRCLE THROUGH THE HOUGHCIRCLE FUNCTION
    circle = findBall(maskedMotion)    

    #DRAW THE CIRCLES
    if circle!=None and circle.size != 0:    
        for i in circle[0,:]:
            #draw the outer circle
            cv2.circle(maskedMotion,(i[0],i[1]),i[2],(0,255,0),2)
            #draw the center of the circle
            cv2.circle(maskedMotion,(i[0],i[1]),2,(0,0,255),3)

    out.write(maskedMotion)
    cv2.imshow('Result', maskedMotion)

    #ESCAPE SEQUENCE
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
out.release()
cv2.destroyAllWindows()

Any suggestions? 有什么建议么?

As suggested by shawshank in a comment, the problem was the resolution. 正如肖申克在评论中所建议的那样,问题在于解决方案。 I was trying to save a video output with a smaller resolution than the original source. 我试图以比原始来源小的分辨率保存视频输出。 So I just changed 所以我改变了

out = cv2.VideoWriter('output.avi', fourcc, 30, (640,480), True)

for 对于

out = cv2.VideoWriter('output.avi', fourcc, 30, (1920,1080), True)

Hope someone else will find this tip useful :D 希望其他人会发现此技巧有用:D

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM