Search code examples
pythoninfinite

Converting .jp2 to .jpg but the code is running infinitely


I am trying to convert .jp2 files in my folder to .jpg format.

import os
import pyvips

#Assigned directory
directory = 'D:\Anaconda\data'
 
# iterate over files in the directory
for filename in os.listdir(directory):
    f = os.path.join(directory, filename)
    #print(filename)
    # checking if it is a file
    if os.path.isfile(f):
        #Used pyvis for conversion
        image = pyvips.Image.new_from_file(f)
        #storing only the name of the file, removing extension
        fp = filename[:-4]
        image.write_to_file(fp + "j.jpg")

When I am running this code, it's running infinitely without giving any errors. I stopped it manually. What should I do to convert all my .jp2 files in the folder to .jpg?


Solution

  • import os
    import pyvips
    
    # assign directory
    directory = 'D:\Anaconda\data\\'
    target_path_img = 'D:\Anaconda\dataset_image\\'
     
    # iterate over files in
    # that directory
    for filename in os.listdir(directory):
        f = os.path.join(directory, filename)
        #print(directory)
        # checking if it is a file
        if os.path.isfile(f):
            #print(f)
            image = pyvips.Image.new_from_file(f)
            fat = filename[:-4]
            #print(fat)
            image.write_to_file(target_path_img + fat + "_img.jpg")
    

    I know it's pretty lame but can be improved. Moreover, it's giving me the correct result.