簡體   English   中英

使用opencv捕獲和存儲的視頻流獲得非常高的fps

[英]Getting very high fps for video stream captured and stored using opencv

我編寫了一個小的 python 代碼,它從網絡攝像頭捕獲視頻流,並將其寫入輸出文件。

我已經休眠了 50 毫秒,並在 VideoWriter 中指定了 20.0 的 fps,如下所示:

#!/usr/bin/python
import cv2
from PIL import Image
import threading
from http.server import BaseHTTPRequestHandler,HTTPServer
from socketserver import ThreadingMixIn
from io import StringIO,BytesIO
import time
import datetime

capture=None
out=None

class CamHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path.endswith('.mjpg'):
            self.send_response(200)
            self.send_header('Content-type','multipart/x-mixed-replace; boundary=--jpgboundary')
            self.end_headers()
            while True:
                try:
                    rc,img = capture.read()
                    if not rc:
                        continue
                    #Get the timestamp on the frame
                    timestamp = datetime.datetime.now()
                    ts = timestamp.strftime("%A %d %B %Y %I:%M:%S%p")
                    cv2.putText(img, ts, (10, img.shape[0] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.35, (0, 0, 255), 1)
                    #Store the frame into the output file
                    out.write(img)
                    #Some processing before sending the frame to webserver
                    imgRGB=cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
                    jpg = Image.fromarray(imgRGB)
                    tmpFile = BytesIO()
                    jpg.save(tmpFile,'JPEG')
                    self.wfile.write("--jpgboundary".encode())
                    self.send_header('Content-type','image/jpeg')
                    self.send_header('Content-length',str(tmpFile.getbuffer().nbytes))
                    self.end_headers()
                    jpg.save(self.wfile,'JPEG')
                    time.sleep(0.05)
                except KeyboardInterrupt:
                    break
            return
        if self.path.endswith('.html'):
            self.send_response(200)
            self.send_header('Content-type','text/html')
            self.end_headers()
            self.wfile.write('<html><head></head><body>'.encode())
            self.wfile.write('<img src="http://127.0.0.1:8080/cam.mjpg"/>'.encode())
            self.wfile.write('</body></html>'.encode())
            return


class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
    """Handle requests in a separate thread."""

def main():
    global capture
    global out
    capture = cv2.VideoCapture(0)

    # Define the codec and create VideoWriter object
    fourcc = cv2.VideoWriter_fourcc(*'XVID')
    out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))

    global img
    try:
        server = ThreadedHTTPServer(('0.0.0.0', 8080), CamHandler)
        print( "server started")
        server.serve_forever()
    except KeyboardInterrupt:
        capture.release()
        server.socket.close()
        out.release()
        cv2.destroyAllWindows()

if __name__ == '__main__':
    main()

它工作正常,我能夠保存視頻。 但是,在視頻屬性中看到的 fps 是 600.0(我設置的 30 倍!!)

$ mediainfo output.avi 
General
Complete name                            : output.avi
Format                                   : AVI
Format/Info                              : Audio Video Interleave
File size                                : 4.95 MiB
Duration                                 : 17s 252ms
Overall bit rate                         : 2 408 Kbps
Writing application                      : Lavf58.3.100

Video
ID                                       : 0
Format                                   : MPEG-4 Visual
Format profile                           : Simple@L1
Format settings, BVOP                    : No
Format settings, QPel                    : No
Format settings, GMC                     : No warppoints
Format settings, Matrix                  : Default (H.263)
Codec ID                                 : XVID
Codec ID/Hint                            : XviD
Duration                                 : 17s 252ms
Bit rate                                 : 2 290 Kbps
Width                                    : 640 pixels
Height                                   : 480 pixels
Display aspect ratio                     : 4:3
Frame rate                               : 600.000 fps
Color space                              : YUV
Chroma subsampling                       : 4:2:0
Bit depth                                : 8 bits
Scan type                                : Progressive
Compression mode                         : Lossy
Bits/(Pixel*Frame)                       : 0.012
Stream size                              : 4.71 MiB (95%)
Writing library                          : Lavc58.6.103

我很確定我的代碼看起來沒問題,如果有任何明顯的錯誤,請告訴我。 以防萬一,我正在使用帶有內置網絡攝像頭的 ubuntu 操作系統、華碩 X553M 筆記本電腦來運行上述內容。

編輯 1:我正在使用 python3,如果這很重要

編輯 2:使用 MJPG 編解碼器確實解決了問題,(感謝@api55)所以有人可以告訴我為什么 XVID 會給出不正確的 fps?

XVID 編解碼器是否可能錯誤地寫入 fps 屬性,而視頻實際上以 20 fps 正確編碼?

您每 50 毫秒 + 處理時間獲取幀,但將它們以 50 毫秒的延遲寫入視頻,因此它們將以更高的速度播放,比率=(50 + 處理時間)/ 50 毫秒。

我有這個食譜,它與安德烈回答的非常相似。 fps 非常接近預期。

cap = cv2.VideoCapture(capture) # 0 | filepath
fps = cap.get(cv2.CAP_PROP_FPS)
period = 1000 / fps

while cap.isOpened():
    start = time.time()

    success, frame = cap.read()
    if not success:
        if capture:
            break  # video
        continue  # cam

    # processing steps

    cv2.imshow('video (ESC to quit)', frame)
    processing_time = (time.time() - start) * 1000
    wait_ms = period - processing_time if period > processing_time else period
    if cv2.waitKey(int(wait_ms)) & 0xFF == 27:
        break
    end = (time.time() - start)
    print(f'FPS: {1.0 / end:.2f} (expected {fps:.2f})\r', end='')

暫無
暫無

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

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