pythonfor-loopglobos.path

For loop not writing images


I'm attempting to write a for loop that opens each image in a folder, processes it, and then outputs it back into the same folder. The problem is, when I run the script, nothing happens. I just see the script displayed in the command window. I have tried running each part of the script outside of the loop, and the individual parts seem to be okay. There are no errors when this happens. For reference, I have defined the guassian noise image outside of the loop, with the loop adding the guassian noise over the original image. I then want to append a number to the end of the new image name, so the original image is not deleted.

import os
import glob
import cv2
import numpy as np
img_dir = "path to folder"
data_path = os.path.join(img_dir, '*tif')
files = glob.glob(data_path)
data = []
#Loop
i = 0
for f1 in files:
    img = cv2.imread(f1)
    data.append(img)
    #image processing
    cv2.imwrite(
        "{}{}_{:07d}.tif".format(
            img_dir,
            f1.split("/")[-1].strip(".tif"),
            i),
        img)        
    i += 1

Solution

  • I got it figured out for anyone with similar problems. This was a path issue. I was pulling from a list and python didn't like that. The following changes (specifically the definition of "files" and the for loop definition are what worked.

    import os
    import glob
    import cv2
    import numpy as np
    import matplotlib.pyplot as plt
    
    #Set working directory
    wrking_dir = os.chdir(os.path.join(path))
    
    #Get images from working directory
    files = glob.glob("*.tif")
    
    #Create zero image with same dimensions as input image
    gauss_noise=np.zeros((400,400, 3),dtype=np.uint8)
    cv2.randn(gauss_noise,5,95)
    gauss_noise=(gauss_noise*10.5).astype(np.uint8)
    
    #Loop over images to add guassian mask and then save
    i = 0
    for file in files:
        img=cv2.imread(file)
        #Add gaussian noise image to OG image
        gn_img=cv2.add(img,gauss_noise)
        #cv2.imwrite("{}{}_{:02d}.tif".format(img_dir,file.split("/")[-1].strip(".tif"), i), gn_img)        
        cv2.imwrite('masked_' + file, gn_img)