Python/Opencv save multiple images to folder with different names

Question:

I am working on image processing, I have a folder with all of the images that needs to be processed, and I want to save all the processed images to another folder. How do I do that?

for img in glob.glob("Img/*.png"):
    path = '/result'
    image = cv2.imread(img)
    angle, rotated = correct_skew(image)
    print(angle)
    cv2.imwrite(os.path.join(path , 'img.png'), rotated)
    cv2.waitKey(1)

This code can read the image and process it, but I can’t figure out how to save all the images with different names, like I want it to be img1.png, img2.png, etc.

Or is there anyway that I can save the images to another folder with the same names as before?

Asked By: Jack

||

Answers:

In order to save your processed images in a serial manner, you can use enumerate. When a loop is initiated using enumerate, a counter is also initiated. And each iteration yields an integer number.

In the following case i is the integer value which increments for each iteration. i is used as part of the file name to save the processed image

path = '/result'
for i, img in enumerate(glob.glob("Img/*.png"), 1):
    image = cv2.imread(img)
    angle, rotated = correct_skew(image)
    print(angle)
    cv2.imwrite(os.path.join(output_path, 'img_{}.png'.format(i)), rotated)
Answered By: Jeru Luke

Save the last line as a variable wrapped in a string()

Then cv2.imwrite(variable)for the last line.

#My thought is to change the type to a string and then write the file as originally desired. When you save as a string you can change whatever type it is turning into inside the for statement.

Answered By: Linc Minecrafter