Home > database >  How can I change all the images in a folder and save the changed images to another folder?
How can I change all the images in a folder and save the changed images to another folder?

Time:10-06

I have a lot of images in a folder. I need to process each image the same way and save the processed images to a different folder. I imagine it something like this:

for i in range(nuber_of_file):
    current_image = cv2.imread("path to file")
    #  transformation
    cv2.imwrite("new path", new_image)

I am having difficulty getting the number of files in a folder and getting a new path each time. Can you please tell me how to do this?

CodePudding user response:

you can list the files in a folder with os.listdir(dirString). I gives you a list of files names, you can filter them like this :

dl = os.listdir(dirString)

imgList = list()

imgList.append([f for f in dl if ".JPEG" in f or ".jpg" in f or ".png" in f])

Then you get the full path and read the image like this:

img = cv2.imread(os.path.join(dirString, imgList[0]), cv2.IMREAD_COLOR)

Mathieu.

CodePudding user response:

You can use:

  • glob: to get all the files in your directory
  • rglob: (recursive glob) to get all the files in your directory and all sub directories

Then you can read them with cv2.imread.

here is an example:

from pathlib import Path
import cv2


def main():
    destination_path = '/path/to/destination'
    target_path = '/path/to/target'

    format_of_your_images = 'jpg'

    all_the_files = Path(destination_path).rglob(f'*.{format_of_your_images}')

    for f in all_the_files:
        p = cv2.imread(str(f))
        #  transformation
        cv2.imwrite(f'{target_path}/{f.name}', p)


if __name__ == '__main__':
    main()


Hope it was helpful

  • Related