Pradip Gupta
Pradip Gupta

Reputation: 579

Equally spaced elements between two given number

I am working with video files. I have a start frame no. x (say 10) and a stop frame no. y (say 200). I want to pick up "n" frames (say n=8) between x and y. These "n" number of frames should be unique and equally spaced between x and y.

Please suggest the fastest way to do this in Python 3.x. Presently I am using this:

list = random.sample(range(start_frame,stop_frame), int((stop_frame-start_frame)/n))

This gives me unique frames but not equally spaced. How can I get equally spaced frames between the start and stop frame nos.

Upvotes: 3

Views: 7824

Answers (2)

Brad Solomon
Brad Solomon

Reputation: 40878

If you want both endpoints to be inclusive, you could so something like this to get n=8 frames from 10 to 200:

x = 10
y = 200
n = 8
step = (y - x) / (n - 1)

frames = [x + step * i for i in range(n)]

print(frames)
[10.0, 37.14285714285714, 64.28571428571428, 91.42857142857143,
 118.57142857142857, 145.71428571428572, 172.85714285714286, 200.0]

Upvotes: 7

jpp
jpp

Reputation: 164633

If you are open to using a 3rd party library, this is possible with NumPy. You can use numpy.linspace to equally divide a range into n components:

import numpy as np

frames = np.linspace(10, 200, num=8)

print(frames)

[ 10.          37.14285714  64.28571429  91.42857143 118.57142857
 145.71428571 172.85714286 200.        ]

If you need integers, you can cast to int:

print(frames.astype(int))

array([ 10,  37,  64,  91, 118, 145, 172, 200])

Upvotes: 6

Related Questions