gpt4 book ai didi

python - OpenCV视频写入文件有效,但视频为空白

转载 作者:行者123 更新时间:2023-12-02 17:06:30 25 4
gpt4 key购买 nike

我正在使用opencv进行某些神经样式转换技巧,但无法将视频保存到文件中。文件已创建,但只有6 kb。

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()

主要的事情发生在:
out = cv2.VideoWriter('output2.avi', cv2.VideoWriter_fourcc(*'XVID'), 5, (450, 600))
output = net.forward() # which computes the neural styled output image

并将输出/帧保存到文件,我做了:
out.write(np.uint8(output))

关于我的代码为什么不起作用的任何想法?我尝试了许多编解码器和文件类型组合,但我不认为问题出在这里。你们认为这可能是维度吗? (我现在有450、600,因为我打印了output.shape,它返回了450,600,3,所以我认为450 x 600听起来不错)。

最佳答案

@Dan Mašek的评论可能是正确的。您可以阅读有关它的更多信息here。为了完整起见,您可以通过以下方式解决此问题:

  • out.write(np.uint8(output))更改为out.write(np.uint8(output * 255))


  • 注释output /= 255.0并将cv2.imshow("Output", output)更改为cv2.imshow("Output", output / 255.)

  • 您应该根据希望 output在(1) [0., 1.]或(2) [0, 255]范围内来选择解决方案。

    关于python - OpenCV视频写入文件有效,但视频为空白,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53997532/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com