How to access file names from a folder in a jupyter notebook - python

I am working with jupyter notebook and python, and I have a folder called 'images', with the images inside titled, 'image0', 'image1', 'image2', etc. I would like to access this folder, and see the largest image number inside the folder. How do I access the folder to see the names of the images inside?
I tried:
imagesList = []
for image in images:
imagesList.append(image)
imageNum = []
for image in images:
imageNum.append(int(image[5:]))
max = 0
for item in imageNum:
if item>max:
max = item
print(max)
but am getting 'images is not defined'.
I also tried:
for image in home/jovyan/images:
but this gave me 'home' is not defined.
How do I access the image names within this folder?
Thanks!

import os
folder_files = os.listdir('images') #You can also use full path.
print("This Folder contains {len_folder} file(s).".format(len_folder=len(folder_files)))
for file in folder_files:
#Action with these files
print(file)

Related

How do I access google drive files with the same name in 2 different folders - Python

I am currently trying to access files with the same name in different google drive folders but do not know how to code this. Below is the file paths and names of the files that I am trying to access.
/content/drive/My Drive/Jacob_Images/Ground_Truths/a (3).jpg
/content/drive/My Drive/Jacob_Images/Ground_Truths/a (7).jpg
/content/drive/My Drive/Jacob_Images/Ground_Truths/a (6).jpg
/content/drive/My Drive/Jacob_Images/Originals/a (3).jpg
/content/drive/My Drive/Jacob_Images/Originals/a (7).jpg
/content/drive/My Drive/Jacob_Images/Originals/a (6).jpg
Below is the code, that I started to make but I am unable to finish it. There are several files in each folder that is why there is an *.
file = '/content/drive/My Drive/Jacob_Images/Originals/*.jpg'
mask = '/content/drive/My Drive/Jacob_Images/Ground_Truths/*.jpg'
glob.glob(file)
glob.glob(mask)
for x in glob.glob(file):
for y in glob.glob(mask):
In this case, the easiest way I can think of would be something like that
import os
original_folder = "data/originals"
ground_truth_folder = "data/ground_truths"
# get file names of all files in folder without the whole path
original_images = os.listdir(original_folder )
ground_truth_images = os.listdir(ground_truth_folder)
for img in original_images:
# For every images in the original folder, check if it is in the Ground_truth one
if img in ground_truth_images
print(f"{img} is in {original_folder} and {ground_truth_folder}"):
# Do your comparison here
same_shape, same_img = compare_images(img, original_folder,ground_truth_folder)
else:
print(f"{img} is in {original_folder} but not in {ground_truth_folder}")
For your comparison you could have a function like below, that returns both if they have the same shape and if it's the same image:
def compare_images(img,original_folder, ground_truth_folder):
original_img = np.array(Image.open(os.path.join(original_folder, img)))
ground_truth_img = np.array(Image.open(os.path.join(ground_truth_folder, img)))
return original_img.shape == ground_truth_img.shape, np.all(original_img == ground_truth_img)

Storing the path to folders and inner folders

i'm having difficulties trying to read from sub-folders that are inside a folder. What im trying to do is: i have my path "C:\Dataset" which has 2 folders inside them and inside both folders, i have person names that have pictures for example: "C:\Dataset\Drunk\JohnDoe\Pic1", "C:\Dataset\Sober\JaneDoe\Pic1". I want to be able to read each picture and store them in a path variable.
At the moment, what i got so far, basically, i get the images as long as they are inside Drunk and Sober only, for instance: 'C:\Dataset\Drunk\Pic1', and the code that i am using to do is this:
DATADIR = "C:\Dataset"
CATEGORIES = ["Positive", "Negative"]
for category in CATEGORIES:
path = os.path.join(DATADIR, category)
for img in os.listdir(path):
img_path = os.path.join(path,img)
img_data = open(img_path, 'r').read()
break
break
Basically, what i am trying to do is that when i iterate inside Drunk folder it also iterates inside the inner folders, reading the path to the pictures that are in C:\Dataset\Drunk\JohnDoe\nthPic, C:\Dataset\Drunk\JoeDoe\nthPic, C:\Dataset\Drunk and Sober \nthJoe\nthPic C:\Dataset\Drunk\JamesDoe\nthPic. Therefore, when I do the reading, it grabs the whole folder map
This is basically what my goal is.
You need one nesting more:
It saves all images in the dictionary images, key is the full path.
DATADIR = "C:\Dataset"
CATEGORIES = ["Drunk", "Sober"]
images = {}
for category in CATEGORIES:
path = os.path.join(DATADIR, category)
for person in os.listdir(path):
personfolder = os.path.join(path, person):
for imgname in os.listdir(personfolder):
fullpath = os.path.join(personfolder, imgname)
images[fullpath] = open(fullpath, 'r').read()

Python - PIL Image open, How to open all image in the directory and keep it update

i follow tutorial on youtube
This one.
the problem is how to open all the images in the directory without declaring 1 by 1...
and name it like in the img_list array
here is part of the code :
my_img = ImageTk.PhotoImage(Image.open("1.jpg"))
my_img1 = ImageTk.PhotoImage(Image.open("2.jpg"))
my_img2 = ImageTk.PhotoImage(Image.open("3.jpg"))
img_list = [my_img, my_img1, my_img2]
I don't use Tk, but you should be able to glob() the files like this:
import glob
# Get list of JPEGs to process
names = glob.glob('*.jpg')
# Open as images
images = [ImageTk.PhotoImage(Image.open(name)) for name in names]

how to open a folder of images (Python)

I'm working on a program to open a folder full of images, copy the images, and then save the copies of the images in a different directory.
I am using Python 2.4.4, but I am open to upgrading the program to a newer version if that allows me to import PIL or Image because I cannot do that with my version.
As of now, I have:
import Image
import os
def attempt():
path1 = "5-1-15 upload"
path2 = "test"
listing = os.listdir(path1)
for image in listing:
im = Image.open(path1)
im.save(os.path.join(path2))
I am new to Python, so this is probably obviously wrong for numerous reasons.
I mostly need help with opening a folder of images and iterating through the pictures in order to save them somewhere else.
Thanks!
Edit- I've tried this now:
import shutil
def change():
shutil.copy2("5-1-15 upload", "test")
And I am receiving an IOError now: IOError: System.IO.IOException: Access to the path '5-1-15 upload' is denied. ---> System.UnauthorizedAccessException: Access to the path '5-1-15 upload' is denied.
at System.IO.FileStream..ctor (System.String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, Boolean anonymous, FileOptions options) [0x00000] in :0
Am I entering the folders wrong? How should I do this if it an a folder within a specific computer network.
Basically there is a folder called images with multiple subfolders within it which I am trying to extract the images from.
Based on this answer, copyfile will do the trick, as you are just copying images from one side to another, as if it was another type of file.
import shutil
import os
def attempt():
path1 = "5-1-15 upload"
path2 = "test"
listing = os.listdir(path1)
for image in listing:
copyfile(image, path2)

how to separate the images in folder using image name python?

I need to separate the images in folder with it's filename in python.
for example, i have a folder of images named as,
0_source.jpg, 0_main.jpg,0_cell.jpg, 1_net.jpg, 1_cells.jpg, 2_image.jpg,2_name.jpg
i want to separate these images and save in different folder like:
folder1:
0_source.jpg, 0_main.jpg, 0_cell.jpg
folder 2:
1_net.jpg, 1_cells.jpg
folder 3:
2_image.jpg, 2_name.jpg
I tried to look around, but seems none of them fits what i really needed.
hope someone here could help.
I'm open to any ideas, recommendation and suggestion, thank you.
The main idea is to use a regular expression to extract the folder name starting from the image name. Then build the folders and move the images
import shutil
import re
import os
images = ["0_source.jpg", "0_main.jpg", "0_cell.jpg", "1_net.jpg", "1_cells.jpg", "2_image.jpg", "2_name.jpg"]
def build_images_folders(image_names: [str]):
folder_name_regex = re.compile(r"^(\d)._*") # Regular expression which extract the folder starting from the image_name name
for image_name in image_names:
regex_match = folder_name_regex.match(image_name)
if regex_match:
folder_index = regex_match.group(1) # Extract the folder name
folder_name = "{folder_prefix}{folder_index}".format(folder_prefix="folder_", folder_index=folder_index) # Build the folder name
os.makedirs(folder_name, exist_ok=True) # Build the folder. If already exists, don't raise exception
src_image_path = image_name
dst_image_path = os.path.join(folder_name, image_name)
shutil.move(src_image_path, dst_image_path)
else:
error = "Invalid image name format \"{image_name}\". Expecting <number>_<string>".format(image_name=image_name)
raise ValueError(error)
if __name__ == '__main__':
build_images_folders(images

Categories