0

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?

1
  • python, pathlib Commented Apr 22, 2022 at 15:46

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer however I got this error: TypeError: join() argument must be str, bytes, or os.PathLike object, not 'ndarray'
@JackNg There is a typo in my code. Please change the last line to cv2.imwrite(os.path.join(output_path, 'img_{}.png'.format(i)), rotated)
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.