ContinuumIO / anaconda-issues

Anaconda issue tracking
646 stars 220 forks source link

opencv - not writing output with cv2.VideoWriter.write #223

Open mattivi opened 9 years ago

mattivi commented 9 years ago

OpenCV is not writing to output video files with cv2.VideoWriter.write. I only get an empty video file (8 KB) and no error messages. Where is the problem? Thanks a lot! I am running 2.7.8 |Anaconda 2.1.0 (x86_64)| (default, Aug 21 2014, 15:21:46) [GCC 4.2.1 (Apple Inc. build 5577)] opencv 2.4.8 np17py27_2

Here is a sample test code that write an image to a video output file:

import cv2
import numpy as np
import Image

#read image
fname_img_02 = "test.png"
img_02 = Image.open(fname_img_02)
#convert to cv2 image
img_out_cv2 = np.array(img_02)
#convert from RGB of PIL to BGR of OpenCV
img_out_cv2 = img_out_cv2[:, :, ::-1].copy()
frameW = img_02.size[0]
frameH = img_02.size[1]

fourcc =  cv2.cv.CV_FOURCC(*'XVID')
video = cv2.VideoWriter("output.avi", fourcc, 2, (frameW,frameH), 1)
nFrames = 20

for i in range(nFrames):
    video.write(img_out_cv2)

video.release()
mattivi commented 9 years ago

I've tried installing OpenCV 2.4.9 with https://binstar.org/jjhelmus/opencv, but unfortunately with no results. Anyone is having the same issue? How to solve it? Thanks a lot.

kaanaksit commented 9 years ago

I am having the exact same problem with my ubuntu.

aizvorski commented 9 years ago

@mattivi you're running into essentially the same issue as #121, video file read/write fails on linux (it works ok on windows). ContinuumIO seems to give fixing this a pretty low priority, it's been a known issue for almost a year. Fortunately, I put together a workaround :) Use skvideo.io.VideoWriter in place of cv2.VideoWriter. The API is very similar. To write a file:

from skvideo.io import VideoWriter
import numpy
writer = VideoWriter(filename, frameSize=(w, h))
writer.open()
image = numpy.zeros((h, w, 3))
writer.write(image)
writer.release()

This uses avconv under the hood, so make sure you have that installed. Good luck!

tibinthomas commented 8 years ago

I too have got the same problem. Any solution anybody please --- > Looking forward for a solution as fast as possible

aizvorski commented 8 years ago

@tibinthomas The solution I posted doesn't work for you?

tibinthomas commented 8 years ago

@aizvorski I'm working with OpenCV 3.1.. skvideo module is missing.

from skvideo.io import VideoWriter ImportError: No module named skvideo.io

mgserafi commented 8 years ago

@tibinthomas you have to install it from https://github.com/scikit-video/scikit-video

You should have all the dependencies since you already have opencv

sadimanna commented 7 years ago

this is my code..... I wrote this in Python 2.7.11 IDLE......and I am not getting even the output file...

`import os, sys, subprocess as sp import numpy as np import cv2 import os, sys, subprocess as sp t1 = 6 t2 = 10 def Video_clip(filename,targetname = None): name,ext = os.path.splitext(filename) if not targetname: T1, T2 = [int(1000*t) for t in [0, 30]] targetname = name+ "4"+ext cmd = ["ffmpeg","-y", "-i", filename, "-ss", "%0.2f"%t1, "-t", "%0.2f"%(t2-t1), "-vcodec", "copy", "-acodec", "copy", targetname] sp.call(cmd)

...................................................................................................................................

filename = 'H:\PROJECT\Alphabets\A.mp4' targetname = 'H:\PROJECT\Alphabets\A_T.mp4' target_bw = 'H:\PROJECT\Alphabets\A_BW.mp4' Video_clip(filename,targetname) cap = cv2.VideoCapture(targetname) fourcc = cv2.VideoWriter_fourcc(*'MP4V') out = cv2.VideoWriter(target_bw,fourcc, 30.0, (640,480))

print cap.grab()

while cap.isOpened(): ret1,frame = cap.read() if not ret1: break

.......frame modification.....

frame = frame[100:600,300:1000,:]
frame = abs(255 - frame)
frame = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
ret2,thresh1 = cv2.threshold(frame,160,255,cv2.THRESH_BINARY_INV)
if not ret2:
    break
#........writing the frame.....#
out.write(thresh1)
cv2.imshow('frame',thresh1)
if cv2.waitKey(40) & 0xFF == ord('q'):
    break

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

cchacons commented 7 years ago

Anyone know if this issue has been fixed? it's been more than a year.

Thanks, Carlos

PetreanuAndi commented 7 years ago

@aizvorski , your solution does work, but the quality of the output is horrible (beyond the frist keyframe) Checking their documentation, i found this observation : "Often, writing videos requires fine tuning FFmpeg’s writing parameters to select encoders, framerates, bitrates, etc. For this, you can use skvideo.io.FFmpegWriter"

However, that does not compile, it can not find the FFmpegWriter method So i'm stuck at having very weak video quality with skvideo or none at all with opencv (known issue for about two years now)

Wtf people? Anybody else doing computer vision in Python and bashing themselves in the head? Any help would be amazing

miquelmarti commented 7 years ago

This looks ugly, seriously... VideoWriter is broken and no reference anywhere?

mgserafi commented 7 years ago

@PetreanuAndi, do you have ffmpeg installed?

PetreanuAndi commented 7 years ago

Hello. At that point in time I managed to output a significantly better quality video using :

fourcc = cv2.VideoWriter_fourcc('M', 'J', 'P', 'G') ..... writer = cv2.VideoWriter(str(video_path), fourcc, 12, (w 2, h 2), True) ...... output = cv2.cvtColor(output, cv2.COLOR_BGR2RGB) writer.write(output) .............

However, I do recall having to install a bunch of codecs and other such packages (including ffmpeg) in order for it to work. I found lots of incomplete advice online, so I really can-t recall right now what particular package did the trick, as it was more of a trial&error process of getting it to work. I hope this helps. I've moved on since then..

MrNocTV commented 7 years ago

Looks like there are a lot of issues with opencv3, but no one get things fixed. Alternative solution is a pain in the ass. I don't know if opencv2 is still in developed and maintained anymore?

jveitchmichaelis commented 7 years ago

The documentation in OpenCV says (hidden away) that you can only write to avi using OpenCV3. Whether that's true or not I've not been able to determine, but I've been unable to write to anything else.

However, OpenCV is mainly a computer vision library, not a video stream, codec and write one. Therefore, the developers tried to keep this part as simple as possible. Due to this OpenCV for video containers supports only the avi extension, its first version.

From: http://docs.opencv.org/3.1.0/d7/d9e/tutorial_video_write.html

My setup: I built OpenCV 3 from source using MSVC 2015, including ffmpeg. I've also downloaded and installed XVID and openh264 from Cisco, which I added to my PATH. I'm running Anaconda Python 3. I also downloaded a recent build of ffmpeg and added the bin folder to my path, though that shouldn't make a difference as its baked into OpenCV.

I'm running in Win 10 64-bit.

This code seems to work fine on my computer. It will generate a video containing random static:

writer = cv2.VideoWriter("output.avi", cv2.VideoWriter_fourcc(*"MJPG"), 30,(640,480))

for frame in range(1000):
    writer.write(np.random.randint(0, 255, (480,640,3)).astype('uint8'))

writer.release()

Some things I've learned through trial and error:

In the end I think the key point is that OpenCV is not designed to be a video capture library - it doesn't even support sound. VideoWriter is useful, but 99% of the time you're better off saving all your images into a folder and using ffmpeg to turn them into a useful video.

Bonus round - what about gstreamer? Here's an example of a grayscale video using X264. Note you must have WITH_GSTREAMER enabled (check with cv2.getBuildInformation). Like most things OpenCV, it will fail silently!

pipeline = "appsrc ! video/x-raw,format=GRAY8,width=640,height=480,framerate=60/1 ! videoconvert ! x264enc ! avimux ! filesink location= ./test.avi "

writer = cv2.VideoWriter(pipeline, cv2.CAP_GSTREAMER, 0, 60, (640,480))

# This will fail if WITH_GSTREAMER is off
# annoyingly it will still continue if your pipeline is invalid, but at least you'll get an error message.
if not output.isOpened():
    raise IOError

for frame in range(1000):
    writer.write(np.random.randint(0, 255, (480,640,3)).astype('uint8'))

writer.release()

This is a really effective way of ensuring that your video encoding will work. If you can capture from your source (e.g. camera) using a normal Gstreamer pipeline, you can chuck it into OpenCV. This is also one of the only ways to take advantage of hardware encoding (e.g. omxh264enc on the Pi).

Note the only modification is to change e.g. v4l2src with appsrc. Otherwise just modify your frame size and frame rates as appropriate in the pipeline and make sure they match up with your VideoWriter object. Then write your frame as you would normally.

bnestor commented 7 years ago

Hey, IT ONLY WORKS FOR RGB FRAMES! By chance I managed to have one video working, and one video not working from the same program. I tested each condition systematically and I found out that you cannot print a single frame grayscale image to video. Windows running Anaconda 4.3.16 / Python 2.7.13 64 bit with opencv version 3.1.0

`format='XVID' fps=5 fourcc = cv2.VideoWriter_fourcc(*format) vid = None

Next snippet goes into your loop where you call write images one at a time

green=np.asarray(img2).astype(np.uint8) blue=np.zeros_like(green) red=np.zeros_like(green) img3=cv2.merge((blue, green,red)) if vid is None: if size is None: size = img3.shape[1], img3.shape[0] vid = cv2.VideoWriter(filename, fourcc, float(fps), size, is_color) # my filename ends with .avi

if vid.isOpened():

#     print("TUREEEEEEEEEE")

if size[0] != img3.shape[1] and size[1] != img3.shape[0]: img3 = cv2.resize(img3, size) try: vid.write(img3) except: print("Error: video frame did not write")

after your loop you must release the video

vid.release()`

Let me know if you had the same experiences.

Edit: just read the comment above mine. But I will leave this up for the code (similiar to openCV's example in the docs)

jeremy-rutman commented 7 years ago

I was able to solve this by keeping the output video dimensions identical to the input frame dimensions.

NGJROMO commented 7 years ago

@jeremy-rutman

That works for me. Thx! Dimensions can be retrieved using cap.get(3) cap.get(4)

where cap is a VideoCapture object

ghost commented 6 years ago

@jeremy-rutman thanks!!! that worked for me.

SHOBAMOHAN commented 6 years ago

Hi, this code woks fine for writing the video 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()

vikash0837 commented 6 years ago

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

here the dimension (640,480) should match with the frame dimension. Just check frame.shape in python to verify.

hcz28 commented 6 years ago

@jveitchmichaelis Thanks!!! That really worked for me!

barisgecer commented 6 years ago

@jeremy-rutman I am leaving this here for others:

        cap = cv2.VideoCapture(file)
        fourcc = cv2.VideoWriter_fourcc(*'DIVX')
        out = cv2.VideoWriter('output.avi', fourcc, 20.0, (int(cap.get(3)),int(cap.get(4))))
        while(...)
            ret, frame = cap.read()        
            out.write(frame)
        cap.release()
        out.release()
sureshd2020 commented 6 years ago

I have been a stupid coder, I have been writing, video = cv2.VideoWriter("output.avi", fourcc, 2, (frameH,frameW), False),
instead of video = cv2.VideoWriter("output.avi", fourcc, 2, (frameW,frameH), True) Now, the frames are written into output.avi.

sureshd2020 commented 6 years ago

fourcc = cv2.cv.CV_FOURCC(*'XVID') video = cv2.VideoWriter("output.avi", fourcc, 2, (frameW,frameH), 1)

This works fine.

sureshd2020 commented 6 years ago

I wanted to read a .mpg video file and extract a segment of it begining at 10 seconds from begining and for 30 seconds and write the resulting segment into another file, ouput.avi. This is how I did it and it works:

import cv2 import numpy as np import datetime import argparse import imutils

ap = argparse.ArgumentParser()

ap.add_argument("-f", "--fps", type=int, default=25, help="FPS of output video") ap.add_argument("-c", "--codec", type=str, default="MJPG", help="codec of output video") args = vars(ap.parse_args())

fourcc = cv2.VideoWriter_fourcc(*args["codec"]) framecnt = 0 cap= cv2.VideoCapture('e:\videos\enter capture\20180624-104315.MPG') success, image = cap.read()

cv2.namedWindow("Video Display") cap.set(cv2.CAP_PROP_POS_FRAMES,10000)

framerate = cap.get(5) print ("framerate: ", framerate) framecount = cap.get(7) print("framecount: ",framecount) success,image = cap.read() startFrameCount = framecount starttime = datetime.datetime.now().strftime("%a, %d %B %Y %H:%M:%S") print("Start Time: ",starttime) h, w = image.shape[:2] out = cv2.VideoWriter('e:\videos\enter capture\outVideo.avi',fourcc, 2,(w,h),True)

while success:
success,image = cap.read() w = image.shape[0] h = image.shape[1] out.write(image)
framecount += 1 cv2.imwrite("frame%d.jpg" % framecount, image) cv2.imshow("Frame Name ", image)
out.write(image) zeros = np.zeros((h,w), dtype="int")

      deltaFrameCount = framecount - startFrameCount
      deltaInterval = deltaFrameCount / 25
      if deltaInterval > 30:
                break
      if cv2.waitKey(1) & 0xFF == ord('q'):
              break

When everything done, release the capture

deltaFrameCount = framecount - startFrameCount deltaInterval = deltaFrameCount / 25 endtime = datetime.datetime.now().strftime("%a, %d %B %Y %H:%M:%S") print("End Time: ",endtime) print("Video Interval %d secs"% deltaInterval) out.release() cap.release() cv2.destroyAllWindows()

sureshd2020 commented 6 years ago

After much time spent in experimenting, I found that with openCV version 3.3.1, running on Windows 10, VideoWriter does not like special characters in the output file name. For example, I used "c:\python36\output24-07-2018||12:49.avi" as output fie name and it did not even open such a file. But, when I changed the filename to "c:\python36\output24072018_1249.avi", everything worked. This may need further investigation. Thanks for the hints, y'all.

sureshd2020 commented 6 years ago

I am sorry, I made a mistake in my previous post. Actually, VideoWriter does not permit even the character in the filename. When it finds the "_" character it truncate everything following it. Some strange editing going on either in the Python3.6 System internals or OpenCv internals.

mingwandroid commented 6 years ago

No these are limitations of Windows.

On Tue, Jul 24, 2018, 8:25 AM sureshd2014 notifications@github.com wrote:

I am sorry, I made a mistake in my previous post. Actually, VideoWriter does not permit even the "" character in the filename. When it finds the "" character it truncate everything following it. Some strange editing going on either in the Python3.6 System internals or OpenCv internals.

— You are receiving this because you are subscribed to this thread. Reply to this email directly, view it on GitHub https://github.com/ContinuumIO/anaconda-issues/issues/223#issuecomment-407308387, or mute the thread https://github.com/notifications/unsubscribe-auth/AA_pdKIMJ7ZlKIYLxpd8g6A7og6Nbxy4ks5uJswEgaJpZM4DFIdt .

sureshd2020 commented 6 years ago

OK. Here is the final openCV Videowriter code that worked for me. It allows the underscore char in the filename but no other special characters. from time import strftime ....... .......

datetm = strftime("%Y%m%d_%H%M%S") fileName = "e:\videos\Enter\output" + str(datetm) + ".avi" out = cv2.VideoWriter(str(fileName), fourcc, 25.0, (frameWidth, frameHeight),True) cv2.waitKey(1) That opened the file in the appropriate folder.

To write the frame into the file out.write(thisFrame) cv2.waitKey(2)

To close the file and cleanup out.release()

That worked for me. Good Luck

deepaktripathi1997 commented 6 years ago

this code hangs and the file is also not saved what to do I have used android webcam using its IP address

url = "http://192.168.0.104:8080/shot.jpg"

imgResp = urllib.request.urlopen(url) imgNp = np.array(bytearray(imgResp.read()),dtype=np.uint8)

imgResp = urllib.request.urlopen(url)

Finally decode the array to OpenCV usable format ;)

img = cv2.imdecode(imgNp,-1)

fourcc = cv2.VideoWriter_fourcc(*'MJPG') out = cv2.VideoWriter('output.avi',fourcc,20.0,(1280,720))

while True: imgResp = urllib.request.urlopen(url) imgNp = np.array(bytearray(imgResp.read()),dtype=np.uint8)

imgResp = urllib.request.urlopen(url)

# Numpy to convert into a array
#imgNp = np.array(bytearray(imgResp.read()),dtype=np.uint8)

 # Finally decode the array to OpenCV usable format ;) 
img = cv2.imdecode(imgNp,-1)

img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

cv2.imshow("Video",img)
#resized = cv2.resize(img,(480,640), interpolation = cv2.INTER_AREA)
out.write(img)
if cv2.waitKey(1)== 13:
    break

out.release()

cv2.destroyAllWindows()

aaruk commented 5 years ago

I am facing the exact same issue 4 years later, with no clear solution. The worst part is that the Videowriter writes & exits without any error messages! The code I use is the tutorial code given by opencv with some minor modifications in Ubuntu 14.04. Have tried all popular codecs (XVID, MJPG, X264, DIVX) have ensured that the image size given during VideoWriter initialization is the same as the image I am writing to into video. Made sure ffmpeg is installed in my machine. I can understand having issues. But failing silently is frustrating.

NOTE: The issue was opened 4 years ago!!!!!

shijithp00 commented 5 years ago

For Me, MPJG codec was giving a very ugly output, changing the codec to DIVX was giving a fairly good output output shape : (480, 640, 3), grayscale output with three channels not an actual grayscale o/p with just one channel.

# Create a VideoCapture object
cap = cv2.VideoCapture(0)

# Check if camera opened successfully
if (cap.isOpened() == False): 
    print("Unable to read camera feed")

# Define the codec and create VideoWriter object.The output is stored in 'outpy.avi' file.
# codec = cv2.VideoWriter_fourcc(*"MJPG"), this codec is not working properly to wrire grey image
codec = cv2.VideoWriter_fourcc(*'DIVX')
out = cv2.VideoWriter('outpy.avi',codec, 30, (int(cap.get(3)),int(cap.get(4))),False)

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

        #Convert the original frame to grey image
        output = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

        # Write the frame into the file 'output.avi'
        out.write(output)

        # Display the resulting frame
        cv2.imshow('frame',frame)

        # Press Esc on keyboard to stop recording
        if cv2.waitKey(1) == 27:
            break

    # Break the loop
    else:
        break

# When everything is done, release the video capture and video write objects
cap.release()
out.release()

# Closes all the frames
cv2.destroyAllWindows()
ragibayon commented 5 years ago

I was able to solve this by keeping the output video dimensions identical to the input frame dimensions.

Thank you that worked for me.

EVINK commented 5 years ago

@jeremy-rutman thanks, thats working for me with Ubuntu 18.04

LewisGS commented 5 years ago

Didn't work for me.. I'm trying to save a video but I have really problems, because I save the video in the correct folder but when I try to play it doesn't work just stay black... I try to follow the opencv documentation but it didn't works. I used most of extension, ('mp4v'), ('XDIV'), (*'DIVX')... Even downloading the codecs from fourcc.org, im really blocked. Could anyone help me. https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_gui/py_video_display/py_video_display.html

Im on win10, maybe its important to know...?

A piece of code: `
import numpy as np import cv2

cap = cv2.VideoCapture("myVideo.mp4")

fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('newVideo.avi',fourcc, 20.0, (640,480))

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

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

cap.release()
out.release()
cv2.destroyAllWindows()`
pknambiar commented 5 years ago

Same error with me too !

vikash0837 commented 5 years ago

Swap the tuple in out which contains (width,height)

On Fri 15 Mar, 2019, 9:20 AM PK Nambiar, notifications@github.com wrote:

Same error with me too !

— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/ContinuumIO/anaconda-issues/issues/223#issuecomment-473149131, or mute the thread https://github.com/notifications/unsubscribe-auth/Aa65YOpCzwf2ExbJH675DkiTVcRtnjvBks5vWxhwgaJpZM4DFIdt .

pknambiar commented 5 years ago

Nope.. that too doesn't work

vikash0837 commented 5 years ago

Can you send me your code at vkmrs30@gmail.com along with video file

On Fri 15 Mar, 2019, 9:48 AM PK Nambiar, notifications@github.com wrote:

Nope.. that too doesn't work

— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/ContinuumIO/anaconda-issues/issues/223#issuecomment-473153294, or mute the thread https://github.com/notifications/unsubscribe-auth/Aa65YMQgyUKpVB6c2FV21maRXMEs3wwiks5vWx8DgaJpZM4DFIdt .

vikash0837 commented 5 years ago

video writer should be released after the writing is completed.

On Fri 15 Mar, 2019, 9:48 AM PK Nambiar, notifications@github.com wrote:

Nope.. that too doesn't work

— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/ContinuumIO/anaconda-issues/issues/223#issuecomment-473153294, or mute the thread https://github.com/notifications/unsubscribe-auth/Aa65YMQgyUKpVB6c2FV21maRXMEs3wwiks5vWx8DgaJpZM4DFIdt .

pratikadarsh commented 5 years ago

for me correcting the file size in the VideoWriter constructor call solved the issue.

JavierClearImageAI commented 5 years ago

use the same directory:

input directory: /home/pepe/input_dir video_path: /home/pepe/outputfile.avi

Explanation: it looks that ffmpeg doesn't have the right to write files in another folder, at least in my case

dhiren-hamal commented 5 years ago

I was facing TypeError: must be real number, not tuple error which I solved by getting help from this thread

cap = cv2.VideoCapture(0) width = cap.get(cv2.CAP_PROP_FRAME_WIDTH) height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT) generates values in flot which causes the following error: TypeError: must be real number, not tuple which can be solve with parsing width and height into integer for example: writer = cv2.VideoWriter('my_video.mp4', cv2.VideoWriter_fourcc(*'XV ID'),30,(int(width), int(height)))

Hope this will help someone.

bharath5673 commented 5 years ago

OpenCV is not writing to output video files with cv2.VideoWriter.write. I only get an empty video file (8 KB

cap = cv2.VideoCapture(file)
    fourcc = cv2.VideoWriter_fourcc(*'DIVX')
    out = cv2.VideoWriter('output.avi', fourcc, 20.0, (int(cap.get(3)),int(cap.get(4))))
    while(...)
        ret, frame = cap.read()        
        out.write(frame)
    cap.release()
    out.release()
sureshd2020 commented 4 years ago

Thanks. This question is now closed. "Support the fight against Corruption - support "India Against Corruption".

On Wed, Jul 24, 2019 at 10:00 PM bharath notifications@github.com wrote:

OpenCV is not writing to output video files with cv2.VideoWriter.write. I only get an empty video file (8 KB

cap = cv2.VideoCapture(file) fourcc = cv2.VideoWriter_fourcc(*'DIVX') out = cv2.VideoWriter('output.avi', fourcc, 20.0, (int(cap.get(3)),int(cap.get(4)))) while(...) ret, frame = cap.read() out.write(frame) cap.release() out.release()

— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/ContinuumIO/anaconda-issues/issues/223?email_source=notifications&email_token=AB6GAL6SEWJMK2UE5GEUFA3QBB7QRA5CNFSM4AYUQ5W2YY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOD2W4MIA#issuecomment-514704928, or mute the thread https://github.com/notifications/unsubscribe-auth/AB6GAL6QOY5XDKTTVDT2XI3QBB7QRANCNFSM4AYUQ5WQ .

yongen9696 commented 4 years ago

My case is a bit weird, I need to write the same file for twice, then the video only can play. My OS is ubuntu 18.04.03 LTS

Hashemian01 commented 4 years ago

This one worked for me

!pip install sk-video
import cv2
from skvideo.io import vwrite
from skvideo.io import FFmpegWriter
cap = cv2.VideoCapture('Input.mp4')
fps=cap.get(cv2.CAP_PROP_FPS)
W=int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
H=int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
out = FFmpegWriter('Output.avi', 
            inputdict={'-r': str(fps), '-s':'{}x{}'.format(W,H)},
            outputdict={'-r': str(fps), '-c:v': 'libx264', '-preset': 'ultrafast', '-pix_fmt': 'yuv444p'})
while True:
  success , frame = cap.read()
  if success==True:
    out.writeFrame(frame)
  else:
    break
cap.release()
PrasadNR commented 4 years ago

Thanks. This question is now closed. "Support the fight against Corruption - support "India Against Corruption". On Wed, Jul 24, 2019 at 10:00 PM bharath @.**> wrote: OpenCV is not writing to output video files with cv2.VideoWriter.write. I only get an empty video file (8 KB cap = cv2.VideoCapture(file) fourcc = cv2.VideoWriter_fourcc('DIVX') out = cv2.VideoWriter('output.avi', fourcc, 20.0, (int(cap.get(3)),int(cap.get(4)))) while(...) ret, frame = cap.read() out.write(frame) cap.release() out.release() — You are receiving this because you commented. Reply to this email directly, view it on GitHub <#223?email_source=notifications&email_token=AB6GAL6SEWJMK2UE5GEUFA3QBB7QRA5CNFSM4AYUQ5W2YY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOD2W4MIA#issuecomment-514704928>, or mute the thread https://github.com/notifications/unsubscribe-auth/AB6GAL6QOY5XDKTTVDT2XI3QBB7QRANCNFSM4AYUQ5WQ .

What nonsense is this? How do I flag this irrelevant comment? This issue is open since 6 years now and I am facing issues.

dashesy commented 3 years ago

It worked for me after I resized to the target video size

fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi', fourcc, 20.0, (640,480))
...
frame = cv2.resize(frame, (640, 480), cv2.INTER_LANCZOS4)
...
out.write(frame)
...
out.release()

Without that write silently fails! and there is no indication of error other than small output file!!