OpenCV video write to file works but video is blank












0















I am using opencv for some neural style transfer trick, but I am having trouble saving the video to file. The file is created, but it is only 6 kb large.



from imutils.video import VideoStream
from imutils import paths
import itertools
import argparse
import imutils
import time
import cv2
import numpy as np

ap = argparse.ArgumentParser()
ap.add_argument("-m", "--models", required=True,
help="path to directory containing neural style transfer models")
args = vars(ap.parse_args())


modelPaths = paths.list_files(args["models"], validExts=(".t7",))
modelPaths = sorted(list(modelPaths))


models = list(zip(range(0, len(modelPaths)), (modelPaths)))

modelIter = itertools.cycle(models)
(modelID, modelPath) = next(modelIter)


print("[INFO] loading style transfer model...")
net = cv2.dnn.readNetFromTorch(modelPath)


print("[INFO] starting video stream...")
vs = VideoStream(src=0).start()
time.sleep(2.0)
print("[INFO] {}. {}".format(modelID + 1, modelPath))



out = cv2.VideoWriter('output2.avi', cv2.VideoWriter_fourcc(*'XVID'), 5, (451, 600))
while True:

frame = vs.read()




frame = imutils.resize(frame, width=600)
orig = frame.copy()
(h, w) = frame.shape[:2]


blob = cv2.dnn.blobFromImage(frame, 1.0, (w, h),
(103.939, 116.779, 123.680), swapRB=False, crop=False)
net.setInput(blob)
output = net.forward()


output = output.reshape((3, output.shape[2], output.shape[3]))
output[0] += 103.939
output[1] += 116.779
output[2] += 123.680
output /= 255.0
output = output.transpose(1, 2, 0)

out.write(np.uint8(output))

cv2.imshow("Input", frame)
cv2.imshow("Output", output)
key = cv2.waitKey(1) & 0xFF

if key == ord("n"):

(modelID, modelPath) = next(modelIter)
print("[INFO] {}. {}".format(modelID + 1, modelPath))
net = cv2.dnn.readNetFromTorch(modelPath)
print(frame.shape)

elif key == ord("q"):
break


cv2.destroyAllWindows()
vs.stop()


The main stuff are happening at:



out = cv2.VideoWriter('output2.avi', cv2.VideoWriter_fourcc(*'XVID'), 5, (450, 600))
output = net.forward() # which computes the neural styled output image


and to save output/frame to file, I did:



out.write(np.uint8(output))


Any ideas on why isn't my code working? I have tried many codec and file type combinations, and I don't believe the problem is there. Do you guys think it might be the dimension? (I have 450, 600 right now because I printed output.shape and it returned 450,600,3 so I think 450 x 600 sounds right).










share|improve this question























  • If you write np.uint8(output) to the video, then you should imshow the same thing. I see output /= 255.0, so my guess is that output is a floating point array with values in range [0.0, 1.0]. Casting that to uint8 will reduce it to just 0s and 1s. However, imshow (as per documentation) will convert and scale floating point images back to 0-255 range.

    – Dan Mašek
    Jan 1 at 17:44











  • @DanMašek is correct. You can read more about what he described here.

    – Berriel
    Jan 1 at 21:24











  • make sure your application has access to the opencv_ffmpeg dll (or shared lib?)

    – Micka
    Jan 1 at 22:58
















0















I am using opencv for some neural style transfer trick, but I am having trouble saving the video to file. The file is created, but it is only 6 kb large.



from imutils.video import VideoStream
from imutils import paths
import itertools
import argparse
import imutils
import time
import cv2
import numpy as np

ap = argparse.ArgumentParser()
ap.add_argument("-m", "--models", required=True,
help="path to directory containing neural style transfer models")
args = vars(ap.parse_args())


modelPaths = paths.list_files(args["models"], validExts=(".t7",))
modelPaths = sorted(list(modelPaths))


models = list(zip(range(0, len(modelPaths)), (modelPaths)))

modelIter = itertools.cycle(models)
(modelID, modelPath) = next(modelIter)


print("[INFO] loading style transfer model...")
net = cv2.dnn.readNetFromTorch(modelPath)


print("[INFO] starting video stream...")
vs = VideoStream(src=0).start()
time.sleep(2.0)
print("[INFO] {}. {}".format(modelID + 1, modelPath))



out = cv2.VideoWriter('output2.avi', cv2.VideoWriter_fourcc(*'XVID'), 5, (451, 600))
while True:

frame = vs.read()




frame = imutils.resize(frame, width=600)
orig = frame.copy()
(h, w) = frame.shape[:2]


blob = cv2.dnn.blobFromImage(frame, 1.0, (w, h),
(103.939, 116.779, 123.680), swapRB=False, crop=False)
net.setInput(blob)
output = net.forward()


output = output.reshape((3, output.shape[2], output.shape[3]))
output[0] += 103.939
output[1] += 116.779
output[2] += 123.680
output /= 255.0
output = output.transpose(1, 2, 0)

out.write(np.uint8(output))

cv2.imshow("Input", frame)
cv2.imshow("Output", output)
key = cv2.waitKey(1) & 0xFF

if key == ord("n"):

(modelID, modelPath) = next(modelIter)
print("[INFO] {}. {}".format(modelID + 1, modelPath))
net = cv2.dnn.readNetFromTorch(modelPath)
print(frame.shape)

elif key == ord("q"):
break


cv2.destroyAllWindows()
vs.stop()


The main stuff are happening at:



out = cv2.VideoWriter('output2.avi', cv2.VideoWriter_fourcc(*'XVID'), 5, (450, 600))
output = net.forward() # which computes the neural styled output image


and to save output/frame to file, I did:



out.write(np.uint8(output))


Any ideas on why isn't my code working? I have tried many codec and file type combinations, and I don't believe the problem is there. Do you guys think it might be the dimension? (I have 450, 600 right now because I printed output.shape and it returned 450,600,3 so I think 450 x 600 sounds right).










share|improve this question























  • If you write np.uint8(output) to the video, then you should imshow the same thing. I see output /= 255.0, so my guess is that output is a floating point array with values in range [0.0, 1.0]. Casting that to uint8 will reduce it to just 0s and 1s. However, imshow (as per documentation) will convert and scale floating point images back to 0-255 range.

    – Dan Mašek
    Jan 1 at 17:44











  • @DanMašek is correct. You can read more about what he described here.

    – Berriel
    Jan 1 at 21:24











  • make sure your application has access to the opencv_ffmpeg dll (or shared lib?)

    – Micka
    Jan 1 at 22:58














0












0








0








I am using opencv for some neural style transfer trick, but I am having trouble saving the video to file. The file is created, but it is only 6 kb large.



from imutils.video import VideoStream
from imutils import paths
import itertools
import argparse
import imutils
import time
import cv2
import numpy as np

ap = argparse.ArgumentParser()
ap.add_argument("-m", "--models", required=True,
help="path to directory containing neural style transfer models")
args = vars(ap.parse_args())


modelPaths = paths.list_files(args["models"], validExts=(".t7",))
modelPaths = sorted(list(modelPaths))


models = list(zip(range(0, len(modelPaths)), (modelPaths)))

modelIter = itertools.cycle(models)
(modelID, modelPath) = next(modelIter)


print("[INFO] loading style transfer model...")
net = cv2.dnn.readNetFromTorch(modelPath)


print("[INFO] starting video stream...")
vs = VideoStream(src=0).start()
time.sleep(2.0)
print("[INFO] {}. {}".format(modelID + 1, modelPath))



out = cv2.VideoWriter('output2.avi', cv2.VideoWriter_fourcc(*'XVID'), 5, (451, 600))
while True:

frame = vs.read()




frame = imutils.resize(frame, width=600)
orig = frame.copy()
(h, w) = frame.shape[:2]


blob = cv2.dnn.blobFromImage(frame, 1.0, (w, h),
(103.939, 116.779, 123.680), swapRB=False, crop=False)
net.setInput(blob)
output = net.forward()


output = output.reshape((3, output.shape[2], output.shape[3]))
output[0] += 103.939
output[1] += 116.779
output[2] += 123.680
output /= 255.0
output = output.transpose(1, 2, 0)

out.write(np.uint8(output))

cv2.imshow("Input", frame)
cv2.imshow("Output", output)
key = cv2.waitKey(1) & 0xFF

if key == ord("n"):

(modelID, modelPath) = next(modelIter)
print("[INFO] {}. {}".format(modelID + 1, modelPath))
net = cv2.dnn.readNetFromTorch(modelPath)
print(frame.shape)

elif key == ord("q"):
break


cv2.destroyAllWindows()
vs.stop()


The main stuff are happening at:



out = cv2.VideoWriter('output2.avi', cv2.VideoWriter_fourcc(*'XVID'), 5, (450, 600))
output = net.forward() # which computes the neural styled output image


and to save output/frame to file, I did:



out.write(np.uint8(output))


Any ideas on why isn't my code working? I have tried many codec and file type combinations, and I don't believe the problem is there. Do you guys think it might be the dimension? (I have 450, 600 right now because I printed output.shape and it returned 450,600,3 so I think 450 x 600 sounds right).










share|improve this question














I am using opencv for some neural style transfer trick, but I am having trouble saving the video to file. The file is created, but it is only 6 kb large.



from imutils.video import VideoStream
from imutils import paths
import itertools
import argparse
import imutils
import time
import cv2
import numpy as np

ap = argparse.ArgumentParser()
ap.add_argument("-m", "--models", required=True,
help="path to directory containing neural style transfer models")
args = vars(ap.parse_args())


modelPaths = paths.list_files(args["models"], validExts=(".t7",))
modelPaths = sorted(list(modelPaths))


models = list(zip(range(0, len(modelPaths)), (modelPaths)))

modelIter = itertools.cycle(models)
(modelID, modelPath) = next(modelIter)


print("[INFO] loading style transfer model...")
net = cv2.dnn.readNetFromTorch(modelPath)


print("[INFO] starting video stream...")
vs = VideoStream(src=0).start()
time.sleep(2.0)
print("[INFO] {}. {}".format(modelID + 1, modelPath))



out = cv2.VideoWriter('output2.avi', cv2.VideoWriter_fourcc(*'XVID'), 5, (451, 600))
while True:

frame = vs.read()




frame = imutils.resize(frame, width=600)
orig = frame.copy()
(h, w) = frame.shape[:2]


blob = cv2.dnn.blobFromImage(frame, 1.0, (w, h),
(103.939, 116.779, 123.680), swapRB=False, crop=False)
net.setInput(blob)
output = net.forward()


output = output.reshape((3, output.shape[2], output.shape[3]))
output[0] += 103.939
output[1] += 116.779
output[2] += 123.680
output /= 255.0
output = output.transpose(1, 2, 0)

out.write(np.uint8(output))

cv2.imshow("Input", frame)
cv2.imshow("Output", output)
key = cv2.waitKey(1) & 0xFF

if key == ord("n"):

(modelID, modelPath) = next(modelIter)
print("[INFO] {}. {}".format(modelID + 1, modelPath))
net = cv2.dnn.readNetFromTorch(modelPath)
print(frame.shape)

elif key == ord("q"):
break


cv2.destroyAllWindows()
vs.stop()


The main stuff are happening at:



out = cv2.VideoWriter('output2.avi', cv2.VideoWriter_fourcc(*'XVID'), 5, (450, 600))
output = net.forward() # which computes the neural styled output image


and to save output/frame to file, I did:



out.write(np.uint8(output))


Any ideas on why isn't my code working? I have tried many codec and file type combinations, and I don't believe the problem is there. Do you guys think it might be the dimension? (I have 450, 600 right now because I printed output.shape and it returned 450,600,3 so I think 450 x 600 sounds right).







python opencv conv-neural-network codec






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Jan 1 at 17:34









AcyAcy

8417




8417













  • If you write np.uint8(output) to the video, then you should imshow the same thing. I see output /= 255.0, so my guess is that output is a floating point array with values in range [0.0, 1.0]. Casting that to uint8 will reduce it to just 0s and 1s. However, imshow (as per documentation) will convert and scale floating point images back to 0-255 range.

    – Dan Mašek
    Jan 1 at 17:44











  • @DanMašek is correct. You can read more about what he described here.

    – Berriel
    Jan 1 at 21:24











  • make sure your application has access to the opencv_ffmpeg dll (or shared lib?)

    – Micka
    Jan 1 at 22:58



















  • If you write np.uint8(output) to the video, then you should imshow the same thing. I see output /= 255.0, so my guess is that output is a floating point array with values in range [0.0, 1.0]. Casting that to uint8 will reduce it to just 0s and 1s. However, imshow (as per documentation) will convert and scale floating point images back to 0-255 range.

    – Dan Mašek
    Jan 1 at 17:44











  • @DanMašek is correct. You can read more about what he described here.

    – Berriel
    Jan 1 at 21:24











  • make sure your application has access to the opencv_ffmpeg dll (or shared lib?)

    – Micka
    Jan 1 at 22:58

















If you write np.uint8(output) to the video, then you should imshow the same thing. I see output /= 255.0, so my guess is that output is a floating point array with values in range [0.0, 1.0]. Casting that to uint8 will reduce it to just 0s and 1s. However, imshow (as per documentation) will convert and scale floating point images back to 0-255 range.

– Dan Mašek
Jan 1 at 17:44





If you write np.uint8(output) to the video, then you should imshow the same thing. I see output /= 255.0, so my guess is that output is a floating point array with values in range [0.0, 1.0]. Casting that to uint8 will reduce it to just 0s and 1s. However, imshow (as per documentation) will convert and scale floating point images back to 0-255 range.

– Dan Mašek
Jan 1 at 17:44













@DanMašek is correct. You can read more about what he described here.

– Berriel
Jan 1 at 21:24





@DanMašek is correct. You can read more about what he described here.

– Berriel
Jan 1 at 21:24













make sure your application has access to the opencv_ffmpeg dll (or shared lib?)

– Micka
Jan 1 at 22:58





make sure your application has access to the opencv_ffmpeg dll (or shared lib?)

– Micka
Jan 1 at 22:58












1 Answer
1






active

oldest

votes


















2














@Dan Mašek's comment is probably correct. You can read more about it here. For completeness, you could fix it by:




  1. Changing out.write(np.uint8(output)) to out.write(np.uint8(output * 255))


or




  1. Comment output /= 255.0 and change cv2.imshow("Output", output) to cv2.imshow("Output", output / 255.)


You should choose the solution based on whether you want output to be on the (1) [0., 1.] or (2) [0, 255] range.






share|improve this answer



















  • 1





    Since output is only used to write either a video or show an image, I'd say the scaling is absolutely useless in the code shown. As such, I'd propose approach #3 -- ditch the output /= 255.0 and replace it with output = np.uint8(output). Then you can pass the same image to both write and imshow (I assume the reason for displaying it as well as writing is to be able to see exactly what it is you write). Anyway, +1 to you for writing an answer even though the OP couldn't be bothered to respond...

    – Dan Mašek
    Jan 1 at 22:46













  • so sorry, I didn't see this response. I will try it out first thing tomorrow morning.

    – Acy
    Jan 7 at 2:18











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53997532%2fopencv-video-write-to-file-works-but-video-is-blank%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









2














@Dan Mašek's comment is probably correct. You can read more about it here. For completeness, you could fix it by:




  1. Changing out.write(np.uint8(output)) to out.write(np.uint8(output * 255))


or




  1. Comment output /= 255.0 and change cv2.imshow("Output", output) to cv2.imshow("Output", output / 255.)


You should choose the solution based on whether you want output to be on the (1) [0., 1.] or (2) [0, 255] range.






share|improve this answer



















  • 1





    Since output is only used to write either a video or show an image, I'd say the scaling is absolutely useless in the code shown. As such, I'd propose approach #3 -- ditch the output /= 255.0 and replace it with output = np.uint8(output). Then you can pass the same image to both write and imshow (I assume the reason for displaying it as well as writing is to be able to see exactly what it is you write). Anyway, +1 to you for writing an answer even though the OP couldn't be bothered to respond...

    – Dan Mašek
    Jan 1 at 22:46













  • so sorry, I didn't see this response. I will try it out first thing tomorrow morning.

    – Acy
    Jan 7 at 2:18
















2














@Dan Mašek's comment is probably correct. You can read more about it here. For completeness, you could fix it by:




  1. Changing out.write(np.uint8(output)) to out.write(np.uint8(output * 255))


or




  1. Comment output /= 255.0 and change cv2.imshow("Output", output) to cv2.imshow("Output", output / 255.)


You should choose the solution based on whether you want output to be on the (1) [0., 1.] or (2) [0, 255] range.






share|improve this answer



















  • 1





    Since output is only used to write either a video or show an image, I'd say the scaling is absolutely useless in the code shown. As such, I'd propose approach #3 -- ditch the output /= 255.0 and replace it with output = np.uint8(output). Then you can pass the same image to both write and imshow (I assume the reason for displaying it as well as writing is to be able to see exactly what it is you write). Anyway, +1 to you for writing an answer even though the OP couldn't be bothered to respond...

    – Dan Mašek
    Jan 1 at 22:46













  • so sorry, I didn't see this response. I will try it out first thing tomorrow morning.

    – Acy
    Jan 7 at 2:18














2












2








2







@Dan Mašek's comment is probably correct. You can read more about it here. For completeness, you could fix it by:




  1. Changing out.write(np.uint8(output)) to out.write(np.uint8(output * 255))


or




  1. Comment output /= 255.0 and change cv2.imshow("Output", output) to cv2.imshow("Output", output / 255.)


You should choose the solution based on whether you want output to be on the (1) [0., 1.] or (2) [0, 255] range.






share|improve this answer













@Dan Mašek's comment is probably correct. You can read more about it here. For completeness, you could fix it by:




  1. Changing out.write(np.uint8(output)) to out.write(np.uint8(output * 255))


or




  1. Comment output /= 255.0 and change cv2.imshow("Output", output) to cv2.imshow("Output", output / 255.)


You should choose the solution based on whether you want output to be on the (1) [0., 1.] or (2) [0, 255] range.







share|improve this answer












share|improve this answer



share|improve this answer










answered Jan 1 at 21:55









BerrielBerriel

2,85211331




2,85211331








  • 1





    Since output is only used to write either a video or show an image, I'd say the scaling is absolutely useless in the code shown. As such, I'd propose approach #3 -- ditch the output /= 255.0 and replace it with output = np.uint8(output). Then you can pass the same image to both write and imshow (I assume the reason for displaying it as well as writing is to be able to see exactly what it is you write). Anyway, +1 to you for writing an answer even though the OP couldn't be bothered to respond...

    – Dan Mašek
    Jan 1 at 22:46













  • so sorry, I didn't see this response. I will try it out first thing tomorrow morning.

    – Acy
    Jan 7 at 2:18














  • 1





    Since output is only used to write either a video or show an image, I'd say the scaling is absolutely useless in the code shown. As such, I'd propose approach #3 -- ditch the output /= 255.0 and replace it with output = np.uint8(output). Then you can pass the same image to both write and imshow (I assume the reason for displaying it as well as writing is to be able to see exactly what it is you write). Anyway, +1 to you for writing an answer even though the OP couldn't be bothered to respond...

    – Dan Mašek
    Jan 1 at 22:46













  • so sorry, I didn't see this response. I will try it out first thing tomorrow morning.

    – Acy
    Jan 7 at 2:18








1




1





Since output is only used to write either a video or show an image, I'd say the scaling is absolutely useless in the code shown. As such, I'd propose approach #3 -- ditch the output /= 255.0 and replace it with output = np.uint8(output). Then you can pass the same image to both write and imshow (I assume the reason for displaying it as well as writing is to be able to see exactly what it is you write). Anyway, +1 to you for writing an answer even though the OP couldn't be bothered to respond...

– Dan Mašek
Jan 1 at 22:46







Since output is only used to write either a video or show an image, I'd say the scaling is absolutely useless in the code shown. As such, I'd propose approach #3 -- ditch the output /= 255.0 and replace it with output = np.uint8(output). Then you can pass the same image to both write and imshow (I assume the reason for displaying it as well as writing is to be able to see exactly what it is you write). Anyway, +1 to you for writing an answer even though the OP couldn't be bothered to respond...

– Dan Mašek
Jan 1 at 22:46















so sorry, I didn't see this response. I will try it out first thing tomorrow morning.

– Acy
Jan 7 at 2:18





so sorry, I didn't see this response. I will try it out first thing tomorrow morning.

– Acy
Jan 7 at 2:18




















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53997532%2fopencv-video-write-to-file-works-but-video-is-blank%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Monofisismo

Angular Downloading a file using contenturl with Basic Authentication

Olmecas