1

我正在尝试在 yolo 中检测后保存视频,它会保存视频但不显示检测到的项目。代码在这里

import cv2
from darkflow.net.build import TFNet
import numpy as np
import time
import os
from PyQt5 import QtCore, QtWidgets, QtGui, uic
from PyQt5.QtWidgets import QPushButton, QInputDialog, QLineEdit
from PyQt5.uic import loadUi
import sys
from PIL import Image

option= {
    'model':'cfg/yolo.cfg',
    'load':'bin/yolov2.weights',
    'threshold': 0.3,
    }
class MyWindow(QtWidgets.QMainWindow):

    def __init__(self):
        super(MyWindow, self).__init__()
        loadUi("new.ui", self)
        self.testcam.clicked.connect(self.CameraTest)
        self.start.clicked.connect(self.Camera)
        

    def CameraTest(self):
        cap = cv2.VideoCapture(0)
        cap.set(3,640) # set Width
        cap.set(4,480) # set Height
        while(True):
            ret, frame = cap.read()
            gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    
            cv2.imshow('CamTest', frame)
    
            k = cv2.waitKey(30) & 0xff
            if k == 27: # press 'ESC' to quit
                break
        cap.release()
        cv2.destroyAllWindows()
    def Camera(self):

        tfnet = TFNet(option)
        colors = [tuple(255 * np.random.rand(3)) for _ in range(10)]

        cap= cv2.VideoCapture(0)
        #cap.set(cv2.CAP_PROP_FRAME_WIDTH, 512)
        #cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 512)
        fourcc=cv2.VideoWriter_fourcc(*'XVID')
        out=cv2.VideoWriter('new.avi',fourcc,20.0,(640,480))

        while True:
            stime = time.time()
            ret, frame = cap.read()
            out.write(frame)
            if (ret==True):
                
                results = tfnet.return_predict(frame)
                for color, result in zip(colors, results):
                    tl = (result['topleft']['x'], result['topleft']['y'])
                    br = (result['bottomright']['x'], result['bottomright']['y'])
                    label = result['label']
                    confidence = result['confidence']
                    text = '{}: {:.0f}%'.format(label, confidence * 100)
                    frame = cv2.rectangle(frame, tl, br, color, 5)
                    frame = cv2.putText(
                        frame, text, tl, cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 0), 2)
                cv2.imshow('frame', frame)
                print('FPS {:.1f}'.format(1 / (time.time() - stime)))
                if cv2.waitKey(1) & 0xFF == ord('q'):
                    break
            else:
                break

        cap.release()
        out.release()
        cv2.destroyAllWindows()
if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    window = MyWindow()
    window.show()
    sys.exit(app.exec_())
4

1 回答 1

1

这两行应该写在循环之前

codec = cv2.VideoWriter_fourcc(*"MJPG")

out = cv2.VideoWriter('./processed.avi' , codec, fps, (width, height))

这应该在 imshow() 上方的循环内

out.write(frame)
于 2020-12-03T17:30:37.487 回答