How to measure the time an object is in an area

asked 2017-10-18 08:46:01 -0500

TalsaD gravatar image

Hi, I have a program that detects a ball with color detection. I would like to measure the speed of my object and to do that I have created a zone with 2 lines. I would like to know the time the ball is in this zone but I don't know how. I tried with the module time but it seems complicated to incorporate it in a loop while. Sorry for my English, I'm a French student.

import cv2
import numpy as np
import time

debut = 0
cap = cv2.VideoCapture(0)

while True:

retour, image = cap.read()
k = cv2.waitKey(5) & 0xFF
if k == 27:
    break

hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) # Conversion BGR à HSV

couleur_basse = np.array([20,100,100]) # Choix de la plage de couleur la plus basse
couleur_haute = np.array([30,255,255]) # Choix de la plage de couleur la plus haute

masque = cv2.inRange(hsv, couleur_basse, couleur_haute) # On crée un masque qui ne garde que la plage de couleur choisie
masque = cv2.erode(masque, None, iterations=2) # Facultatif mais plus précis
masque = cv2.dilate(masque, None, iterations=2) # Facultatif mais plus précis

moments = cv2.moments(masque) # On crée un dictionnaire qui recensent les positions
centre_x, centre_y = None, None # On crée les coordonnées du centre

if moments['m00'] != 0: # Permet de ne pas diviser par 0
    centre_x = int(moments['m10']/moments['m00'])
    centre_y = int(moments['m01']/moments['m00'])

if centre_x != None and centre_y != None: # Si les coordonnées existent, on les associe au centre 
    centre = (centre_x, centre_y)

    cv2.circle(image, centre, 25, (0,0,0)) # On crée un marqueur qui suit la balle

cv2.line(image,(10,0),(10,1000),(0,0,255),5)
cv2.line(image,(100,0),(100,1000),(0,0,255),5)

if centre_x != None :
    if centre_x >= 10 and centre_x <= 100:
        debut = time.clock()



cv2.imshow('image',image) # Affichage de la vidéo originale
cv2.imshow('masque',masque) # Affichage de la vidéo avec le masque


cap.release()
cv2.destroyAllWindows()
edit retag flag offensive close merge delete