Как отобразить веб-камеру на вашем флеш-сервере? - PullRequest
0 голосов
/ 16 мая 2019

У меня есть два рабочих файла.Main.py и camera.py файл main.py состоит из функций, вызываемых из файла camera.py, а файл camera.py состоит из моего кода для yolo_webcam.Я получаю NameError: имя 'self' не определено.вот два файла ..

main.py

from flask import Flask, render_template, Response
from camera import VideoCamera

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

def gen(camera):
    while True:
        frame = camera.get_frame()
        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')

@app.route('/video_feed')
def video_feed():
    return Response(gen(VideoCamera()),
                    mimetype='multipart/x-mixed-replace; boundary=frame')

if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True)

camera.py

import cv2
import time
import numpy as np
from keras import backend as K
from keras.models import load_model
from yad2k.models.keras_yolo import yolo_head, yolo_eval
from yad2k.yolo_utils import read_classes, read_anchors, preprocess_webcam_image, draw_boxes, generate_colors

class VideoCamera(object):
    def __init__(self):
        # Using OpenCV to capture from device 0. If you have trouble capturing
        # from a webcam, comment the line below out and use a video file
        # instead.
        self.video = cv2.VideoCapture(0)
        class_names = read_classes("model_data/coco_classes.txt")
        anchors = read_anchors("model_data/yolo_anchors.txt")
        image_shape = (480., 640.)
        yolo_model = load_model("model_data/yolo.h5")
        print(yolo_model.summary())
        yolo_outputs = yolo_head(yolo_model.output, anchors, len(class_names))
        scores, boxes, classes = yolo_eval(yolo_outputs, image_shape)

        # If you decide to use video.mp4, you must have this file in the folder
        # as the main.py.
        # self.video = cv2.VideoCapture('video.mp4')

    def predict(sess, frame):
        # Preprocess your image
        image, image_data = preprocess_webcam_image(frame, model_image_size=(608, 608))

        # Run the session with the correct tensors and choose the correct placeholders in the feed_dict.
        # You'll need to use feed_dict={yolo_model.input: ... , K.learning_phase(): 0})
        out_scores, out_boxes, out_classes = sess.run([scores, boxes, classes], feed_dict={yolo_model.input: image_data,
        K.learning_phase(): 0})
        # Print predictions info
        print('Found {} boxes'.format(len(out_boxes)))
        # Generate colors for drawing bounding boxes.
        colors = generate_colors(class_names)
        # Draw bounding boxes on the image file
        draw_boxes(image, out_scores, out_boxes, out_classes, class_names, colors)

        return np.array(image)

    sess = K.get_session()
    while True:
        # Capture frame-by-frame
        grabbed, frame = self.video.read()
        if not grabbed:
            break

        #Run detection
        start = time.time()
        output_image = predict(sess, frame)
        end = time.time()
        print("Inference time: {:.2f}s".format(end - start))

    def __del__(self):
        self.video.release()
        cv2.destroyAllWindows()

    def get_frame(self):
        success, image = self.video.read()
        # We are using Motion JPEG, but OpenCV defaults to capture raw images,
        # so we must encode it into JPEG in order to correctly display the
        # video stream.
        ret, jpeg = cv2.imencode('.jpg', image)
        # Display the resulting frame
        cv2.imshow('', output_image)
        return jpeg.tobytes()

Где я ошибаюсь?Пожалуйста, помогите мне, я новичок.

1 Ответ

0 голосов
/ 16 мая 2019

В predict вы назвали свой первый параметр метода sess, а не self.Поэтому вы не можете сделать

grabbed, frame = self.video.read()

Возможно, вы захотите вместо этого попробовать

grabbed, frame = sess.video.read()

или переименовать первый параметр в self и изменить использование sess в predict соответственно.

...