huggin face code
huggin face code
------
import os
import cv2
import numpy as np
import requests
from flask import Flask, render_template, Response, request, jsonify
from datetime import datetime
app = Flask(__name__)
# Global variables
object_count = 0
detection_enabled = True
detection_logs = []
current_frame = None # To store the last processed frame
def detect_objects(frame):
global object_count, detection_logs
height, width, channels = frame.shape
# Reduce frame size for better performance
blob = cv2.dnn.blobFromImage(frame, 0.00392, (320, 320), (0, 0, 0), True,
crop=False)
net.setInput(blob)
outs = net.forward(output_layers)
class_ids = []
confidences = []
boxes = []
object_count = 0
if len(indexes) > 0:
for i in indexes.flatten():
x, y, w, h = boxes[i]
label = str(classes[class_ids[i]])
# Add to logs with timestamp
detection_logs.append(f"{label} detected at
{datetime.now().strftime('%H:%M:%S')}")
detection_logs = detection_logs[-10:] # Keep the last 10 logs
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.putText(frame, label, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,
255, 0), 2)
return frame
def gen_frames():
global current_frame
cap = cv2.VideoCapture(0)
while True:
success, frame = cap.read()
if not success:
print("Failed to capture frame")
break
else:
current_frame = frame # Store the current frame for capturing
if detection_enabled:
frame = detect_objects(frame)
ret, buffer = cv2.imencode('.jpg', frame)
frame = buffer.tobytes()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
@app.route('/')
def index():
return render_template('index.html')
@app.route('/detection')
def detection():
return render_template('detection.html')
@app.route('/video_feed')
def video_feed():
return Response(gen_frames(), mimetype='multipart/x-mixed-replace;
boundary=frame')
@app.route('/object_count')
def object_count_route():
global object_count
return jsonify({'count': object_count})
@app.route('/detection_logs')
def detection_logs_route():
return jsonify({'logs': detection_logs})
@app.route('/toggle_detection')
def toggle_detection():
global detection_enabled
detection_enabled = request.args.get('enable', 'true').lower() == 'true'
return '', 204 # Empty response
@app.route('/capture_frame')
def capture_frame():
global current_frame
if current_frame is not None:
filename = f'static/captured_frame_{datetime.now().strftime("%Y%m%d_%H%M
%S")}.jpg'
cv2.imwrite(filename, current_frame) # Save the frame to disk
return f"Frame captured and saved as {filename}"
return "No frame to capture"
if __name__ == '__main__':
app.run(debug=True)