1

i have multiple folders in a directory and in each of the folder are hundred of images(.jpg).

Now i try to create a csv file, which includes the name of the image, a comma and then the label of it.

So my folders are

dog cat mouse elephant

and in these are images titled dog1.jpg, dog2.jpg, ... cat1.jpg, and so on.

I have already tried to list all the names of the pictures with the following code:

import os

path = '/content../'

files = []
for  r, d, f in os.walk(path):
    for file in f:
        if '.jpg' in file:
          print(file)

This prints me the list of my images. My thoughts are that i create something like

import csv 

# csv file name 
with open('test.csv')
category []
if filename == 'dog' then append 0 
if filename == 'cat' then append 1 ... 

But I am getting nowhere.

At the end the csv file should look like:

dog1.jpg,0
dog2.jpg,0
cat1.jpg,1
mouse2.jpg,2
elepant.jpg,3

I hope you can help me, Thank you very much!

cocojambo
  • 63
  • 2
  • 5
  • So, instead of *print(file)*, which prints the file to the command line, you should just append the filename to the csv. Then within the same loop, work out the label and append that. Theoretically, you could do it with a normal file like [this](https://stackoverflow.com/questions/7152762/how-to-redirect-print-output-to-a-file-using-python). Having this at the same loop level is the important part. – Pam Nov 09 '19 at 13:32

1 Answers1

0

Here is my take on it

File with explanation: https://hastebin.com/hopeneluhi.py

Please note I didnt test this. Let me know if there are any issues :)

Sxribe
  • 819
  • 7
  • 16
  • Hey, I tried it but I have a question regarding this line: t = f[0:-5] #cut f the number and .jpg from file, leaving only the type (this may have to be changed.) In my csv file i looks like this now: dog154.jpg, dog15 dog163.jpg, dog16 so it cuts out the last nr. and writes it next to it.. can you help me? – cocojambo Nov 10 '19 at 20:56
  • Of course, is there any chance you have a discord account where we could communicate? If so, send me a friend request at Sxribe#1182 – Sxribe Nov 10 '19 at 22:39
  • hello, i solves it by using if "dog" in t instead of if t == dog. Thank you very much !! – cocojambo Nov 10 '19 at 23:03