Hi, I want to write program which detect the object and speed. I have problem with speed detection, values are weird Maybe someone wrote a similar program somewhen and can help me?
Python code program:
import dataclasses as dc
import math
import sys
import time
import numpy as np
import cv2
from PyQt5.QtWidgets import QApplication
@dc.dataclass(unsafe_hash=True)
class Coordinates:
x: float
y: float
def nothing(x):
pass
#blueLower = (38, 86, 0)
cap = cv2.VideoCapture(2, cv2.CAP_DSHOW)
initial_time = time.time()
cv2.namedWindow("Tracking")
cv2.createTrackbar("LH", "Tracking", 0,360, nothing)
cv2.createTrackbar("LS", "Tracking", 0,255, nothing)
cv2.createTrackbar("LV", "Tracking", 0,255, nothing)
cv2.createTrackbar("UH", "Tracking", 255,255, nothing)
cv2.createTrackbar("US", "Tracking", 255,255, nothing)
cv2.createTrackbar("UV", "Tracking", 255,255, nothing)
object_detector = cv2.createBackgroundSubtractorMOG2(history=50, varThreshold=10)
app = QApplication(sys.argv)
screen = app.screens()[0]
dpi = screen.physicalDotsPerInch()
fps = round(cap.get(cv2.CAP_PROP_FPS))
coordinates = []
def convert_pixel_to_meter(pixels):
return (pixels * 0.0254) / dpi
def convert_pixel_to_mm(pixels):
return (pixels * 25.4) / dpi
def calculate_distance_between_point(x1, y1, x2, y2):
return abs(math.sqrt(pow((x2 - x1), 2) + pow((y2 - y1), 2)))
while True:
ret, frame = cap.read()
height, width, _ = frame.shape
roi = frame
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
l_h = cv2.getTrackbarPos("LH", "Tracking")
l_s = cv2.getTrackbarPos("LH", "Tracking")
l_v = cv2.getTrackbarPos("LH", "Tracking")
u_h = cv2.getTrackbarPos("UH", "Tracking")
u_s = cv2.getTrackbarPos("UH", "Tracking")
u_v = cv2.getTrackbarPos("UH", "Tracking")
blueLower = np.array([l_h, l_s, l_v])
blueUpper = np.array([u_h, u_s, u_v])
mask = cv2.inRange(hsv, blueLower, blueUpper)
res = cv2.bitwise_and(frame, frame, mask=mask)
contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
x, y, w, h = cv2.boundingRect(cnt)
if w >50 and h > 50:
cx = int((x+x+w)/2)
cy = int((y+y+h)/2)
cv2.rectangle(roi, (x, y), (x+w, y+h), (0, 255, 0), 3)
cv2.circle(roi, (cx, cy), 5, (0, 0, 255), -1)
text = "cx: " + str(cx) + ", cy: " + str(cy)
cv2.putText(roi, text, (cx - 10, cy- 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,255, 0), 2)
print("Position: ", convert_pixel_to_mm(cx), convert_pixel_to_mm(cy))
coordinates.append(Coordinates(convert_pixel_to_meter(x), convert_pixel_to_meter(y)))
if len(coordinates) > 1:
pixel_dimension = calculate_distance_between_point(coordinates[len(coordinates)-1].x,
coordinates[len(coordinates)-1].y, x, y)
distance_in_meter = convert_pixel_to_meter(pixel_dimension)
speed = distance_in_meter / (time.time() - initial_time)
print("AverageSpeed: ", speed)
cv2.imshow("roi", roi)
#cv2.imshow("Frame", frame)
cv2.imshow("Mask", mask)
cv2.imshow("res", res)
key = cv2.waitKey(30)
if key == 27:
break
cap.release()
cv2.destroyAllWindows()