Can't find path to put images in a list? - python

I'm having some trouble getting my path to work when opening a folder. I put the folder of images into the same folder as the .py file that I'm coding in. Then I try to open it with this code:
images = []
for file in glob('./images/*.PNG'):
print(file)
im = Image.open(file)
images.append(im)
This, however, isn't working. I typed out the "print(file)" so I could see if it was even opening the file and it doesn't seem to even be doing that. I think it's a pathing issue but I have no idea because (as far as I'm concerned) that's the correct path. To reiterate, this "images" directory is in the same directory as the .py file I'm writing in. Any help would be greatly appreciated.

this is usually what I did when I need to access a file inside path:
import os
pathCurrent = os.getcwd() + '\\'
imageFile = pathCurrent + '*.PNG'
And then you can use it as:
images = []
for file in glob(imageFile):
print(file)
im = Image.open(file)
images.append(im)
Let me know if this help.

Maybe:
images = []
def is_img(p: Path) -> bool:
return p.suffix.upper() in ('.PNG', '.JPG', '.JPEG', '.ICO', '.BMP')
for file in glob('./images/*'):
if not is_img(file):
print(file.suffix)
continue
print(file)
im = Image.open(file)
images.append(im)

Related

Python cannot find a directory

I wrote a code like this with jupyter notebook in a project;
import os
image_path = r'C:\Users\ays\Desktop\IR\01.jpg'
image_files = os.listdir(image_path)
img = cv2.imread(os.path.join(image_path,image_files))
cv2.imshow('image',img)
it gives an error like;
[WinError 3] The system cannot find the path specified: 'C:\Users\ays\Desktop\IR\01.jpg'
i was trying to print an image and
i had a directory problem
The argument to os.listdir() must be the directory, not the image file, so remove \01.jpg.
Then you'll need to loop over the result of os.listdir(), since it returns a list.
import os
image_path = r'C:\Users\ays\Desktop\IR'
image_files = os.listdir(image_path)
for file in image_files:
img = cv2.imread(os.path.join(image_path,file))
cv2.imshow('image',img)
Your image_path seems to be a file, not a directory. Drop the file name and you should be OK:
image_path = r'C:\Users\ays\Desktop\IR'

How can I change all the images in a folder and save the changed images to another folder?

I have a lot of images in a folder. I need to process each image the same way and save the processed images to a different folder. I imagine it something like this:
for i in range(nuber_of_file):
current_image = cv2.imread("path to file")
# transformation
cv2.imwrite("new path", new_image)
I am having difficulty getting the number of files in a folder and getting a new path each time. Can you please tell me how to do this?
You can use:
glob: to get all the files in your directory
rglob: (recursive glob) to get all the files in your directory and all sub directories
Then you can read them with cv2.imread.
here is an example:
from pathlib import Path
import cv2
def main():
destination_path = '/path/to/destination'
target_path = '/path/to/target'
format_of_your_images = 'jpg'
all_the_files = Path(destination_path).rglob(f'*.{format_of_your_images}')
for f in all_the_files:
p = cv2.imread(str(f))
# transformation
cv2.imwrite(f'{target_path}/{f.name}', p)
if __name__ == '__main__':
main()
Hope it was helpful
you can list the files in a folder with os.listdir(dirString). I gives you a list of files names, you can filter them like this :
dl = os.listdir(dirString)
imgList = list()
imgList.append([f for f in dl if ".JPEG" in f or ".jpg" in f or ".png" in f])
Then you get the full path and read the image like this:
img = cv2.imread(os.path.join(dirString, imgList[0]), cv2.IMREAD_COLOR)
Mathieu.

Pygame says it can't find directory

# load all images for the players
animation_types = ['Idle', 'Run', 'Jump']
for animation in animation_types:
# reset temporary list of images
temp_list = []
# count number of files in the folder
num_of_frames = len(os.listdir(f'Assets/{self.char_type}/{animation}'))
for i in range(num_of_frames):
img = pygame.image.load(f'Assets/{self.char_type}/{animation}/{i}.png')
img = pygame.transform.scale(img, (int(img.get_width() * scale), int(img.get_height() * scale)))
temp_list.append(img)
self.animation_list.append(temp_list)
I am fairly new to python and pygame and am making my first game. I ran into a problem where i'm trying to access files for an animation. For the idle animation the directory is Assets/player/Idle. Inside the folder are 5 images. When I run the code I receive this error:
img = pygame.image.load(f'Assets/{self.char_type}/{animation}/{i}.png')
FileNotFoundError: No such file or directory
I am pretty sure the problem is with the images in the animation folder as I made sure the other folders were found and they were fine. I honestly don't know what to do. If you need the full script then I can send it. Thank you.
I am on a linux system and I had a similar problem. This is what worked for me:
import os
PATH = os.path.dirname(os.path.abspath(__file__))
def get_path(*slices):
return os.path.join(PATH, *slices)
First get the path to the containing directory then in the function return the joined path.
In your case you then need to call:
num_of_frames = len(os.listdir(get_path('Assets', self.char_type, animation))
and
img = pygame.image.load(get_paht('Assets', self.char_type, animation, str(i) + '.png')
other sources of the error:
you are on a windows machine (the path-splitting character on windows is not /)
the files aren't named correctly (0.png, 1.png, 2.png, 3.png, 4.png)
EDIT: Debugging idea: add
print('loading path =', f'Assets/{self.char_type}/{animation}/{i}.png')
before loading the image and check if this file actually exists.

how to solve pygame.error: Couldn't open game\images\person1.png

Can you help me? It's the first time that I use pygame and I found an error loading image. I've just searched in this site for a possible solution, but nothing seems to work for me. I tried to use pygame.image.load() with all the path or with a part, but it didn't work. I created this function that is similar of a function in pygame tutorial in the documentation of pygame.
def load_png(name = ""):
current_path = os.path.dirname(__file__)
game_path = os.path.join(current_path, 'game')
image_path = os.path.join(game_path, 'images')
image_path += "\\" + name
image = pygame.image.load(image_path)
if image.get_alpha() is None:
image = image.convert()
else:
image = image.convert_alpha()
return image, image.get_rect()
The problem was an incorrect file name: "person1.png" instead of "person1.jpg".
If anyone has the same problem, try to print the files in the directory and compare them with the file names in your module.
How do I list all files of a directory?

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