2

I have a directory of images which I am trying to resize. However during this process I do not want to retain them in the directory hence I am trying to rewrite with the same name. The following is my code:

import os
from os.path import basename
from imutils import paths
import imutils
import argparse
import cv2

ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True,
    help="path to the input image")
args = vars(ap.parse_args())

for (i, imagePath) in enumerate(paths.list_images(args['image'])):
    image = cv2.imread(imagePath)
    fil = basename(imagePath)
    filname = os.path.splitext(fil)[0]
    newimage = imutils.resize(image, width=500)
    cv2.imwrite(filname+'.jpg', newimage)

When I try to use cv2.imshow for both pre and post resize I could get the display. Similarly when I print the fil and filname, it gets printed correctly. However, the images are not getting overwritten.

1 Answer 1

3

If you would like to overwrite them with the exact name and extension they had originally, you don't need to reconstruct the path like you're doing in this line

filname = os.path.splitext(fil)[0]

Rather, you can continue to use the variable imagePath that was provided with imutils.paths which is the exact path to overwrite, already.

cv2.imwrite(imagePath, newimage)


However, if you do need to take any images of other filetypes and convert them to .jpg like you've done, then you will not be overwriting example.png when you write example.jpg, so you'd need to delete example.png.


With my changes above, the code overwrites the images with their new sizes on my system.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.