Home > database >  Python/Opencv save multiple images to folder with different names
Python/Opencv save multiple images to folder with different names

Time:05-01

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?

CodePudding user response:

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)
  • Related