[Solved] how to save file image as original name


The reason you have the error is because the lists made by glob and os.listdir are not the same, either different files (glob is only getting jpg files and listdir gets everything) or different order, or both. You can change the filenames in a list, orig_files, to make a corresponding list of new filenames, new_files.

It also looks like it makes more sense to just read one image at a time (you only use them one at a time) so I moved that into the loop. You can also use os.path.basename to get the filename, and zip to iterate through multiple lists together.

cropped_images = "GrabCut"

if not os.path.exists(cropped_images):
    os.makedirs(cropped_images)

# Load data
filepath = "Data"
orig_files = [file for file in glob.glob(filepath+"/*.jpg")]
new_files = [os.path.join(cropped_images, os.path.basename(f)) for f in orig_files]

for orig_f,new_f in zip(orig_files,new_files):
    image = cv2.imread(orig_f)

    DO SOMETHING...

    cv2.imwrite(new_f, image)

solved how to save file image as original name