簡體   English   中英

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM