Search code examples
pythonopencvimage-preprocessing

How to save multiple images in one folder by using open cv?


Here is the code that i'm trying to modify. To read and save all the images at once in one folder, however I got error when I tried to save it


import cv2
import glob        
import numpy as np

#empty lists
image_list=[]

images = []
for img in glob.glob(r"C:\Users\user\Documents\Dataset\Test\Abnormal_Resize\Abnormal_Crop\*.png"):
    n= cv2.imread(img)
    images.append(n)
    print (img)

#limit list to 236 elements
image_list = image_list[:100]

#Resizing the image for compatibility
for img in image_list:
    image = cv2.resize(image, (500, 600))

#The initial processing of the image
#image = cv2.medianBlur(image, 3)
image_bw = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

#The declaration of CLAHE 
#clipLimit -> Threshold for contrast limiting
clahe = cv2.createCLAHE(clipLimit = 5)
final_img = clahe.apply(image_bw) 

cv2.imwrite(path+r"C:\Users\user\Documents\Dataset\Test\Abnormal_Resize\Abnormal_Crop\Abnormal_Cntrst\contrast_"+str(i)+".png", final_img)

Solution

  • It seems like there are multiple issues with this code.

    1. i is not defined.
    2. images list has all the images appended and while processing you are making use of the empty list variable image_list

    You are probably looking for a solution like this.

    import cv2
    import glob        
    import numpy as np
    
    input_path = r"<your_input_folder_path>/*.png"
    
    # make sure below folder already exists
    out_path = '<your_output_folder_path>/'
    
    image_paths = list(glob.glob(input_path))
    for i, img in enumerate(image_paths):
        image = cv2.imread(img)
        image = cv2.resize(image, (500, 600))
        #The initial processing of the image
        #image = cv2.medianBlur(image, 3)
        image_bw = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    
        #The declaration of CLAHE 
        #clipLimit -> Threshold for contrast limiting
        clahe = cv2.createCLAHE(clipLimit = 5)
        final_img = clahe.apply(image_bw) 
    
        cv2.imwrite(out_path + f'{str(i)}.png', final_img)