srivatsavdamaraju's picture
Create app.py
79632d8 verified
import cv2
import numpy as np
import base64
from flask import Flask, render_template
from flask_socketio import SocketIO, emit
from io import BytesIO
from PIL import Image
# Initialize Flask app and SocketIO
app = Flask(__name__)
socketio = SocketIO(app)
@app.route('/')
def index():
"""Serve the HTML page."""
return render_template('index2.html')
@socketio.on('video_frame')
def handle_video_frame(data):
"""Receive video frame from client, apply Canny edge detection, and emit the processed frame."""
# Extract the base64 image from the client
frame_data = data['image']
# Decode the base64 image to bytes
img_data = base64.b64decode(frame_data)
# Convert the image data to a numpy array
np_arr = np.frombuffer(img_data, np.uint8)
frame = cv2.imdecode(np_arr, cv2.IMREAD_COLOR)
if frame is not None:
# Apply Canny edge detection
edges = cv2.Canny(frame, 100, 200)
# Convert the edges image to BGR (for compatibility with base64 encoding)
edges_bgr = cv2.cvtColor(edges, cv2.COLOR_GRAY2BGR)
# Convert the processed image (edges) to base64
_, buffer = cv2.imencode('.jpg', edges_bgr)
edges_str = base64.b64encode(buffer).decode('utf-8')
# Emit the processed frame back to the client
emit('display_frame', {'image': edges_str}, broadcast=True)
if __name__ == '__main__':
socketio.run(app, host='0.0.0.0', port=5000)