Speed detection by frames

Hi, I want to write program which detect the object and speed. I have problem with speed detection, values are weird :confused: 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()

do us a favour, and paste your code here, not on some external bin, thank you.

Im sorry, I added code here now

1 Like

that code needs two cameras.

I hope you don’t expect anyone to be able to run this.

make it as easy as possible to help you. that means: don’t expect anyone to run this code. show what’s going on.

that’s all you said about this. can’t work with that.

don’t wait for someone to pull your teeth before you start talking. this isn’t gitmo, this is a website. I only use pliers in person.

best to spare the words and use pictures and other numbers instead.

please explain the(assumed !) relation between your qt-app’s screensize/dpi and measurement in the real world

please also read this and this

Program detect and tracking the object, shows object center position and calculates avarage speed by frames, I mean distance is counted beetween previous frame and next frame and then is divisible by time (previous frame and next frame). And I also tried convert pixel to meter. It looks like that:

I read about calibration and pinhole camera. I have program to calibration camera, but I dont know how to load these parameters to my algorythm

I converted pixels to millimeter from position of object center. I meaused camera image width, I divided it into resolution and then I multiplied by the coordinates of the center.
I don`t know why I used dpi to convert, but yes, its don’t have relation I guess

mm_to_pix = 300.0/640

cx_mm = cx*mm_to_pix
cy_mm = cy*mm_to_pix

Now I have to solve problem with speed