Avinash Koshal
Avinash Koshal

Reputation: 85

Saving multiple images with the Original name after introducing Gaussian Blur

I have Python code which reads 54 images from the folder named Disparity and applies Gaussian Blur to these images and after that writes them to a location. The code is given below:

path = "Disparity/*.png"

for bb,file in enumerate (glob.glob(path)):
    a = cv2.imread(file)
    blur = cv2.GaussianBlur(a, (5, 5), random.randint(3, 10))
    cv2.imwrite('GaussianBlur{}.jpg'.format(bb), blur)

After running this code, what I'm expecting is that it reads the first image as a.png and the second image as b.png.

These two images should be saved as a_GaussianBlur0.jpg and b_GaussianBlur.jpg.

Please tell me how I could get the original name along with the edited one?

Upvotes: 0

Views: 1547

Answers (2)

Martin Evans
Martin Evans

Reputation: 46759

To extract just the filename from a given file path, you can use the Python os.path.basename() function. This will also give you an extension. The os.path.splitext() could then be used to return just the base file name. This can then be used to construct your new output filename:

import os

path = "Disparity/*.png"

for index, filename in enumerate(glob.glob(path)):
    a = cv2.imread(filename)
    blur = cv2.GaussianBlur(a, (5, 5), random.randint(3, 10))
    basename = os.path.splitext(os.path.basename(filename))[0]
    cv2.imwrite(f'{basename}_Gaussian{index}.png')

So if you had three files ['abc.png', 'def.png', 'ghi.png'], your output filenames would be:

abc_Gussian0.png
def_Gussian1.png
ghi_Gussian2.png

Upvotes: 1

Avinash Koshal
Avinash Koshal

Reputation: 85

I would like to answer my Own Question... I have to do the following changes in my code:

The last line of code which is : -> cv2.imwrite('GaussianBlur{}.jpg'.format(bb), blur )

This should be like: -> cv2.imwrite(file+'GaussianBlur{}.jpg'.format(bb), blur )

I have added file here because all names of the files that are read from the Disparity folder are inside the File variable. By adding the file I'm actually adding the original name to individual image

Upvotes: 0

Related Questions