94 lines
3.0 KiB
Python
94 lines
3.0 KiB
Python
import cv2
|
|
import numpy as np
|
|
from flask import Flask, Response, request
|
|
import json
|
|
import time
|
|
import sys
|
|
import os
|
|
|
|
|
|
max_readings = int(sys.argv[1])
|
|
porta = sys.argv[2]
|
|
url = sys.argv[3]
|
|
arquivoSaida = sys.argv[4]
|
|
|
|
app = Flask(__name__)
|
|
|
|
def calculate_angle(reference_line, width):
|
|
[vx, vy, _, _] = cv2.fitLine(reference_line, cv2.DIST_L2, 0, 0.01, 0.01)
|
|
slope_reference = vy / vx
|
|
|
|
vertical_line = np.array([[width // 2, 0], [width // 2, 100]], dtype=np.float32)
|
|
[vx, vy, _, _] = cv2.fitLine(vertical_line, cv2.DIST_L2, 0, 0.01, 0.01)
|
|
slope_vertical = vy / vx
|
|
|
|
angle_radians = np.arctan((slope_reference - slope_vertical) / (1 + slope_reference * slope_vertical))
|
|
angle_degrees = np.degrees(angle_radians)
|
|
|
|
return angle_degrees
|
|
|
|
|
|
def detect_lines(_camera_index):
|
|
cap = cv2.VideoCapture(_camera_index)
|
|
|
|
readings = []
|
|
output_folder = 'Python/Output/'
|
|
|
|
while True:
|
|
ret, frame = cap.read()
|
|
if not ret:
|
|
break
|
|
|
|
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
|
|
|
|
# Defina o limite de intensidade desejado
|
|
_, thresh = cv2.threshold(gray, 50, 255, cv2.THRESH_BINARY) # Ajuste o valor do limite conforme necessário
|
|
|
|
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
|
|
|
if contours:
|
|
reference_line = max(contours, key=cv2.contourArea)
|
|
angle = calculate_angle(reference_line.squeeze(), frame.shape[1])[0]
|
|
|
|
#print(angle)
|
|
|
|
# Adicionando o ângulo atual à lista de dados
|
|
timestamp = time.time()
|
|
readings.append({"timestamp": timestamp, "angle": float(angle)})
|
|
|
|
# Mantendo apenas as últimas 10 leituras
|
|
if len(readings) > max_readings:
|
|
readings.pop(0)
|
|
|
|
# Salvando os dados em formato JSON no arquivo
|
|
if not os.path.exists(output_folder):
|
|
os.makedirs(output_folder)
|
|
|
|
if len(readings) == max_readings:
|
|
try:
|
|
with open(output_folder + arquivoSaida, 'w') as file:
|
|
json.dump({'frames': readings}, file)
|
|
except Exception as e:
|
|
print(f"Erro ao escrever no arquivo: {e}")
|
|
|
|
cv2.drawContours(frame, [reference_line], -1, (0, 255, 0), 2)
|
|
cv2.line(frame, (frame.shape[1] // 2, 0), (frame.shape[1] // 2, 100), (255, 0, 0), 2)
|
|
|
|
cv2.imshow('Video', frame)
|
|
if cv2.waitKey(1) & 0xFF == ord('q'):
|
|
break
|
|
|
|
# Convertendo frame para JPEG e enviando via Flask
|
|
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('/' + url, methods=['GET'])
|
|
def video_feed():
|
|
camera_index = int(request.args.get('camera_index'))
|
|
return Response(detect_lines(camera_index), mimetype='multipart/x-mixed-replace; boundary=frame')
|
|
|
|
if __name__ == "__main__":
|
|
app.run(host='0.0.0.0', port=porta) |