I have the next problems with my code: my backend code doesn’t initiate when i try to compile it and make it send coordinates to my html page of a web server that i created in javascript on Visual Studio code.
First, i created a code with python to open the camera of my laptop and calculate the area of each square (or rectangles) that the camera could recognize. Then I created a web server with express and Socket.io. For this I created a directory on my computer to make this, and in a folder named public and another named nodejs_web_server.
Now, i will share the codes here. THE FIRST CODE IS:
import cv2
import numpy as np
import requests from socketIO_client import SocketIO, BaseNamespace
import json
IP_SERVER = 'localhost' # servers ip SERVER_URL = 'http://localhost:3000' # URL of Express server
print("Starting...") socketIO = SocketIO(IP_SERVER, 3000) try: socketIO = SocketIO(IP_SERVER, 3000) print("Connected to server") except Exception as e: print(f"Error by trying to connect to server: {e}")
cap = cv2.VideoCapture(0)
frame = cv2.imread('your_image.jpg') # Replace 'your_imagen.jpg' with the path of your image
while True: ret, frame = cap.read()
print(f"Readed frame: {ret}")
if not ret:
break
# Convert the image to a gray scale
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Apply a gaussian filter to reduce the noise
gray = cv2.GaussianBlur(gray, (5, 5), 0)
# detect the borders of the image
edges = cv2.Canny(gray, 50, 150)
# detect the contours of the image
contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# minimum area to recognize squares
minimum_area = 1000
for contour in contours:
perimeter = cv2.arcLength(contour, True)
approx = cv2.approxPolyDP(contour, 0.04 * perimeter, True)
if len(approx) == 4 and cv2.contourArea(contour) > minimum_area:
# Find the centre of the square
M = cv2.moments(contour)
if M["m00"] != 0:
cx = int(M["m10"] / M["m00"])
cy = int(M["m01"] / M["m00"])
coordenadas = {'x': cx, 'y': cy}
response = requests.post(f'{SERVER_URL}/coordenadas', json=coordenadas)
print(response.status_code, response.text)
# Send the values to server with the id "coordenadas"
coordenadas_json = json.dumps({'x': cx, 'y': cy})
socketIO.emit('coordenadas', coordenadas_json)
# invert the image horizontally
frame = cv2.flip(frame, 1)
# show the image in real time
cv2.imshow('Detection of squares', frame)
# stop the loop when 'q' is pressed
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# wait 500ms
if cv2.waitKey(500) & 0xFF == ord('q'):
break
#close the camara and the window
cap.release() cv2.destroyAllWindows()`
Then i have this one named “app.js”:
var express = require('express');
var app = express();
var server = require('http').Server(app);
const io = require('socket.io')(server);
app.use(express.static('public'));
ArduinoSocketID = null;
io.on('connection', function(socket){
socket.on('coordenadas',(mensaje)=>{
console.log('mensaje del cliente', mensaje);
io.sockets.emit('coordenadas',mensaje);
//console.log(ArduinoSocketID);
});
});
server.listen(3000, function(){
console.log("Servidor corriendo en el puerto 3000")
});
Then this one “main.js”:
var socket = io.connect('http://localhost:3000', {'forceNew': true});
socket.on('coordenadas', (mensaje) => { console.log('coordenadas recibidas', mensaje);
var data = JSON.parse(mensaje);
console.log('COOR X:', data.x);
console.log('COOR Y:', data.y);
document.getElementById("19212438").innerHTML = "X=" + data.x + ", Y=" + data.y;
});`
Now, the number “19212438” its my ID in the list of my classmates that appears on my html page, in which one i want to trasmit the values of x and y in real time. (Each class members appears on my html code and each of them has its own ID. “19212438” its mine and i have to transmitt the x and y values generated on my backend code of python in the html page on real time).
Thanks for your support.
I have asked ChatGPT to solve it but it only generates even more and more errors during the compilation. I dont have experince in coding. Its my final project of my class in school. Hope someone could help me.
If you want to send me questions about my project, this is my email direction: [email protected]