Ask Your Question
0

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

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

masterenol gravatar image

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

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:
                break
            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 = cap.read()

if last_frame is None:
    exit()

while(cap.isOpened()):
    ret, frame = cap.read()

    if frame is None:
        exit()

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

    if cv2.waitKey(33) >= 0:
        break

    last_frame = frame

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

1 answer

Sort by ยป oldest newest most voted
2

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

kbarni gravatar image

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

laserHPos=0;
laserVPos=100;
while(cap.isOpened()):
    ret, frame = cap.read()

    if frame is None:
        exit()

    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:
        break

    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

Comments

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 -0600 )edit

Question Tools

1 follower

Stats

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

Seen: 1,311 times

Last updated: Jan 16 '18