[英]Convert all jpg to png files in Google Colab
我有一个包含大约 800 张图像的数据集,其中大多数是带有一些 jpg 文件的 png。 数据集安装在 Google Colab 的驱动器中。 我的问题是我下面的这段代码有助于转换,但它不会将文件保存在目录中的 images 文件夹中。 如何让文件保存在循环中的原始位置?
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
尝试这个:
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)
您的代码的问题在于,在迭代os.listdir()
时,它将只有像image_1.png
这样的文件名,而不是像'/content/drive/MyDrive/images/images/image_1.png'
这样的整个路径,这是必不可少的用于保存图像。
因此将os.rename(filename, prefix+'.png')
行更改为os.rename(os.path.join(directory, filename), os.path.join(directory, prefix+'.png'))
它有效
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.