E. Erfan
E. Erfan

Reputation: 1411

Python concatinating a string and an intiger counter to name content inside a folder

I am using widows 10 pro, python 3.6.2rc1. I am training a convolutional neural network made by tensorflow. As a preprocessing phase, I hae written the following code to resize each image. It works perfectly well, but since I have more than 100 training images (I made it quite low just to see how it works at the moment) with very different names, and at the end I'd like all of them follow the same naming convention as in "image001", "image002" and so on, I added a counter and use it to change the name of the image before saving it to the same folder by using cv2.imwrite(). But I am getting this error:

Traceback (most recent call last):
  File "E:/Python/TrainingData/TrainingPrep.py", line 11, in <module>
    cv2.imwrite(imageName,re)
cv2.error: D:\Build\OpenCV\opencv-3.2.0\modules\imgcodecs\src\loadsave.cpp:531: error: (-2) could not find a writer for the specified extension in function cv::imwrite_

import cv2
import glob

i=0
images = glob.glob("*.jpg")
for image in images:
    img = cv2.imread(image,1)
    counter=str(i)
    re = cv2.resize(img,(128,128))
    imageName = "image"+counter
    cv2.imwrite(imageName,re)
    i=i+1
    print(counter)

I need my images have the names image001, image00x. I appreciate if you help me solve this problem.

Thank you very much.

Upvotes: 1

Views: 1559

Answers (2)

jacoblaw
jacoblaw

Reputation: 1283

This method will give you the leading zeros you want in the file name:

import cv2
import glob

i=0
images = glob.glob("*.jpg")
for image in images:
    img = cv2.imread(image,1)
    re = cv2.resize(img,(128,128))
    imageName = "image{:03d}.png".format(i) # format i as 3 characters with leading zeros
    cv2.imwrite(imageName,re)
    i=i+1
    print(counter)

Upvotes: 2

Alex Huszagh
Alex Huszagh

Reputation: 14614

The imwrite method expects the extension to determine the file format.

Simply change your line to (for PNG, or whatever file format you want) and it should work:

imageName = "image"+counter+".png"

You can rename the files later if you so wish, using glob.glob. A working example should be something like this:

import cv2
import glob
import os

i=0
images = glob.glob("*.jpg")
for image in images:
    img = cv2.imread(image,1)
    counter=str(i)
    re = cv2.resize(img,(128,128))
    imageName = "image"+counter+".jpg"
    cv2.imwrite(imageName,re)
    i=i+1
    print(counter)

rename = glob.glob("images*.jpg")
for src in rename:
    dst = os.path.splitext(item)[0] 
    os.rename(src, dst)

Upvotes: 3

Related Questions