gpt4 book ai didi

Python CV2 视频编写器不保存视频

转载 作者:行者123 更新时间:2023-12-05 05:55:07 24 4
gpt4 key购买 nike

我有一个简单的 python 代码,它使用 OpenCV 和 Keras 对帧执行一些检测(我之前的问题 here 的后续问题)。但是当我想使用 video_writer 将帧记录并保存为视频时,生成的视频是空的。

video_writer 出了什么问题?

#........some code    
# start the webcam feed
cap = cv2.VideoCapture(1)

canvasImageOriginal = cv2.imread("fg2.png")
canvasImage = cv2.imread("fg2.png")
canvasHappy = cv2.imread("fg2happy.png")
canvasSad = cv2.imread("fg2sad.png")
x0, x1 = 330, 1290
y0, y1 = 155, 700

#=========
w=960#int(cap.get(cv2.CV_CAP_PROP_FRAME_WIDTH ))
h=540#int(cap.get(cv2.CV_CAP_PROP_FRAME_HEIGHT ))
# video recorder
fourcc = cv2.VideoWriter_fourcc(*'XVID')
video_writer = cv2.VideoWriter('output.avi', fourcc, 25.0, (w, h))
#=========


prediction_history = []
LOOKBACK = 5 # how far you want to look back

counter = 0
while True:
# Find haar cascade to draw bounding box around face
ret, frame = cap.read()
frame=cv2.flip(frame,3)
if not ret:
break
facecasc = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = facecasc.detectMultiScale(gray,scaleFactor=1.3, minNeighbors=5)

for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y-50), (x+w, y+h+10), (255, 0, 0), 2)
roi_gray = gray[y:y + h, x:x + w]
cropped_img = np.expand_dims(np.expand_dims(cv2.resize(roi_gray, (48, 48)), -1), 0)
prediction = model.predict(cropped_img)

maxindex = int(np.argmax(prediction))
text = emotion_dict[maxindex]
print(prediction[0][3])

prediction_history.append(maxindex)
most_common_index = max(set(prediction_history[-LOOKBACK:][::-1]), key = prediction_history.count)
text = emotion_dict[most_common_index]

#if ("Sad" in text) or ("Angry" in text) or ("Disgusted" in text):
# text = "Sad"
if ("Happy" in text) or ("Sad" in text) :
cv2.putText(frame, text, (x+20, y-60), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2, cv2.LINE_AA)
if ("Happy" in text):
counter= counter+1
if counter == 10:
#print("Happy!")

canvasImage = canvasHappy
else:
counter = 0
canvasImage = canvasImageOriginal





dim = (800,480)
frame_shrunk = cv2.resize(frame, (x1 - x0, y1 - y0))
canvasImage[y0:y1, x0:x1] = frame_shrunk
#cv2.imshow('Video', cv2.resize(frame,dim,interpolation = cv2.INTER_CUBIC))
cv2.imshow('Demo', canvasImage)
video_writer.write(frame)

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

cap.release()
video_writer.release()
cv2.destroyAllWindows()

最佳答案

如上所述,请检查print(frame.shape)

当我这样做时,我看到了 (300,450,3),我将 videowriter 的分辨率更改为 (450,300),它对我有用。因此,我可以说 frame.shape=(y, x, maybe color)videowriter=(x,y) 的分辨率。

关于Python CV2 视频编写器不保存视频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69532134/

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