简体   繁体   中英

Convert all jpg to png files in Google Colab

I have a dataset with about 800 images and most are png with a few jpg files. The dataset is mounted in the drive of Google Colab. My question is I have this code below that helps with conversion, but it does not save the files in the images folder from the directory. How do I get the files to save in the original location in the loop?

directory = r'/content/drive/MyDrive/images/images/' 
for filename in os.listdir(directory): 
    if filename.endswith('.jpg'): 
        prefix = filename.split('.jpg')[0]
        # im = Image.open(filename)
        os.rename(filename, prefix+'.png')  
    else: 
        continue

Try this:

directory = r'/content/drive/MyDrive/images/images/' 

files = os.listdir(directory)


# Then you rename the files 
for file_name in files:
    # You give the full path of the file
    old_name = os.path.join(directory, file_name)

    # You CHANGE the extension
    new_name = old_name.replace('.jpg', '.png')
    os.rename(old_name, new_name)

The problem with your code is that when iterating os.listdir() it will have only the file names like image_1.png but not the entire path like '/content/drive/MyDrive/images/images/image_1.png' which is essential for saving the images.

So change the line os.rename(filename, prefix+'.png') into os.rename(os.path.join(directory, filename), os.path.join(directory, prefix+'.png'))

And it works

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM