Exemplo n.º 1
0
Arquivo: main.py Projeto: ECast221/G1
from flask import Flask, request, session, render_template, g, Response
from camera import VideoCamera
import cv2
import os

import pickle, socket, struct, threading

app = Flask(__name__, static_folder='static')
app.secret_key = 'secretkey'
backupCam = VideoCamera()
videoFrame = backupCam.get_frame()
connected = False

# PORT = int(os.environ.get('PORT'))    # HEROKU
PORT = 8089  # LOCAL


@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        session.pop('user_id', None)
        username = request.form['username']
        password = request.form['password']

        try:
            user = [x for x in users if x.username == username][0]
            if user and user.password == password:
                session['user_id'] = user.id
                return render_template('streams.html')
        except IndexError:
            return render_template('index.html')
import sys
import cv2
import argparse
import imutils
from camera import VideoCamera
from skimage import io

# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-v", "--video", help="path to the (optional) video file")
ap.add_argument("-b", "--buffer", type=int, default=64, help="max buffer size")
ap.add_argument("-m", "--model", help="path to trained model")
args = vars(ap.parse_args())

if not args.get("video", False):
    video_camera = VideoCamera(0)
    # otherwise, grab a reference to the video file
else:
    video_camera = VideoCamera(args["video"])


## This is the main function for detecting the car using the HOG method
def detect_car(frame):
    #load car detector
    detector = dlib.fhog_object_detector("../DATA/SVM/car_detector.svm")
    #win = dlib.image_window()
    try:
        dets = detector(frame)
        for d in dets:
            frame = frame[int(d.top()):int(d.bottom() + 20),
                          int(d.left()):int(d.right() + 20)]
def video_feed():
    return Response(gen(VideoCamera()),
                    mimetype='multipart/x-mixed-replace; boundary=frame')
Exemplo n.º 4
0
# Dan McGinn

from flask import Flask, render_template, url_for, request, redirect, make_response, Response, request  # micro web framework
from camera import VideoCamera  # Camera Module
import RPi.GPIO as GPIO  # GPIO library to control GPIO pins of Raspberry Pi
import time, threading, os, socket, random, json

pi_camera = VideoCamera(flip=False)  # flip pi camera if upside down.

app = Flask(__name__)

ip_address = ''
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
ip_address = s.getsockname()[0]  # Get IP Address
s.close()

host_port = 8000  # Set host port


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


def gen(camera):
    #get camera frame
    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')
Exemplo n.º 5
0
# Credits: http://blog.miguelgrinberg.com/post/video-streaming-with-flask
#
# Usage:
# 1. Install Python dependencies: cv2, flask. (wish that pip install works like a charm)
# 2. Run "python main.py".
# 3. Navigate the browser to the local webpage.
from flask import Flask, render_template, Response, jsonify, redirect, request, url_for
from camera import VideoCamera
from PIL import Image
import re
from io import BytesIO
import io
import base64
app = Flask(__name__)

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



def gen():
    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(), mimetype='multipart/x-mixed-replace; boundary=frame')
Exemplo n.º 6
0
def feed():
    # VideoCameraに変更 
    return Response(generate(VideoCamera()), mimetype='multipart/x-mixed-replace; boundary=frame')
Exemplo n.º 7
0
 def video_feed():
     # mengambil nilai balikan object VideoCamera untuk di stream
     return Response(gen(VideoCamera()),
                     mimetype='multipart/x-mixed-replace; boundary=frame')
Exemplo n.º 8
0
def livestream():

    video_camera = VideoCamera()  # creates a camera object, flip vertically
    object_classifier = cv2.CascadeClassifier(
        "/home/pi/opencv/data/haarcascades/haarcascade_upperbody.xml",
    )  # an opencv classifier
    face_classifier = cv2.CascadeClassifier(
        "/home/pi/opencv/data/haarcascades/haarcascade_frontalface_default.xml"
    )  #must change for your filesystem
    # App Globals (do not edit)
    app = Flask(__name__)
    app.config['BASIC_AUTH_USERNAME'] = '******'
    app.config['BASIC_AUTH_PASSWORD'] = '******'
    app.config['BASIC_AUTH_FORCE'] = True
    last_epoch = 0.0
    basic_auth = BasicAuth(app)

    def check_for_objects():
        last_epoch = 0.0
        email_update_interval = 10
        while True:
            try:
                frame, found_obj = video_camera.get_object(object_classifier)
                frames, found_face = video_camera.get_object(face_classifier)
                if found_obj and (time.time() -
                                  last_epoch) > email_update_interval:
                    last_epoch = time.time()
                    print("Sending email...")
                    sendEmail(frame)
                    print("done!")
                    return
                elif found_face and (time.time() -
                                     last_epoch) > email_update_interval:
                    last_epoch = time.time()
                    print("Sending email...")
                    sendEmail(frames)
                    print("done!")
                    return
            except:
                print(("Error sending email: "), sys.exc_info()[0])

    @app.route('/')
    @basic_auth.required
    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(video_camera),
                        mimetype='multipart/x-mixed-replace; boundary=frame')

    if __name__ == '__main__':
        t = threading.Thread(target=check_for_objects, args=())
        t.daemon = True
        t.start()
        app.run(host='0.0.0.0', debug=False, threaded=False)
Exemplo n.º 9
0
import cv2  #video processing
import sys
import time
import threading
import os
from mail import sendEmail  #To send email updates
from flask import Flask, render_template, Response, request  #Flask webserver
from camera import VideoCamera  #Import camera
from flask_basicauth import BasicAuth  #Basic web authentication
from gevent.pywsgi import WSGIServer  #Wsgi server

#Cameras are initialised as NTSC, must be changed to PAL standard
os.system("v4l2-ctl -d /dev/video0 --set-standard 5")
os.system("v4l2-ctl -d /dev/video1 --set-standard 5")
video_camera = VideoCamera(instance=0)  #Initialises camera 1
video_camera2 = VideoCamera(instance=1)  #Initilises camera 2
#To add cameras, create more of the above statements, replace the X with the number of the next camera: 'dev/videoX' and 'instance = X' => dev/video2' and 'instance = 2' and so on

app = Flask(__name__)
app.config[
    'BASIC_AUTH_USERNAME'] = '******'  #Reccommend to customise before deployment
app.config['BASIC_AUTH_PASSWORD'] = '******'

basic_auth = BasicAuth(app)  #initialises basicAuth
emailTimer = 1800  #Every 1800 seconds / 30 Minutes
timer = 0


@app.route('/')
@basic_auth.required  #Requires authentication on this page
def index():
Exemplo n.º 10
0
def video_feed():
    info = None
    face = None
    return Response(gen(VideoCamera(), info, face),
                    mimetype='multipart/x-mixed-replace; boundary=frame')
Exemplo n.º 11
0
def video_feed():
	if not session.get('logged_in'):
		return redirect(url_for('home'))
	else:
		return Response(gen(VideoCamera()),
			mimetype='multipart/x-mixed-replace; boundary=frame')
def video_feed_2():
    return Response(gen(
        VideoCamera("rtsp://*****:*****@192.168.0.210:554/1/1")),
                    mimetype='multipart/x-mixed-replace; boundary=frame')
Exemplo n.º 13
0
import cv2
from camera import VideoCamera
import datetime
import argparse
import time

# creates a camera object, don't flip vertically
video_camera = VideoCamera(
	flip = False, 
	usePiCamera = False, 
	resolution = (640, 480),
	record = False,
	record_timestamp = False,
	record_duration = "00:05:00" # "HH:MM:SS"
	) 

def save_image(frame, current_frame):
	filename = current_frame.strftime("%Y-%m-%d_%H:%M:%S") + "_capture.png"
	cv2.imwrite(filename, frame)


def timelapse(delay, duration = 1000, show_feed = True):
	init_time = datetime.datetime.now()
	finish_time = init_time + datetime.timedelta(seconds=duration)
	# current gets assigned to init_frame
	previous_frame = current_frame = init_time
	while(current_frame < finish_time):
		# take the time again
		current_frame = datetime.datetime.now() 
		elapsed_time = (current_frame - previous_frame).total_seconds()
		if(elapsed_time < delay):
Exemplo n.º 14
0
 def __init__(self, q):
     self.status = False
     self.V = VideoCamera(Q=q)
     self.p = None
     self.q = q
     self.rec = False
Exemplo n.º 15
0
def shot_feed():
    return Response(image(VideoCamera()), mimetype='image/jpeg')
Exemplo n.º 16
0
from mail import sendEmail
from flask import Flask, render_template, Response
from camera import VideoCamera
from flask_basicauth import BasicAuth
import time
import threading
import RPi.GPIO as GPIO
import time
import datetime
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage

email_update_interval = 10  #Interval de temps d'envoie d'un mail
video_camera = VideoCamera(
    flip=True)  #Crée un objet caméra, retournez verticalement
object_classifier = cv2.CascadeClassifier(
    "models/facial_recognition_model.xml"
)  #OpenCV Classifier (reconnaissance facial)

#App Global à ne pas éditer
app = Flask(__name__)  #Appelle la dernière "fonction" pour lancer le serveur
app.config['BASIC_AUTH_USERNAME'] = '******'  #Username pour accéder au site
app.config['BASIC_AUTH_PASSWORD'] = '******'  #MDP pour accéder au site
app.config['BASIC_AUTH_FORCE'] = True

basic_auth = BasicAuth(app)
last_epoch = 0  #Initialisation du dernier temps de détection de mouvement

SENSOR_PIN = 7  #Numéro du Pin du GPIO de la Raspberry Pi pour le HC-SR501
Exemplo n.º 17
0
def video_feed_sketch():
    return Response(gen(VideoCamera(), is_sketch=True),
                    mimetype='multipart/x-mixed-replace; boundary=frame')
Exemplo n.º 18
0
def cam_on():
    obj = VideoCamera()

    return render_template('cam_on.html')
Exemplo n.º 19
0
def video_feed():
    global video_camera
    video_camera = VideoCamera()
    return Response(gen(video_camera),
                    mimetype='multipart/x-mixed-replace; boundary=frame')
def video_feed():
    """ A route that returns a streamed response needs to return a Response object
    that is initialized with the generator function."""

    return Response(gen(VideoCamera()),
                    mimetype='multipart/x-mixed-replace; boundary=frame')
def index():
    obj = VideoCamera()

    return render_template('index.html')
Exemplo n.º 22
0
from models.train import Traindata
from models.register import Register
import cv2
from random import choice
import time
from flask_bootstrap import Bootstrap
import os
import shutil
from PIL import Image
from autocrop import Cropper
from random import randint
from numpy import load
from werkzeug.utils import secure_filename

register_route = Blueprint('register_route', __name__)
setdatacamera = VideoCamera()
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])
webcam_id = 1


def allowed_file(filename):
    return '.' in filename and filename.rsplit(
        '.', 1)[1].lower() in ALLOWED_EXTENSIONS


def gen(camera):
    camera.video = cv2.VideoCapture(webcam_id)
    while True:
        check_face, frame = camera.get_frame()
        if check_face:
            camera.i = camera.i + 1
Exemplo n.º 23
0
import socket
import _thread
import numpy as np
import cv2
import multiprocessing as mp
import threading as td
from camera import VideoCamera
from PIL import Image

CAMERA = VideoCamera()
SHAPE = (480, 640, 3)
POINTS = 2.9


def get_points(q):
    if(q >= 100):
        return 100
    elif(q <= 1):
        return 1
    return q


def frame_transform2bytes(frame, quality):
    ret, jpeg = cv2.imencode(
        '.jpg', frame, [cv2.IMWRITE_JPEG_QUALITY, quality])
    return jpeg.tobytes()

def motion_detector(current_frame, last_frame, last_intense):
    diff_frame = current_frame - last_frame
    intense_per_pix = (diff_frame/255.)**2
    intense = (np.mean(intense_per_pix))
Exemplo n.º 24
0
from flask import Flask, render_template, Response, jsonify
from camera import VideoCamera
import cv2

app = Flask(__name__)
video_stream = VideoCamera()


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


def gen(camera):
    # camera =VideoCamera()
    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(video_stream),
                    mimetype='multipart/x-mixed-replace; boundary=frame')


if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=False, port="5000")
Exemplo n.º 25
0
from flask import Flask, render_template, request, Response
from cv2 import cv2
import numpy as np
import RPi.GPIO as GPIO
import acts
import math
import time
from camera import VideoCamera

video_camera = VideoCamera()

app = Flask(__name__)


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


def gen():
    while True:
        #         time_start = time.time()
        frame = video_camera.get_object()
        #         time_finish = time.time()
        #         fps = 1/(time_finish - time_start)
        #         print("Time Start: {}\nTime Finish:{}".format(time_start,time_finish) +"\nFPS:" +  str(round(fps,2)))
        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')


def man_frame():
Exemplo n.º 26
0
def video_feed():
    video_feed = VideoCamera(LOCAL_HOST, LOCAL_PORT)
    return Response(gen(video_feed),
                    mimetype='multipart/x-mixed-replace; boundary=frame')
Exemplo n.º 27
0
Arquivo: app.py Projeto: rohits2/webrc
    from robot import Robot
else:
    from fake_robot import Robot
from asyncio import sleep
from loguru import logger
import cv2

app = Sanic(__name__)
app.config['COMPRESS_MIMETYPES'] = {'text/html', 'application/json', 'image/jpeg'}
app.config['COMPRESS_LEVEL'] = 9
Compress(app)
app.enable_websocket()

PORT = 5000

cam = VideoCamera()

robot = Robot()

app.static('/index.js', './src/index.js')

with open("res/index.htm", "r") as f:
    index_template = Template(f.read())


@app.route('/')
async def index(request):
    return response.html(index_template.render())


async def frame_generator(resp):
Exemplo n.º 28
0
import RPi.GPIO as GPIO
import time
from time import sleep
import cv2
import sys
from mail import sendEmail
from flask import Flask, render_template, Response
from camera import VideoCamera
from flask_basicauth import BasicAuth
import threading

email_update_interval = 30  #interval in seconds for time between email notifications
video_camera = VideoCamera(
)  # creates a camera object. Calls function from Picam
#model template loaded in object classifier. I am using haarcascade face model. Other models in the CaarHascade folder
object_classifier = cv2.CascadeClassifier(
    "/home/pi/Documents/ASPR/HaarCascade/haarcascade_profileface.xml")

#initiate flask and authentication
app = Flask(__name__)
app.config['BASIC_AUTH_USERNAME'] = '******'
app.config['BASIC_AUTH_PASSWORD'] = '******'
app.config['BASIC_AUTH_FORCE'] = True

basic_auth = BasicAuth(app)
#timeStart starts at zero but lately given time as variable
timeStart = 0


def check_for_people():
    global timeStart
Exemplo n.º 29
0
import cv2
import sys
#from mail import sendEmail
from flask import Flask, render_template, Response
from camera import VideoCamera
from flask_basicauth import BasicAuth
import time
import threading

#email_update_interval = 600 # sends an email only once in this time interval
video_camera = VideoCamera(
    flip=True)  # creates a camera object, flip vertically
object_classifier = cv2.CascadeClassifier(
    "models/facial_recognition_model.xml")  # an opencv classifier

# App Globals (do not edit)
app = Flask(__name__)
app.config['BASIC_AUTH_USERNAME'] = '******'
app.config['BASIC_AUTH_PASSWORD'] = '******'
app.config['BASIC_AUTH_FORCE'] = True

basic_auth = BasicAuth(app)
last_epoch = 0
kind_front = 1
cap = cv2.VideoCapture(0)


def check_for_objects():
    #global last_epoch
    while True:
        #frame, found_obj = video_camera.get_object(object_classifier)
Exemplo n.º 30
0
def video_feed():
    videoId = request.args.get("videoId")
    fileName = "/home/icarus/projects/AgeGender/videos/" + "8427.mp4" #str(videoId)
    return Response(gen(VideoCamera(fileName)),
                    mimetype='multipart/x-mixed-replace; boundary=frame')