3

I am running a code in python where I get images from input file, and create another folder as output and a file csv. The code that I run is as below:

# import the necessary packages
from PIL import Image
import argparse
import random
import shutil
import glob2
import uuid

# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--input", required = True,
    help = "input directory of images")
ap.add_argument("-o", "--output", required = True,
    help = "output directory")
ap.add_argument("-c", "--csv", required = True,
    help = "path to CSV file for image counts")
args = vars(ap.parse_args())

# open the output file for writing
output = open(args["csv"], "w")

# loop over the input images
for imagePath in glob2.iglob(args["input"] + "/*/*.jpg"):
    # generate a random filename for the image and copy it to
    # the output location
    filename = str(uuid.uuid4()) + ".jpg"
    shutil.copy(imagePath, args["output"] + "/" + filename)

    # there is a 1 in 500 chance that multiple copies of this
    # image will be used
    if random.randint(0, 500) == 0:
        # initialize the number of times the image is being
        # duplicated and write it to the output CSV file
        numTimes = random.randint(1, 8)
        output.write("%s,%d\n" % (filename, numTimes))

        # loop over a random number of times for this image to
        # be duplicated
        for i in range(0, numTimes):
            image = Image.open(imagePath)

            # randomly resize the image, perserving aspect ratio
            factor = random.uniform(0.95, 1.05)
            width = int(image.size[0] * factor)
            ratio = width / float(image.size[0])
            height = int(image.size[1] * ratio)
            image = image.resize((width, height), Image.ANTIALIAS)

            # generate a random filename for the image and copy
            # it to the output directory
            adjFilename = str(uuid.uuid4()) + ".jpg"
            shutil.copy(imagePath, args["output"] + "/" + adjFilename)

# close the output file
output.close()

After running the code I get only csv file, but I don't get output folder. The way I run the code is:

python gather.py --input 101_ObjectCategories --output images --csv output.csv

Please can you help me how to solve the problem, because I need the output folder for next steps, running next functions.

3
  • 3
    Have you looked into os.mkdir()? Commented Mar 1, 2020 at 19:41
  • The error I get Traceback (most recent call last): File "...\code\gather.py", line 31, in <module> shutil.copy(imagePath, args["output"] + "/" + filename) File "...\Anaconda3\lib\shutil.py", line 248, in copy copyfile(src, dst, follow_symlinks=follow_symlinks) File "...\Anaconda3\lib\shutil.py", line 121, in copyfile with open(dst, 'wb') as fdst: FileNotFoundError: [Errno 2] No such file or directory: '....\\database/8403e077-3fd5-4d65-9f45-ada5fab36f9b.jpg' Commented Mar 1, 2020 at 21:38
  • That error seems to be related to the file you are trying to move, not necessarily the folder you've created Commented Mar 1, 2020 at 22:17

3 Answers 3

4

I would recommend the following approach:

import os
from pathlib import Path

Path('path').mkdir(parents=True, exist_ok=True)

This works cross-platform and doesn't overwrite the directories if they already exist.

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

3 Comments

You don't need to os.path.join. You can just do Path("directory/directory").mkdir(...) as pathlib will normalize this.
Yes it does, hence why I said "pathlib will normalize this." :-) Try it out: repl.it/repls/ExcitableTameSpools
Oh, wow, you're right! Let me delete the comment and edit the answer. Thanks!
3

You should try the os module. It has a mkdir method that creates a directory based on the path you give it as a parameter.

import os
os.mkdir("path")

Comments

3

While most answers suggest using os.mkdir() I suggest you rather go for os.makedirs() which would recursively create all the missing folders in your path, which usually is more convinient.

import os
os.makedirs('foo/bar')

Docs: https://docs.python.org/3/library/os.html#os.makedirs

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.