Ask Your Question

Help with moving laser(cv2.line) animation for live webcam

asked 2018-01-16 01:37:21 -0500

masterenol gravatar image

updated 2018-01-16 01:49:42 -0500

Hello everyone,

I'm trying to create an animation in which a drawn laser (cv2.line) shoots across a live webcam. So far I can only get a laser to shoot across the screen once, but I cannot get the laser function to loop so that that lasers shoots across the live webcam for an indefinite amount of loops.

If someone can help me with my dilemma, I would greatly appreciate it.

import numpy as np
import cv2
import time

def laserFire(videoFeed, totLaserPos, timePerPos):
    vRow, vCol, vCH = videoFeed.shape
    laserVerPos = vRow / 2
    laserVerPos = int(laserVerPos)
    laserPosDiv = vCol / totLaserPos
    laserPosDiv = int(laserPosDiv)
    laserPos = [0]
    for i in range(totLaserPos - 1):
        laserPos.append(laserPosDiv * (i + 1))
    laserTime = [0.0] 
    for t in range(totLaserPos - 1):
        laserTime.append(timePerPos * (t + 1))

    #Here is the attempted loop for the laser
    for i in range(totLaserPos):
        for x in range(100):
            if time.clock() >= laserTime[i] + timePerPos:
            elif time.clock() >= laserTime[i]:
                drawLaser = cv2.line(videoFeed, (laserPos[i], laserVerPos), \
                    (laserPos[i] + 40, laserVerPos), (0,0,255), 5)

cap = cv2.VideoCapture(0)

ret, last_frame =

if last_frame is None:

    ret, frame =

    if frame is None:

    laserFire(frame,8,0.2) #Call to laser function
    cv2.imshow('frame', frame)

    if cv2.waitKey(33) >= 0:

    last_frame = frame

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted

answered 2018-01-16 04:33:10 -0500

kbarni gravatar image

Do the loop in the main function (untested code, but easy to understand):

    ret, frame =

    if frame is None:

    cv2.line(frame, (laserHPos, laserVPos), (laserHPos + 40, laserVPos), (0,0,255), 5)

    laserHPos += 10; # update the horizontal position of the laser
    if laserHPos > vCol:
        laserHPos=0; #shoot a new laser...
        laserVPos=numpy.random.randint(vRow); # on a random line

    cv2.imshow('frame', frame)

    if cv2.waitKey(33) >= 0:

    last_frame = frame

The idea is to keep the laser position in a variable, update and reinitialize it when needed.

edit flag offensive delete link more


Thank you so much @kbarni! I got your code to work and sure I can use it to continue my project later today. Awesome!

masterenol gravatar imagemasterenol ( 2018-01-16 15:30:13 -0500 )edit

Question Tools

1 follower


Asked: 2018-01-16 01:37:21 -0500

Seen: 841 times

Last updated: Jan 16 '18