amitkumar299 commited on
Commit
d05562c
·
verified ·
1 Parent(s): d7115fc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +32 -42
app.py CHANGED
@@ -1,42 +1,32 @@
1
- from flask import Flask, render_template, Response
2
- import cv2
3
- from ultralytics import YOLO
4
-
5
- app = Flask(__name__)
6
-
7
- # Load YOLOv8 model
8
- model = YOLO("yolov8n.pt") # Make sure this file is present
9
-
10
- # Start webcam
11
- cap = cv2.VideoCapture(0)
12
-
13
- def generate_frames():
14
- while True:
15
- success, frame = cap.read()
16
- if not success:
17
- break
18
-
19
- # Object detection
20
- results = model.predict(frame, conf=0.5)
21
- annotated_frame = results[0].plot()
22
-
23
- # Encode frame to JPEG
24
- ret, buffer = cv2.imencode('.jpg', annotated_frame)
25
- frame = buffer.tobytes()
26
-
27
- # Stream frame
28
- yield (b'--frame\r\n'
29
- b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
30
-
31
- # Main route with updated project name
32
- @app.route('/')
33
- def index():
34
- project_name = "✨ Real Time Object Detection"
35
- return render_template("index.html", project_name=project_name)
36
-
37
- @app.route('/video_feed')
38
- def video_feed():
39
- return Response(generate_frames(), mimetype='multipart/x-mixed-replace; boundary=frame')
40
-
41
- if __name__ == '__main__':
42
- app.run(debug=False)
 
1
+ from flask import Flask, render_template, request, jsonify
2
+ import cv2
3
+ import numpy as np
4
+ from ultralytics import YOLO
5
+ import base64
6
+
7
+ app = Flask(__name__)
8
+ model = YOLO("yolov8n.pt")
9
+
10
+ def readb64(base64_string):
11
+ nparr = np.frombuffer(base64.b64decode(base64_string.split(',')[1]), np.uint8)
12
+ return cv2.imdecode(nparr, cv2.IMREAD_COLOR)
13
+
14
+ @app.route('/')
15
+ def index():
16
+ return render_template('index.html')
17
+
18
+ @app.route('/detect', methods=['POST'])
19
+ def detect():
20
+ data = request.get_json()
21
+ frame_data = data['image']
22
+
23
+ frame = readb64(frame_data)
24
+ results = model.predict(frame, conf=0.5)
25
+ annotated = results[0].plot()
26
+
27
+ _, buffer = cv2.imencode('.jpg', annotated)
28
+ annotated_b64 = base64.b64encode(buffer).decode('utf-8')
29
+ return jsonify({'image': f'data:image/jpeg;base64,{annotated_b64}'})
30
+
31
+ if __name__ == '__main__':
32
+ app.run(host='0.0.0.0', port=7860)