Martin Martin - 6 months ago 12
Python Question

How do I get indices around certain values in an array

So I came accros this tiny but tricky problem.

I have an array of indices of error_images, something like this:

error_frames = [15,27,34,204,205]


Now I am using a for loop to iterate over these frames and add 10 frames in prior and after the erroneous frames in order to get a sequence, so that in the end, the array is more populated. I also removed duplicates (excuse MATLAB writing):

error_sequence = [5:44,194:215]


Now the tricky part:
In Order to show the sequence, I load every image and show it for a certain time using OpenCV
cv2.imshow
. When actually encountering an error, I want to increase the pause between shown images ('slow motion') and have a special overlay. This looks like this, where
frames
is a collection of my pictures of the scene:

for x in error_sequence:
if x in error_frames:
cv2.imshow('Sequence', frames[x])
cv2.putText(frames[x], "Error!", (50, 50),
cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 255), 3)
cv2.waitKey(100)
else:
cv2.imshow('Sequence', frames[x])
cv2.waitKey(50)


The problem is, that this "one-frame" overlay is way too fast and I want to slow down more frames, lets say 3 before and after the encountered error.

Is there some kind of function, that lets me do that? Something like:

if x+-3 in error_frames:
...


Thank you for your help and sorry, if this is an easy question, I don't know how else to describe it. And yes, I could come up with an extra array that I set to 0 if it is further away from an error frame than 3 and use a seperate if case, but I don't find that very attractive and was wondering if there is a built in function or a nice "one-liner" ;)

Answer

Perhaps something like this:

error_frames_set = set(error_frames)
delta = 3

for x in error_sequence:
    slow_frames = set(x + offset for offset in range(-delta, delta+1))
    if slow_frames.intersection(error_frames_set):
        cv2.imshow('Sequence', frames[x])
        cv2.putText(frames[x], "Error!", (50, 50),
                        cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 255), 3)
        cv2.waitKey(100)
    else:
        cv2.imshow('Sequence', frames[x])
        cv2.waitKey(50)