2
\$\begingroup\$

Here's my code - I've a lot to learn so any advice, tips etc would be welcome! A few notes: I'm using OpenCV and numpy for other features in this code, not just for this snippet. The main readon for making frameDelay a class was as a way of passing another variable into the on_press function The weird infinite while loop in the delay function was so I could have a delay which could change length whilst in the actual delay.

While (((time.time() - starttime)*1000) < self.wait):

The above code didn't work as I wished. In the case of a long wait time, it would take that long before the delay length could be changed. I expect there is a better way!

As I said, here's the code! Thanks for looking.

import cv2
from pynput import mouse
import time
import numpy as np

class frameDelay:

    def __init__(self):
        #set up initial values
        self.lasttime=time.time() #time since last click
        self.times=[0,0] #list of last two click intervals
        self.wait=30000 #initial frame delay

    def on_press(self,x, y, button, pressed):

        if pressed:
            self.times.append(time.time() - self.lasttime) #add time since last click to right of times[]
            self.times.pop(0) #delete oldest value
            self.wait = (((self.times[0] + self.times[1])/2)*50) #average two values
            self.wait = int(np.clip (self.wait,1,500)) #convert to int between 10 and 100
            self.lasttime = time.time() #start timer

    def delay(self):
        #wait for self.wait ms
        starttime=time.time()
        while True:
            if (((time.time() - starttime)*1000) > self.wait):
                break
            time.sleep(0.001)

    def increment(self, x):
        #increase the wait variable - slow down if no clicks.
        self.wait += x

def main():
    
    fd = frameDelay()   
    listener = mouse.Listener(   
    on_click=fd.on_press)
    listener.start()
    #open video file
    cap = cv2.VideoCapture("/Users/regvardy/mediapipe_faceswap-main/webcam_grab.mov")
    
    while(cap.isOpened()):
        ret, frame = cap.read()
        cv2.waitKey(1)
        fd.delay() 
        fd.increment(30)
        cv2.imshow('frame',frame)

    cap.release()
    cv2.destroyAllWindows()

if __name__ == "__main__":
    main()
\$\endgroup\$
2
  • \$\begingroup\$ Disregarding your first snippet for the minute, does the rest of your code work? \$\endgroup\$
    – Reinderien
    Mar 31, 2022 at 21:33
  • \$\begingroup\$ Yes. It works fine! \$\endgroup\$ Apr 1, 2022 at 14:03

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.