I want to read multiple .jpg images, that are in 3 separate folders. The 3 folders are on the same path. I tried to do it like this:
path1 = os.path.abspath('Type_1')
path2 = os.path.abspath('Type_2')
path3 = os.path.abspath('Type_3')
folder = os.path.join(path1, path2, path3)
def load_images_from_folder(folder):
images = []
for filename in os.listdir(folder):
if filename.endswith(".jpg"):
img = cv2.imread(os.path.join(folder, filename))
if img is not None:
images.append(img)
return images
print(load_images_from_folder(folder))
But it only returns the last path and not all of them. I also tried to use relative paths, such as:
path1 = os.path.relpath('Type_1')
path2 = os.path.relpath('Type_2')
path3 = os.path.relpath('Type_3')
folder = os.path.join(os.path.sep, path1, path2, path3)
but still the same problem. Can someone help with this?
Your return images line is inside your loop, so it will return as soon as it finds any matching result. You only want it to return after the whole loop as finished.
Reduce the indentation of the return statement so that it lies after the loop instead of inside it.
def load_images_from_folder(folder):
images = []
for filename in os.listdir(folder):
if filename.endswith(".jpg"):
img = cv2.imread(os.path.join(folder, filename))
if img is not None:
images.append(img)
return images
[Edit]
If you want to look in multiple adjacent folders, you want something like this:
root_folder = '[whatever]/data/train'
folders = [os.path.join(root_folder, x) for x in ('Type_1', 'Type_2', 'Type_3')]
all_images = [img for folder in folders for img in load_images_from_folder(folder)]
That will call load_images on each folder, and put all the results into one list.
If I understand the problem correctly, your file structure looks as follows:
- Type1
- Image1.jpg
- Image2.jpg
- Type2
- Image1.jpg
- Image2.jpg
- Type3
- Image1.jpg
- Image2.jpg
If this is true, then the os.path.join call is errant (it'll result in a string that reads "Type1/Type2/Type3" which achieves nothing for you).
I think the code you're looking for is as follows:
def load_images_from_folder(folder):
images = []
for filename in os.listdir(folder):
if any([filename.endswith(x) for x in ['.jpeg', '.jpg']]):
img = cv2.imread(os.path.join(folder, filename))
if img is not None:
images.append(img)
return images
folders = [
'Type1',
'Type2',
'Type3',
]
for folder in folders:
images = load_images_from_folder(folder)
# your code that does something with the return images goes here
I know this is really old, but this worked for me recently.
def create_dataset(img_folder):
img_data_array=[]
class_name=[]
for dirl in os.listdir(img_folder):
for file in os.listdir(os.path.join(img_folder,dirl)):
if any([file.endswith(x) for x in ['.jpeg', '.jpg']]):
image_path=os.path.join(img_folder,dirl,file)
image=cv2.imread(image_path,cv2.COLOR_BGR2RGB)
img_data_array.append(image)
class_name.append(dirl)
return img_data_array,class_name
img_data, class_name =create_dataset(train_folder)
Related
I copy the images from the source folder to destination folder using shutil.copy() Then I rename the folder using os.rename. However, there is a problem. So if the destination folder is empty, then I will get the image that I copy from source folder and os.rename will rename the images. But once the new images from source folder comes in, it will rename again the image that already rename. For example, after I rename the image, it will be 1_01_411.jpeg. But once it runs again, it will be 1_01_411_412.jpeg as it is in while loop.
I will attach the image that shows the issue.
While True:
src = "/home/pi/Pictures/JB_CAM/"
dest = "/home/pi/windowshare/"
par ="*"
i=1
d = []
for file in glob.glob(os.path.join(src,par)):
f = str(file).split('\\')[-1]
for n in glob.glob(os.path.join(dest,par)):
d.append(str(n).split('\\')[-1])
if f not in d:
print("copied",f," to ",dest)
shutil.copy(file,dest)
else:
f1 = str(f).split(".")
f1 = f1[0]+"_"+str(i)+"."+f1[1]
while f1 in d:
f1 = str(f).split(".")
f1 = f1[0]+"_"+str(i)+"."+f1[1]
print("{} already exists in {}".format(f1,dest))
i =i + 1
shutil.copy(file,os.path.join(dest,f1))
print("renamed and copied ",f1 ,"to",dest)
i = 1
os.getcwd()
collection = "/home/pi/windowshare"
dest = "/home/pi/windowshare/"
for i, filename in enumerate(os.listdir(collection)):
os.rename(dest + filename, dest + filename.split(".")[0] +"_"+ db_sn+ ".jpeg)
I also use OpenCV to test.
src ="/home/pi/Pictures/JB_CAM/"
for img in os.listdir(src):
name,ext = os.path.splitext(img)
if ext ==".jpeg":
f1 = cv2.imread('/home/pi/Pictures/JB_CAM/'+img)
print(f1)
#status =cv2.imwrite("/home/pi/windowshare/"+img.split(".")[0]+"_"+"%d.jpeg" % db_sn,f1)
cv2.imwrite("/home/pi/windowshare/"+img.split(".")[0]+"_"+"%d.jpeg" % db_sn,f1)
However, the problem with this approach is it overwrites the db_sn value to the all the images. The goal is to copy or write(save) the files from source to destination folder and rename according to db_sn(serial number).
I am adjusting a script.
I have 4427 images in a specified folder, named
(1).png
(2).png
(3).png
etc.
Along with those, I have another 14 images, named:
1.png
2.png
3.png
etc.
Basically the script should:
Take a specific image I tell it to open of the 4427
Then, open one of the 14 images at random
Merge the two and save it to a specified directory.
Code
import os
import random
from PIL import Image
path = r"C:\Users\17379\Desktop\images\Low effort glasses"
random_filename = random.choice([
x for x in os.listdir(path)
if os.path.isfile(os.path.join(path, x))
])
print(random_filename)
x = Image.open(r"(1).png").convert("RGBA")
y = Image.open(random_filename)
z = Image.alpha_composite(x, y)
z.save(r"C:\Users\17379\Desktop\images\Resized punks\Resized punks\punk1.png")
How to do this to all 4427 images and then save each file to the specified directory?
The pseudo-code for your task is:
for file_name in source_image_list:
# 1. Take a specific image I tell it to open of the 4427
source_image = open_source(file_name)
# 2. Then, open one of the 14 images at random
random_image = open_random_of(random_image_list)
# 3. Merge the two and save it to a specified directory.
target_image = merge(source_image, random_image)
save(target_image, file_name, directory)
Translate this to Python:
import os
import glob
import random
from PIL import Image
def open_random(random_image_list):
random_filename = random.choice(in random_image_list)
print(f"Random: {random_filename}")
return Image.open(random_filename)
def open_source(file_name):
return Image.open(file_name).convert("RGBA")
def merge(source, random):
return Image.alpha_composite(source, random)
def save(image, original_name, directory):
target = os.path.join(directory, os.path.basename(original_name))
print(f"Saving: {target}")
image.save(target)
if __name__ == '__main__':
source_path = r"C:\Users\17379\Desktop\images"
random_path = r"C:\Users\17379\Desktop\images\Low effort glasses"
directory = r"C:\Users\17379\Desktop\images\Resized punks\Resized punks"
random_image_list = os.listdir(random_path) # can also use glob here to filter for (specific) images only
source_image_list = glob.glob(f"{source_path}/\([0-9]+\).png")
for file_name in source_image_list:
print(f"Source: {file_name}")
# 1. Take a specific image I tell it to open of the 4427
source_image = open_source(file_name)
# 2. Then, open one of the 14 images at random
random_image = open_random_of(random_image_list)
# 3. Merge the two and save it to a specified directory.
target_image = merge(source_image, random_image)
save(target_image, file_name, directory)
Note: I had to replace os.listdir(source_path) for glob.glob because it accepts a regular-expression to filter for specific files only. See also
Python3 create list of image in a folder
I'm trying to create a script that changes the contrast and sharpness of all the images in a folder, and save it to a new folder as filename_edited.jpg
I'm using pythong 3.7, importing os and PIL. I have a folder with some images - DJI_001.jpg, DJI_002.jpg and so forth. The folder with the images is called test.
The folder I want them to go to is called 'novo' in ..\test\novo
Initially I had this. It works, but it saves the images in the same folder:
import PIL
from PIL import Image, ImageEnhance
import os.path, sys
path = "C:\\Users\\r o d r i g o\\Desktop\\001 - progamer\\98 - Image brightness\\test"
dirs = os.listdir(path)
def teste():
for item in dirs:
fullpath = os.path.join(path,item)
if os.path.isfile(fullpath):
img = Image.open(fullpath)
f, e = os.path.splitext(fullpath)
sharpness = ImageEnhance.Sharpness(img)
sharp = sharpness.enhance(10.0)
newimg = sharp
contrast = ImageEnhance.Contrast(newimg)
cont = contrast.enhance(2.3)
head, tail = os.path.split(fullpath)
cont.save(f + "_edited.jpg")
teste()
So after some research I tried to split fullpath in head and tail. The tail variable gets me the file name.
I did this so each time it looped, It could save to the filepath of my new folder + tail.
So I tried this:
def sha():
for item in dirs:
fullpath = os.path.join(path,item)
if os.path.isfile(fullpath):
img = Image.open(fullpath)
#f, e = os.path.splitext(fullpath) #don't need this here
sharpness = ImageEnhance.Sharpness(img)
sharp = sharpness.enhance(10.0)
newimg = sharp
contrast = ImageEnhance.Contrast(newimg)
cont = contrast.enhance(2.3)
head, tail = os.path.split(fullpath)
cont.save("C:\\Users\\r o d r i g o\\Desktop\\001 - progamer\\98 - Image brightness\\test\\novo" + tail)
print("this is the filepath: " + head)
print("this is the filename: " + tail)
sha()
I thought this would work, but it saves the files on the same directory, as novoDJI_001.jpg, novoDJI_002.jpg and so forth.
I added a couple images if it helps:
Saving in the same folder
and
Trying to save on a new folder
So, on my second attempt (more like 20th but well), as you can see I inerted the filepath, but the new folder called novo, in \test\novo ended up in the file name.
Any help is greatly appreciated, I'm sure this is simple but I've spent the last 5 hours on this, but I can't find why it does this! Thank you!
There's no path separator in this line betweeen "novo" and tail:
cont.save("C:\\Users\\r o d r i g o\\Desktop\\001 - progamer\\98 - Image brightness\\test\\novo" + tail)
Please, replace it with something like this:
cont.save("C:\\Users\\r o d r i g o\\Desktop\\001 - progamer\\98 - Image brightness\\test\\novo\\" + tail) // '\\' added after 'novo'
or you may use this as well:
new_name = os.path.join( head, "novo", tail )
cont.save( new_name )
I have a folder with images of dogs, named dogID-X.jpg where X is the number of the picture that belongs to one dogID, e.g. 0a08e-1.jpg, 0a08e-2.jpg, 0a08e-3.jpg means there are three images that belong to the same dog.
How do I sort these images into two subfolders based on two lists that have only the dogID [0a08e, 4a45t, ...] i.e. all images with IDs from one list should go to one folder, and all images from another list should go into the other folder. Thanks! The list looks like this: list(y_labels) = ['86e1089a3',
'6296e909a',
'5842f1ff5',
'850a43f90',
'd24c30b4b',
'1caa6fcdb', ...]
for image in list(y_labels):
folder = y_labels.loc[image, 'PetID']
old = './train_images/{}'.format(image)
new = '//train_images_new/{}/{}'.format(folder, image)
try:
os.rename(old, new)
except:
print('{} - {}'.format(image,folder))
Well let's assume you have lis1 and lis2 as 2 lists containing only dogID, there is also a folder which contains all the images and I'll call it "mypath", sub folders will be named "lis1" and "lis2".
import os
# path to image folder, get all filenames on this folder
# and store it in the onlyfiles list
mypath = "PATH TO IMAGES FOLDER"
onlyfiles = [f for f in os.listdir(mypath) if os.path.isfile(os.path.join(mypath, f))]
# your list of dogID's
lis1 = ["LIST ONE"]
lis2 = ["LIST TWO"]
# create two seperate lists from onlyfiles list based on lis1 and lis2
lis1files = [i for i in onlyfiles for j in lis1 if j in i]
lis2files = [i for i in onlyfiles for j in lis2 if j in i]
# create two sub folders in mypath folder
subfolder1 = os.path.join(mypath, "lis1")
subfolder2 = os.path.join(mypath, "lis2")
# check if they already exits to prevent error
if not os.path.exists(subfolder1):
os.makedirs(subfolder1)
if not os.path.exists(subfolder2):
os.makedirs(subfolder2)
# move files to their respective sub folders
for i in lis1files:
source = os.path.join(mypath, i)
destination = os.path.join(subfolder1, i)
os.rename(source, destination)
for i in lis2files:
source = os.path.join(mypath, i)
destination = os.path.join(subfolder2, i)
os.rename(source, destination)
I hope it solves your problem.
import os
import shutil
path = r'C:\Users\user\temp\test\dog_old' #folder where all dog images present
list_name =[]
# traverse root directory, and list directories as dirs and files as files
for root, dirs, files in os.walk(path):
list_name.extend(files)
from collections import defaultdict
dic=defaultdict(list)
for i in list_name:
filename,ext =os.path.splitext(i)
group, img_index = filename.split('-')
dic[group].append(img_index)
# folder path where new dog images had to added
new_folder = r'C:\Users\user\temp\test\dog_new'
for i in dic:
if not os.path.exists(os.path.join(new_folder,i)):
os.mkdir(os.path.join(new_folder,i))
for img in dic[i]:
old_image = os.path.join(path,'{}-{}.jpg'.format(i,img))
new_image = r'{}.jpg'.format(img)
new_path =os.path.join(new_folder,i)
shutil.move(old_image,os.path.join(new_path,new_image))
else:
for img in dic[i]:
old_image = os.path.join(path,'{}-{}.jpg'.format(i,img))
new_image = r'{}.jpg'.format(img)
new_path =os.path.join(new_folder,i)
print(new_path)
shutil.move(old_image,os.path.join(new_path,new_image))
Try this,
import os
pet_names = ['0a08e', '0a08d']
image_ids = ["0a08e-1.jpg", "0a08e-2.jpg", "0a08e-3.jpg","0a08d-1.jpg", "0a08d-2.jpg", "0a08d-3.jpg"]
image_folder_path = os.getcwd()#"<image folder path>"
# assuming you want to name the folder with the pet name, create folders with the names in the list.
for pet_name in pet_names:
if not os.path.exists(os.path.join(image_folder_path,pet_name)):
print("creating")
os.makedirs(pet_name)
# loop over the image id's match the pet name and put it in the respective folder
for img_id in image_ids:
for pet_name in pet_names:
if pet_name in img_id:
image_full_path_source = os.path.join(image_folder_path,img_id)
dest_path = os.path.join(image_folder_path,pet_name)
image_full_path_destination = os.path.join(dest_path,img_id)
os.rename(image_full_path_source, image_full_path_destination)
Hope it helps!
Images is a folder which have 10 more sub folders and every sub folder have one image which i am resizing and saving on same place but os.walk is not working can anyone check what i did wrong.
path='E:/Dataset_Final/Images/'
def count_em(path):
for root, dirs, files in sorted(os.walk(path)):
for file_ in files:
full_file_path = os.path.join(root, file_)
print (full_file_path)
img = Image.open(full_file_path)
new_width = 32
new_height = 32
img = img.resize((new_width, new_height), Image.ANTIALIAS)
img.save(os.path.join(root, file_+''),'png')
return
count_em(path)
You return after the first directory.
Remove the return statement and your code should work as expected.