Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
import S1-T1-C.00000
Image.open('C:/Users/Vims/Desktop/7th sem/ISA/Lab_1/sequence/sequence')
I have set of image sequence or video. I would like to load in the python code. How can I do it? After that I will do background subtraction of an image.
The sequence of image is from S1-T1-C.00000 to S1-T1-C.00999.
In all situations you need for-loop.
If you don't know names then you can use os.listdir(folder) to get all filenames in folder (you can also use sorted() to have them in correct order) and then you have to read every image separatelly
all_images = []
folder = "C:/folder/with/images"
for filename in sorted(os.listdir(folder)):
full_path = os.path.join(folder, filename)
img = Image.open(full_path)
all_images.append( img )
If you know filenames then you can use string formatting or f-string
all_images = []
folder = "C:/folder/with/images"
for number in range(0, 1_000):
filename = f"S1-T1-C.{number:05}"
full_path = os.path.join(folder, filename)
img = Image.open(full_path)
all_images.append( img )
BTW:
If you have images in many folders then it may need nested for-loops
all_images = []
base_folder = "C:/folder/with/images"
for foldername in os.listdir(base_folder):
folder = os.path.join(base_folder, foldername)
for filename in sorted(os.listdir(folder)):
full_path = os.path.join(folder, filename)
img = Image.open(full_path)
all_images.append( img )
If there can be some other files/folders then every version may need some if/else to filter files/folders
There is also module glob which can use * to match many files/folders
all_filenames = glob.glob("*/S1-T1-C.*")
for filename in all_filenames:
# ... code ...
Related
import os
train_dir = "/Images/train/"
data = []
for i in os.listdir(train_dir):
path = os.path.join(train_dir, i)
img = cv2.imread(path)
print(i)
data.append(img)
My train directory has 49000 images in order img(1), img(2), ..., img(49000)
I want to append these images in this order only but they are getting appended in a different order (as shown in the image).
Any help?
I want to append them as img(1).png, img(2).png, img(3).png, and so on.
Using the sorted method helped me.
data = []
train_dir = "/Images/train/"
files = os.listdir(train_dir)
files = sorted(files ,key=lambda x: int(os.path.splitext(x)[0]))
for i in (files):
path = os.path.join(train_dir, i)
img = cv2.imread(path)
data.append(img)
So all you want to do is to list the images name in a python list. Which is filenames in my solution. Python list has function called sort() which will sort all the images name. Your new filenames list will be in sorted order relative to your images name that are there inside your directory. So, iterating through the list, you will be getting the sorted images name.
train_dir = "/Images/train/"
filenames = [img for img in os.listdir(train_dir)]
filenames.sort()
data = []
for i in filenames:
path = os.path.join(train_dir, i)
img = cv2.imread(path)
print(i)
data.append(img)
I have one folder that contains many subfolders, and images within those subfolders. I have code that loops through the folders and subfolders and prints out the name of each image one at a time. I want all of these image names to be stored in a single array. How do I get my loop to append each image name to the same array?
I have only seen similar solutions on Linux or Matlab so far, but not on python.
files = []
#r=root, d=directories, f = files
for r, d, f in os.walk(path):
for face_image in f :
if face_image.endswith("g"): #to get all '.jpg' and all '.png' files
print(face_image)
When I run the loop above, I get all ~1000 image names printed. But when I then try and print(face_image) outside of the loop, only the name of the final image in the loop is printed. I now now this is because I have not appended each name to an array, but am not sure how to go about this? Any help would be massively appreciated!
Using pathlib and a recursive glob pattern:
from pathlib import Path
file_types = ("jpg", "png")
file_paths = []
for file_type in file_types:
file_paths.extend(Path(".").glob(f"**/*.{file_type}"))
file_names = [file_path.name for file_path in file_paths]
After your print statement, you can use files.append(face_image) to add the face image to your list. When the loops are done, all valid image names will be in the list for you to use.
I wasn't sure if this was a legit question or not. You need to append the files to the list.
files = []
#r=root, d=directories, f = files
for r, d, f in os.walk(path):
for face_image in f :
if face_image.endswith("g"): #to get all '.jpg' and all '.png' files
print(face_image)
files.append(face_image)
You could try something like this:
files = []
for r, d, f in os.walk(path):
# collect all images
files += [os.path.join(r, file) for file in f]
# filter images
files = [ff for ff in files if ff.endswith('g')]
or a little more compact:
files = []
for r, d, f in os.walk(path):
# collect all images that end with 'g'
files += [os.path.join(r, file) for file in f if file.endswith('g')]
I want to save output images using original name of image.
I try this code, but most cases work well, and a half save other file names. How to do it better?
cropped_images = "GrabCut"
if not os.path.exists(cropped_images):
os.makedirs(cropped_images)
# Load data
filepath = "Data"
images = [cv2.imread(file) for file in glob.glob(filepath + "/*.jpg")]
file_names = []
for filename in os.listdir(filepath):
org_image_name = os.path.splitext(filename)[0]
file_names.append(org_image_name)
for i, image in enumerate(images):
DO SOMETHING...
img_name = file_names[i]
cropped_images_path = os.path.join(cropped_images, img_name + '.jpg')
cv2.imwrite(cropped_images_path, image)
The reason you have the error is because the lists made by glob and os.listdir are not the same, either different files (glob is only getting jpg files and listdir gets everything) or different order, or both. You can change the filenames in a list, orig_files, to make a corresponding list of new filenames, new_files.
It also looks like it makes more sense to just read one image at a time (you only use them one at a time) so I moved that into the loop. You can also use os.path.basename to get the filename, and zip to iterate through multiple lists together.
cropped_images = "GrabCut"
if not os.path.exists(cropped_images):
os.makedirs(cropped_images)
# Load data
filepath = "Data"
orig_files = [file for file in glob.glob(filepath+"/*.jpg")]
new_files = [os.path.join(cropped_images, os.path.basename(f)) for f in orig_files]
for orig_f,new_f in zip(orig_files,new_files):
image = cv2.imread(orig_f)
DO SOMETHING...
cv2.imwrite(new_f, image)
This question already has answers here:
Renaming multiple files in a directory using Python
(8 answers)
Closed 4 years ago.
I have a folder with about 1000 images ordered from 1.jpg to 1000.jpg, I want to rename these names with a list "x" that I have with me.
x = ["hello", "rat", ...]
This is the list that I have, so I would like to change the names of the images from 1.jpg to hello.jpg and so on. How do I do this?
I thought of reading the file and then using os.rename(), but I dint know how to do it
with open(x) as list1:
newnames = list1.read().split(',\n')
import os
my_list_of_new_names = ["hello", "rat", "etc..."]
my_dir = "C:\path_to_my_images\my_directory_of_images"
for filename in os.listdir(my_dir):
filename = filename.split('.')
try:
new_name, ext = filename
os.rename(filename, my_list[int(new_name)-1] + ext)
except:
#your list may not be the correct size
pass
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
So I have the file 3D_492.png and I am trying to get rid of everything but the numbers after the last underscore. How would I go about this?
I want 3D_492.png to become 492.png
More examples:
Anniversary_1_Purple_710.png to become 710.png
They are all in the folder \Images
Edit: I'm dumb and forgot to say that I would like to rename the files with the new names.
Thanks
Using split:
filename = "3D_710.png"
# create a list of the parts of the file name separated by "_"
filename_parts = filename.split("_")
# new_file is only the last part
new_file = filename_parts[-1]
print new_file
# 710.png
Full example including rename, assuming Images is relative to the directory containing our Python script:
from os import listdir, rename
from os.path import isfile, join, realpath, dirname
dir_path = dirname(realpath(__file__))
images_path = join(dir_path, "Images")
only_files = [f for f in listdir(images_path) if isfile(join(images_path, f))]
for file in only_files:
filename_parts = file.split("_")
# new_file is only the last part
new_file = filename_parts[-1]
rename(join(images_path, file), join(images_path, new_file))
Perfect job for str.rpartition:
>>> s = "3D_492.png"
>>> start, sep, end = s.rpartition('_')
>>> end
'492.png'
It is guaranteed to return three elements, which sum to the original string. This means you can always get the 2nd element for the "tail":
>>> 'Anniversary_1_Purple_710.png'.rpartition('_')[2]
'710.png'
Putting the pieces together:
import os
os.chdir('\Images')
for old_name in os.listdir('.'):
new_name = old_name.rpartition('_')[2]
if not exists(new_name):
os.rename(old_name, new_name)
Here is one way, using os.path.basename and then str.split to extract characters after the final underscore:
import os
lst = ['3D_492.png', 'Anniversary_1_Purple_710.png']
res = [os.path.basename(i).split('_')[-1] for i in lst]
print(res)
['492.png', '710.png']
Sounds like you just want to split on _ and ignore everything but the last result.
*_, result = fname.split("_")
# or:
# result = fname.split("_")[-1]
Renames are done using os.rename
for fname in fnames: # where fnames is the list of the filenames
*_, new = fname.split("_")
os.rename(fname, new)
Note that if you want to do this with an absolute path (e.g. if fnames looks like ["C:/users/yourname/somefile_to_process_123.png", ...] this will require more processing with os.path.split)
for fpath in fnames:
*dir, basename = os.path.split(fpath)
*_, newname = basename.split("_")
newpath = os.path.join(dir[0], newname)
os.rename(fpath, newpath)
You can use a regular expression to search for the digits preceding the extension.
import re
def update_name(name):
return re.search(r'\d+\..*', name).group()
update_name('3D_492.png') # '492.png'