-2

The idea is the following, the script needs to recognize all DAV files recursively in the folder, and apply the conversion to JPEG of 5 seconds using OPENCV. So far everything working. However the script is listing the AVI files but converts only 1 file, and not all that were listed.

import os
import cv2


path = 'C:\\Users\\coleta 1\\Desktop\\SNAPSHOT'

files = []
for r, d, f in os.walk(path):
    for file in f:
        if '.avi' in file:
            files.append(os.path.join(r, file))

for f in files:
    print(f)

vidcap = cv2.VideoCapture(f)
def Printar(sec):
    vidcap.set(cv2.CAP_PROP_POS_MSEC,sec*10000)
    hasFrames,image = vidcap.read()
    if hasFrames:
        cv2.imwrite("image"+str(count)+".jpg", image)   
    return hasFrames
sec = 0
frameRate = 0.5
count=1
success = Printar(sec) 
while success:
     count = count + 1
     sec = sec + frameRate
     sec = round(sec, 2)
     success = Printar(sec)
     continue
audicom
  • 3
  • 1

2 Answers2

0

The problem with your code is that the lines which use f, vidcap, etc. are outside of the loop, so will not change each time. You need to restructure so that the f, sec, count and vidcap change with each iteration of the loop. You should also try to avoid functions relying too much on global variables, as it becomes harder to know what their values will be at the time the function is executed - generally the values should instead be passed to the function as parameters. A couple of possible ways to reorganize the code would be like this:

...

def do_stuff(path):
    print(path)
    vidcap = cv2.VideoCapture(path)
    frameRate = 0.5
    i = 0
    while True:
        success = printar(frameRate*i, vidcap, i+1)
        if not success:
            return  # add a return value if needed
        i += 1

def printar(sec, vidcap, count):
    vidcap.set(cv2.CAP_PROP_POS_MSEC,sec*10000)
    hasFrames,image = vidcap.read()
    if hasFrames:
        cv2.imwrite("image"+str(count)+".jpg", image)   
    return hasFrames

for f in files:
    do_stuff(f)

Or possibly simpler and better:

from itertools import count
...

def do_stuff(path):
    vidcap = cv2.VideoCapture(path)
    frameRate = 0.5
    for i in count():
        vidcap.set(cv2.CAP_PROP_POS_MSEC, i * frameRate * 10000)
        has_frames, image = vidcap.read()
        if has_frames:
            cv2.imwrite("image{}.jpg".format(i+1), image) 
        else:
            return

for f in files:
    print(f)
    do_stuff(f)
Stuart
  • 9,597
  • 1
  • 21
  • 30
  • I understand, I tried with two options, but in all or the error was the same: It is not necessary to do _Stuff (f) .I updated the question with the error image. – audicom Jan 28 '20 at 17:55
  • sorry, I have edited it. `do_stuff` needs to be defined before it is called. – Stuart Jan 28 '20 at 21:11
0

I understand, I tried with two options, but in all or the error was the same: It is not necessary to do _Stuff (f)

enter image description here

audicom
  • 3
  • 1