def video_stream(): global video_camera global global_frame # time.sleep(5) # instruction('a', 4, audio=True) # instruction('a', 5, audio=True) if video_camera == None: video_camera = VideoCamera() #video_camera.set(5,0.1) frame = video_camera.get_frame() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') while True: frame = video_camera.get_frame() frame_decoded = cv2.imdecode(np.fromstring(frame, dtype=np.uint8), cv2.IMREAD_COLOR) frame = frame_with_angle(frame_decoded) ret, frame = cv2.imencode('.png', frame) frame = frame.tobytes() if frame != None: global_frame = frame yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') else: yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + global_frame + b'\r\n\r\n')
def main(): meter = HotWaterMeter() meter.background = "digits_threshold" camera = VideoCamera(meter.process_image) while True: camera.get_frame() sys.stdout.flush() time.sleep(1)
class ThearedCam: def __init__(self, q): self.status = False self.V = VideoCamera(Q=q) self.p = None self.q = q self.rec = False def recCam(self, rec): self.rec = rec def getStatus(self): return self.status def getRec(self): return self.rec def hang(self): self.V.Video_Start() while self.status: self.V.get_frame(self.rec) def start(self): print("self.p: " + str(self.p)) if self.p == None: self.p = multiprocessing.Process(target=self.hang) self.status = True self.p.start() print(" --- " + str(self.p.pid)) return True else: return "Start Thread Erro" def close(self): if self.p != None and self.p.is_alive(): self.status = False print(self.p.is_alive()) self.p.terminate() os.kill(self.p.pid, 9) time.sleep(0.5) print(self.p.is_alive()) if not self.p.is_alive(): del self.p self.p = None return True else: return "Close Thread Erro"
def video_stream(car_detector): global video_camera global global_frame #global car_detector if video_camera == None: video_camera = VideoCamera() while True: frame = video_camera.get_frame() car_detector.update_frame(frame) try: output = car_detector.detect_car() except: print "car_detector failed" ret, jpeg = cv2.imencode('.jpg', car_detector.get_frame()) jpeg = jpeg.tobytes() if jpeg != None: global_frame = frame yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + jpeg + b'\r\n\r\n') else: yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + global_frame + b'\r\n\r\n')
def gen(): global camera1 if camera1 == None: print('object created') camera1 = VideoCamera() while True: frame = camera1.get_frame() # yield method is used to return without destroying local variable instances yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')
def video_stream(): global video_camera global global_frame if video_camera == None: video_camera = VideoCamera() while True: frame = video_camera.get_frame() if frame != None: global_frame = frame yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')
def publish(): # request.environはWSGIに従ったリクエスト情報。以下のようなデータを含む # 'wsgi.url_scheme': 'http', # 'SERVER_NAME': 'localhost', # 'PATH_INFO': '/', # 'SERVER_PORT': '5000', # 'REQUEST_METHOD': 'GET' if request.environ.get('wsgi.websocket'): # environ['wsgi.websocket'] から WebSocket オブジェクトが得られる(セッションが取れる) ws = request.environ['wsgi.websocket'] videocamera = VideoCamera() old_jpeg = 0 while True: # 画像取得 jpeg = videocamera.get_frame() if jpeg is None: jpeg = old_jpeg print("video read error") else: old_jpeg = jpeg # 温湿度取得 tempature = random.random() * 100 humidity = random.random() * 100 # 画像を送信可能な形式に変換してJSONに格納 image_data = "data:image/jpeg;base64," + base64.b64encode( jpeg).decode('utf-8') # 時間取得 t = int(time.mktime(datetime.datetime.now().timetuple())) # websocketにはsend、recieveがある。html側で送信していないのでrecive処理はしない # message = ws.receive() # print(message) # json.dumpsでデータをJSON形式にエンコードしてsendで送信。 ws.send( json.dumps([{ "time": t, "y": tempature }, { "time": t, "y": humidity }, { 'image': image_data }])) # time.sleep(1) return
def video_stream(): global video_camera global global_frame global estado_req global cedula global secion print(cedula) connectionObject = sqlite3.connect("templates/database/proyecto_python.db") cursorObject = connectionObject.cursor() contador = 0 if estado_req: video_camera = VideoCamera() while estado_req: frame = video_camera.get_frame() datos = video_camera.datos if (sum(datos) >= 10): normalizados = [float(i) / sum(datos) for i in datos] insertValues = "INSERT INTO DATA values(" + str( contador) + "," + str(cedula) + "," + str(secion) + "," + str( normalizados[0] ) + "," + str(normalizados[1] + normalizados[6]) + "," + str( normalizados[2]) + "," + str(normalizados[3]) + "," + str( normalizados[4]) + "," + str( normalizados[5]) + "," + str(0) + ")" cursorObject.execute(insertValues) connectionObject.commit() print(normalizados) contador = contador + 1 video_camera.datos = [0, 0, 0, 0, 0, 0, 0] if frame != None: global_frame = frame yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') else: yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + global_frame + b'\r\n\r\n') video_camera = None yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + global_frame + b'\r\n\r\n') secion = secion + 1 connectionObject.close()
def video_stream(): global video_camera global global_frame if video_camera == None: video_camera = VideoCamera() while True: frame = video_camera.get_frame(False) if frame != None: global_frame = frame yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') else: #return render_template('login.html') yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + global_frame + b'\r\n\r\n')
def image(data_image): sbuf = io.StringIO() sbuf.write(data_image) # decode and convert into image b = io.BytesIO(base64.b64decode(data_image)) pimg = Image.open(b) ## converting RGB to BGR, as opencv standards frame = cv2.cvtColor(np.array(pimg), cv2.COLOR_RGB2BGR) imgencode = cam.get_frame(frame) # Process the image frame currX = cam.get_currX() currY = cam.get_currY() activeColor = "#000" if (currX == -1 or currY == -1): pos = {"x": "null", "y": "null"} else: pos = {"x": currX, "y": currY} sio.emit('pos', pos)
def video_stream(): global video_camera global global_frame if video_camera is None: video_camera = VideoCamera() while True: frame = video_camera.get_frame() if frame is not None: global_frame = frame yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + bytes(frame) + b'\r\n\r\n') if global_frame is not None: yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + bytes(global_frame) + b'\r\n\r\n')
def record_status(): global video_camera if video_camera == None: video_camera = VideoCamera() json = request.get_json() status = json['status'] #username = json['username'] if status == "true": video_camera.start_record() return jsonify(result="started") elif status =="false": video_camera.stop_record() return jsonify(result="stopped") else: curr_frame = video_camera.get_frame(True, status) return jsonify(result="captured")
def video_stream(): global video_camera global global_frame start_time = time.time() global time_list time_list = list() if video_camera == None: video_camera = VideoCamera(start_time,time_list) video_camera.start_record() while True: frame = video_camera.get_frame() if frame != None: global_frame = frame yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') else: yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + global_frame + b'\r\n\r\n')
def background_thread(): """Example of how to send server generated events to clients.""" count = 0 cam = VideoCamera() while True: sio.sleep(5) img = cam.get_frame() raw_img = cam.get_frame_raw() cv2.imshow("the image", raw_img) ai_image = ai.inputs.create_image_from_bytes(img_bytes=img) resp = model.predict([ai_image]) pprint(resp) count += 1 sio.emit('food_type', { 'food': json.dumps(resp["outputs"][0]["data"]["concepts"], indent=2, sort_keys=True), 'image': base64.b64encode(img) }, broadcast=True)
i = 0 # extracting the json files plate = results['results'][0] candidate = plate['candidates'][0] plate_coordinates = results['results'][0]['coordinates'] alpr.unload() out = im[plate_coordinates[0]['y']:plate_coordinates[2]['y'] + 20, plate_coordinates[0]['x']:plate_coordinates[1]['x'] + 20] return candidate['plate'], candidate['confidence'], out if __name__ == '__main__': while True: frame = video_camera.get_frame() try: cv2.imshow("input", frame) # The input is fed into the detect_car function which is inside the hog_detector try: status = False #status,output_hog,bbox = detect_car(frame) #Hog returns the status , cropped out image , bounding box car_detect.update_frame(frame) car_detect.detect_car() output = car_detect.get_detected_car() cv2.imshow("Hog", output) #print status , bbox if True: plate, confidence, out = read_number_plate(frame)
def index(): camera = VideoCamera() frame = camera.get_frame() return render_template('index2.html')
def gen(VideoCamera): while True: frame = VideoCamera.get_frame() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')
def throw_data(): 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')
hog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector()) # initialize HAAR pretrained haar cascade classifiers faceCascade = cv2.CascadeClassifier('./haarcascade_frontalface_default.xml') genderCascade = cv2.CascadeClassifier("./haarcascade_gender_alt2.xml") # initialize our camera feed cam = VideoCamera() #initialize ad system ads = AdSystem.create_ads_list() # while the video stream is open, get the image frame by frame while cam.video.isOpened(): #Get the image frame image = cam.get_frame() image = imutils.resize(image, width=min(400, image.shape[1])) orig = image.copy() # detect pedestrians in the image (rects, weights) = hog.detectMultiScale(image, winStride=(4, 4), padding=(8, 8), scale=1.05) # apply non-maxima suppression to the bounding boxes using a # fairly large overlap threshold to try to maintain overlapping # boxes that are still people rects = np.array([[x, y, x + w, y + h] for (x, y, w, h) in rects]) pick = non_max_suppression(rects, probs=None, overlapThresh=0.65)
# Author : Watchara Pongsri # [github/X-c0d3] https://github.com/X-c0d3/ # Web Site: https://wwww.rockdevper.com from cv2 import cv2 import sys import time from configparser import ConfigParser from datetime import datetime from lineNotify import sendNotify from camera import VideoCamera if __name__ == '__main__': streamer = VideoCamera() last_epoch = 0 while True: frame, found_obj = streamer.get_frame() # Display the resulting frame if (found_obj and time.time() - last_epoch) > 600: last_epoch = time.time() ret, jpeg = cv2.imencode('.jpg', frame) sendNotify( "Detecting \n Found Object !! \n Please recheck your IP camera \n Time:" + datetime.now().strftime("%H:%M:%S"), jpeg) if frame is not None: cv2.imshow("Home Security - IP Camera", frame) if cv2.waitKey(1) & 0xFF == ord('q'): break
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 queue import threading Q = queue.Queue() app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') def gen(): while True: yield Q.get() @app.route('/video_feed') def video_feed(): return Response(gen(), mimetype='multipart/x-mixed-replace; boundary=frame') if __name__ == '__main__': def run_app(): app.run(host='0.0.0.0', debug=False, threaded=False) x = threading.Thread(target=run_app) x.start() v = VideoCamera() while True: frame = v.get_frame() Q.put(b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')
from camera import VideoCamera from car_controll import controll_car from lane_detection import lanedetect_steer from object_detection import object_detection camera = VideoCamera(flip=False) car = controll_car.Car() # object_thread = threading.Thread(target=object_detection.detect_raspberry_cam_delay, args=(1,)) while True: frame = camera.get_frame() try: # if not object_thread.is_alive(): # object_thread = threading.Thread(target=object_detection.detect_raspberry_cam_delay, args=(frame,)) # object_thread.start() # Get steering input instruction from lanedetect_steer frame2, canny, steering=lanedetect_steer.lane_detection(frame,"outdoor") # frame2, canny, steering=lanedetect_steer.lane_detection(frame,"indoor") # Give the steering instruction from lanedetect_steer to the Car-instance car.steer(steering) except Exception as e: print(e) print("steeringerror")
from clarifai import rest from clarifai.rest import ClarifaiApp from clarifai.rest import Image as ClImage import json import cv2 from camera import VideoCamera def pprint(x): print(json.dumps(x, indent = 2, sort_keys = True)) cam = VideoCamera() img = None while True: jpeg, img = cam.get_frame() cv2.imshow("my webcam", img) ch = cv2.waitKey(1) '''if ch == 27: break if ch == 32: print("taken") cv2.imwrite("thepic.jpg", img) break''' del(cam) cv2.destroyAllWindows() app = ClarifaiApp(api_key = "d556e0ea9bd741d98e6fe8f4812f1b44") model = app.models.get('bd367be194cf45149e75f01d59f77ba7') # image = ClImage(file_obj=open('pizza.jpg', 'rb')) img_str = cv2.imencode('.jpg', img)[1].tostring()
def screen(feedNum): img = VideoCamera(feedNum) toto = b'--frame\r\n'b'Content-Type: image/jpeg\r\n\r\n' + img.get_frame() + b'\r\n\r\n' return Response(toto, mimetype='multipart/x-mixed-replace; boundary=frame')
def stream(): response.content_type = 'multipart/x-mixed-replace; boundary=frame' v = VideoCamera() while True: r = yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + v.get_frame() + b'\r\n\r\n')