0% found this document useful (0 votes)
2 views

huggin face code

This document contains a Python code for a Flask application that implements YOLOv3 object detection using OpenCV. It includes functionalities to download YOLOv3 weights, detect objects in video frames, and serve a web interface for real-time video feed and object counting. The application also allows toggling detection and capturing frames from the video stream.

Uploaded by

prakharsachan110
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

huggin face code

This document contains a Python code for a Flask application that implements YOLOv3 object detection using OpenCV. It includes functionalities to download YOLOv3 weights, detect objects in video frames, and serve a web interface for real-time video feed and object counting. The application also allows toggling detection and capturing frames from the video stream.

Uploaded by

prakharsachan110
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 3

yolo 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__)

# Hugging Face YOLOv3 weights URL


yolov3_weights_url =
'https://huggingface.co/prakhar5342/yolov3-model/resolve/main/yolov3.weights'

# Function to download the model if it's not present locally


def download_model():
weights_path = 'model/yolov3.weights'
if not os.path.exists(weights_path):
print("Downloading YOLOv3 weights from Hugging Face...")
response = requests.get(yolov3_weights_url, stream=True)
with open(weights_path, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
f.write(chunk)
print("Download complete.")
else:
print("YOLOv3 weights already present.")

# Call the download_model function to ensure weights are present


download_model()

# Load YOLO model


net = cv2.dnn.readNet('model/yolov3.weights', 'model/yolov3.cfg')
layer_names = net.getLayerNames()
output_layers = [layer_names[i - 1] for i in
net.getUnconnectedOutLayers().flatten()]

with open('model/coco.names', 'r') as f:


classes = [line.strip() for line in f.readlines()]

# 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

for out in outs:


for detection in out:
scores = detection[5:]
class_id = np.argmax(scores)
confidence = scores[class_id]
if confidence > 0.4: # Lower confidence threshold to detect smaller
objects like earphones
object_count += 1
center_x = int(detection[0] * width)
center_y = int(detection[1] * height)
w = int(detection[2] * width)
h = int(detection[3] * height)
x = int(center_x - w / 2)
y = int(center_y - h / 2)
boxes.append([x, y, w, h])
confidences.append(float(confidence))
class_ids.append(class_id)

indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)

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)

You might also like