0

I want to read a sequence of images with VideoCapture but all I could find are examples (such as this one) that in the name of the images there's a proper numeration. My images are in the format: img5000.png, img5002.png, img5004.png...

And I can't find a way to read them without recieving errors. Is there a way to do it?

The code I'm working with is like this one:

import cv2
import numpy
cap = cv2.VideoCapture("/path/img5{:03d}.png",cv2.CAP_IMAGES).

while(1):
   ret,frame = cap.read()
   cv2.imshow('image',frame)
   cv2.waitKey()
   print(frame.shape
carbassot
  • 141
  • 1
  • 10
  • Is there any reason for you not use `cv2.imread()` instead? I don't think you can increment by `2` using the constructor of `cv2.VideoCapture()`. But you can ignore the errors caused by non-existant files in the sequence, check this answer: https://stackoverflow.com/a/63249900/176769 – karlphillip Mar 08 '23 at 19:06

1 Answers1

0

If I get your question right, you want to save the video of your camera into images starting with the name img5000.png.

A slight modification in your code can give you the desired result.

import cv2
import os,sys
cap = cv2.VideoCapture(0)
#file_count is 4999 to start naming from 5000
file_count=4999
#targerDir is the path where you want to save the images
#Here its left as . as I want to save it to the current dir
targetDir='.'
while(1):
   ret,frame = cap.read()
   # show image in window
   cv2.imshow("window", frame) 
   cv2.imwrite(os.path.join(targetDir, f"img{int(file_count)+1}.png"), frame)
   file_count=file_count+1
   keyPressed = cv2.waitKey(5) # time to wait between frames
   if keyPressed != -1: 
      # stop recording if any key is pressed
      sys.exit(0)
   print(frame.shape)