Skip to content Skip to sidebar Skip to footer

Save Images In Loop With Different Names

I have a problem with saving cropped images in a loop. My code: def run(self, image_file): print(image_file) cap = cv2.VideoCapture(image_file) while(cap.isOpened()):

Solution 1:

You are saving each file with the same name. Hence you are overwriting previous saved images

outfile = '%s/%s.jpg' % (self.tgtdir, self.basename)

Change the line to this to add a random string in the name

outfile = '%s/%s.jpg' % (self.tgtdir, self.basename + str(uuid.uuid4()))

You will need to import uuid at the top of your file too

Solution 2:

You may use the datetime module to get the current time with milliseconds precision, which would avoid the name conflicts, to assign the name before saving the image as:

from datetime import datetime

outfile = '%s/%s.jpg' % (self.tgtdir, self.basename + str(datetime.now()))
cv2.imwrite(outfile, img)

You can also use other techniques such as uuid4 to get unique random id for each frame, but since the name would be random it would cumbersome on some platforms to display them in sorted orders, So I think using timestamp in name would get your job done.

Solution 3:

import numpy as np
import cv2

cap = cv2.VideoCapture(0)
i = 0while(True):
    # Capture frame-by-frame
    i = i +1
    ret, frame = cap.read()

gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

# Display the resulting frame
cv2.imshow('frame',frame)
**cv2.imwrite("template {0}.jpg".format(i),gray)**


if cv2.waitKey(0) & 0xFF == ord('q'):
    break

cap.release()
cv2.destroyAllWindows()

--- Code by rohbhot

Solution 4:

i think this will helpful...

importcv2vid= cv2.VideoCapture("video.mp4")
d = 0
ret, frame = vid.read()

while ret:
    ret, frame = vid.read()
    filename = "images/file_%d.jpg"%d
    cv2.imwrite(filename, frame)
    d+=1

this will save every frame with different name.

Post a Comment for "Save Images In Loop With Different Names"