Python/Opencv save multiple images to folder with different names

Issue

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?

Solution

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

Answer Checked By – Willingham (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.