OpenCV 和 python - 裁剪网络摄像头流并将其保存到文件
OpenCV and python - crop webcam stream and save it to file
我想将网络摄像头录制的视频的特定区域保存到文件中。
我通过使用变量 x_0、x_1(宽度)和 y_0、y_1(高度)来定义我想要记录的区域的限制,裁剪记录的帧并将其保存到文件中。我还将这些维度提供给 cv2.VideoWriter.
这是我的代码:
import cv2
def main():
# these are the limits of the cropped area
x_0 = 100
x_1 = 440
y_0 = 0
y_1 = 450
cap = cv2.VideoCapture(2)
fourcc = cv2.VideoWriter_fourcc(*'XVID')
# passing the dimensions of cropped area to VideoWriter
out_video = cv2.VideoWriter('recording.avi', fourcc, 15.0, (y_1-y_0, x_1-x_0))
while(cap.isOpened()):
ret, frame = cap.read()
if ret == True:
frame_crop = frame[y_0:y_1, x_0:x_1]
out_video.write(frame_crop)
cv2.imshow("crop", frame_crop)
key = cv2.waitKey(25)
if key == ord('q'):
break
else:
break
cv2.destroyAllWindows()
cap.release()
if __name__ == "__main__":
main()
当我停止录制时,生成了文件,但是它是空的。
问题在于我如何管理裁剪,因为如果我只是使用,比如:
out_video = cv2.VideoWriter('recording.avi', fourcc, 15.0, (640, 480))
并保存整个帧(通过使用 'out_video.write(frame_crop)')而不是裁剪的帧,它有效。
我做错了什么?
VideoWriter
中的视频大小参数的形状应为 (width, height)
您需要将对它的调用更改为:
out_video = cv2.VideoWriter('recording.avi', fourcc, 15.0, (x_1-x_0, y_1-y_0))
我想将网络摄像头录制的视频的特定区域保存到文件中。
我通过使用变量 x_0、x_1(宽度)和 y_0、y_1(高度)来定义我想要记录的区域的限制,裁剪记录的帧并将其保存到文件中。我还将这些维度提供给 cv2.VideoWriter.
这是我的代码:
import cv2
def main():
# these are the limits of the cropped area
x_0 = 100
x_1 = 440
y_0 = 0
y_1 = 450
cap = cv2.VideoCapture(2)
fourcc = cv2.VideoWriter_fourcc(*'XVID')
# passing the dimensions of cropped area to VideoWriter
out_video = cv2.VideoWriter('recording.avi', fourcc, 15.0, (y_1-y_0, x_1-x_0))
while(cap.isOpened()):
ret, frame = cap.read()
if ret == True:
frame_crop = frame[y_0:y_1, x_0:x_1]
out_video.write(frame_crop)
cv2.imshow("crop", frame_crop)
key = cv2.waitKey(25)
if key == ord('q'):
break
else:
break
cv2.destroyAllWindows()
cap.release()
if __name__ == "__main__":
main()
当我停止录制时,生成了文件,但是它是空的。 问题在于我如何管理裁剪,因为如果我只是使用,比如:
out_video = cv2.VideoWriter('recording.avi', fourcc, 15.0, (640, 480))
并保存整个帧(通过使用 'out_video.write(frame_crop)')而不是裁剪的帧,它有效。
我做错了什么?
VideoWriter
中的视频大小参数的形状应为 (width, height)
您需要将对它的调用更改为:
out_video = cv2.VideoWriter('recording.avi', fourcc, 15.0, (x_1-x_0, y_1-y_0))