How to read all image from folder and save image with same name in other folder python

I have images in the folder my file name is Doc0006.Row1City.jpg. the following code save the image after cropping with the same name but I want to save the image like this Doc0006.Row1City_augment.jpg where I can change in this code

import os.path
import glob
import cv2
def convertjpg(jpgfile,outdir):
    
    src = cv2.imread(jpgfile, cv2.IMREAD_UNCHANGED)
    
    try:
        dst = src[100:500, 200:600] 
        #dst = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
        print(dst.shape)
        cv2.imwrite(os.path.join(outdir,os.path.basename(jpgfile)), dst)
    except Exception as e:
        print(e)
        
for jpgfile in glob.glob(r'/home/hammad/thyroid/data/Hammad/Hammad/HH_Scans_Prediction/7104220_576_F/OriginalScan/*.png'):
    convertjpg(jpgfile,r"/home/hammad/thyroid/data/Hammad/Hammad/HH_Scans_Prediction/7104220_576_F/Cropped/")

Upvotes: 0

Views: 1226

Answers (2)

Abhyuday Vaish
Abhyuday Vaish

Reputation: 2379

You can try the following code:

cv2.imwrite(os.path.join(outdir,os.path.basename(jpgfile).replace(".jpg", "_augment.jpg")), dst)

Explanation: The default name with which it was saving as you mentioned was Doc0006.Row1City.jpg. Now the replace function will replace the .jpg part of your file name with _augment.jpg. This will save the file with the desired name of Doc0006.Row1City_augment.jpg.

Upvotes: 2

elouassif
elouassif

Reputation: 318

You can change this line in your code:

cv2.imwrite(os.path.join(outdir,os.path.basename(jpgfile)), dst)

by

cv2.imwrite(os.path.join(outdir,os.path.basename(jpgfile).replace('.jpg', '_augment.jpg')), dst)

Upvotes: 1

Related Questions