Reputation: 352
If I have folders with a number followed by an arbitrary title
1 - Dog
2 - Cat
3 - Frog
...
999 - Penguin
And in my code I have something like this (very stripped down)
num = 1
for x in range(100):
cv2.imwrite("C:/path/to/1 - Dog/%d.PNG" % x, image)
if x % 5 == 0:
num += 1:
Is there a way to put in the num
variable in the input to cv2.imwrite()
(currently "C:/path/to/1 - Dog/%d.PNG" % x) to allow my script to automatically switch folders to whatever the value of num
is (every time a condition is met)?
The folder being saved to should always follow the value of num
, where the value matches the number in the name of the folder.
Upvotes: 1
Views: 282
Reputation: 207455
I think you are classifying things and you only have the class number but want the full expanded directory name corresponding to that class.
So, my plan would be to get a list of all directories in the current directory whose name begins with digits. Then make a lookup table (dict) such that if you use the class number as the key you will get the full directory name as a result:
#!/usr/bin/env python3
import re
import os
import glob
# Get list of all entries in current directory that start with a number and are directories
# nDirs are "numbered directories"
nDirs = [path for path in glob.glob('[1-9]*') if os.path.isdir(path)]
# Make a dict where you can lookup the directory name if you have its number
nToName = {re.match(r'^(\d+)',path).group(0):path for path in nDirs}
# Print whole lookup table - just for debug
print(nToName)
{'99': '99 - Pear', '2': '2 - Apple', '1': '1 - Banana'}
So, if your class is 2
and you want the directory, you would do:
directory = nToName.get('2')
which would result in:
'2 - Apple'
Upvotes: 1
Reputation: 1003
To control were to write an image, you provide the path to the new location of the image. This path usually contains the folder name, the image name and the image extension. Which could look like this:
Folder: User/Pictures/Test
Image Name: 1 - Dog
Image Extension: Jpg
Final path: User/Pictures/Test/1 - Dog.jpg
Note that you should make sure that the folders you want to copy the image to actually exist. To ensure that, you could use:
import os
os.makedirs(r"User/Pictures/Test/", exist_ok=True)
Upvotes: 0