Search code examples
pythonpython-3.xopencvimage-processingglob

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/")

Solution

  • 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)