46 lines
1.4 KiB
Python
46 lines
1.4 KiB
Python
import cv2
|
|
import numpy as np
|
|
|
|
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
|
|
|
|
cap = cv2.VideoCapture(1)
|
|
|
|
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])
|
|
|
|
print(angle)
|
|
|
|
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
|
|
|
|
cap.release()
|
|
cv2.destroyAllWindows()
|