To set up a Python-based web server that allows any PC on the network to collect images from three webcams using OpenCV and Flask, follow these steps:
-
First, make sure you have Python and pip (Python package manager) installed on your PC.
-
Install the required packages:
pip install opencv-python opencv-python-headless flask
- Create a new Python file (e.g.,
webcam_server.py) and paste the following code:
import cv2
from flask import Flask, render_template, Response
app = Flask(__name__)
# Set up the webcams
webcam1 = cv2.VideoCapture(0)
webcam2 = cv2.VideoCapture(1)
webcam3 = cv2.VideoCapture(2)
def get_frame(webcam):
success, frame = webcam.read()
if not success:
return None
ret, jpeg = cv2.imencode('.jpg', frame)
return jpeg.tobytes()
def gen(webcam):
while True:
frame = get_frame(webcam)
if frame:
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')
@app.route('/')
def index():
return render_template('index.html')
@app.route('/webcam1')
def webcam1_feed():
return Response(gen(webcam1), mimetype='multipart/x-mixed-replace; boundary=frame')
@app.route('/webcam2')
def webcam2_feed():
return Response(gen(webcam2), mimetype='multipart/x-mixed-replace; boundary=frame')
@app.route('/webcam3')
def webcam3_feed():
return Response(gen(webcam3), mimetype='multipart/x-mixed-replace; boundary=frame')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=True, threaded=True)
- Create a new HTML file (e.g.,
templates/index.html) and paste the following code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Webcam Server</title>
</head>
<body>
<h1>Webcam Server</h1>
<img src="{{ url_for('webcam1_feed') }}" alt="Webcam 1">
<img src="{{ url_for('webcam2_feed') }}" alt="Webcam 2">
<img src="{{ url_for('webcam3_feed') }}" alt="Webcam 3">
</body>
</html>
- Run the Python script:
python webcam_server.py
- Now you can access the webcam server on any PC within the network by visiting:
http://<your_server_ip_address>:5000/
Make sure to replace <your_server_ip_address> with the IP address of the PC running the Python script.