i'm trying to retrieve images from my local directory using array list but i got all images from list but i don't know how to show images from list one by one.
Please help me if anyone knows.
my.py:
import os, os.path
imgs = []
# print(imgs)
path = "C:/Users/admin/PycharmProjects/my_module/static/files"
valid_images = [".jpg",".gif",".png",".tga"]
print(valid_images)
for f in os.listdir(path):
ext = os.path.splitext(f)[1]
os.listdir(path).append(f)
# Image.show(f)
There are several options depending on your environment and visualization libraries. Check this good answer
You need to do from PIL import Image, then you could do Image.open(path + "/" + f).show(). Try this:
import os, os.path
from PIL import Image
imgs = []
path = "path/to/directory"
valid_images = [".jpg", ".gif", ".png", ".tga"]
print(valid_images)
for f in os.listdir(path):
ext = os.path.splitext(f)[1]
if ext in valid_images:
imgs.append(path + "/" + f)
img = Image.open(path + "/" + f)
img.show()
print(imgs)
I have tried and i got my expected output.
py:
import os
from PIL import Image
img=[]
path="C:/Users/admin/PycharmProjects/my_module/static/files/"
for f in os.listdir(path):
ext = os.path.splitext(f)[1]
os.listdir(path).append(f)
image = Image.open(f)
image.show()
Related
I am going to resize image file which located in Desktop with set of subfolder.
I try following command and it works without rename save new.
from PIL import Image
import os, sys
import glob
root_dir='./././Desktop/python/'
def resize():
for filename in glob.iglob(root_dir + '**/*.jpg', recursive=True):
print(filename)
im = Image.open(filename)
imResize = im.resize((450,600), Image.ANTIALIAS)
imResize.save(filename , 'JPEG', quality=90)
resize()
My question is how can I add the correct command to save the renewe resized image file with append 'f + _thumbnail' + .jpg?
E.g file1 > file1_thumbnail.jpg
I tried add followings to row print(filename) but show error.
f, e = os.path.splitext(path+item)
size = im.size
ratio = float(final_size) / max(size)
new_image_size = tuple([int(x*ratio) for x in size])
im = im.resize(new_image_size, Image.ANTIALIAS)
new_im = Image.new("RGB", (final_size, final_size))
new_im.paste(im, ((final_size-new_image_size[0])//2, (final_size-new_image_size[1])//2))
new_im.save(f + 'resized.jpg', 'JPEG', quality=90)
May I know how can fix it?
Many Thanks
You can use python slicing of strings for this -
You can modify your code to -
from PIL import Image
import os, sys
import glob
root_dir='./././Desktop/python/'
def resize():
for filename in glob.iglob(root_dir + '**/*.jpg', recursive=True):
print(filename)
im = Image.open(filename)
imResize = im.resize((450,600), Image.ANTIALIAS)
filename = filename[:-4] + " _thumbnail" + filename[-4:]
imResize.save(filename , 'JPEG', quality=90)
resize()
The ".jpg" can be sliced at the end.
I am trying to follow a machine learning code the code
and am unsure of why I receive a FileNotFoundError: [Errno 2] No such file or directory: 'new_imgs/0.png' when trying to modify the images. When checking my folders I see the lfw.gz file and the directory with all of the images. Would I need to create a new folder in this case and set that path = to file paths to have the images that are being resized saved? This is the portion of the code that causes the error. Any advice would be great!
url = "http://vis-www.cs.umass.edu/lfw/lfw.tgz"
filename = "lfw.tgz"
directory = "imgs"
new_dir = "new_imgs"
import urllib
import tarfile
import os
import tarfile
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.image import imread
from scipy.misc import imresize, imsave
import tensorflow as tf
%matplotlib inline
if not os.path.isdir(directory):
if not os.path.isfile(filename):
urllib.urlretrieve (url, filename)
tar = tarfile.open(filename, "r:gz")
tar.extractall(path=directory)
tar.close()
filepaths = []
for dir_, _, files in os.walk(directory):
for fileName in files:
relDir = os.path.relpath(dir_, directory)
relFile = os.path.join(relDir, fileName)
filepaths.append(directory + "/" + relFile)
for i, fp in enumerate(filepaths):
img = imread(fp) #/ 255.0
img = imresize(img, (40, 40))
imsave(new_dir + "/" + str(i) + ".png", img)
Currently I am trying to crop all images inside a folder under the address of: C:\\Users\\xie\\Desktop\\tiff\\Bmp and then resave them into the same folder. Below is the code I am trying to experiment with, both run without error but does nothing. Also note I am using windows as platform.
Code 1:
from PIL import Image
import os.path, sys
path = "C:\\Users\\xie\\Desktop\\tiff\\Bmp"
dirs = os.listdir(path)
def crop():
for item in dirs:
if os.path.isfile(path+item):
im = Image.open(path+item)
f, e = os.path.splitext(path+item)
imCrop = im.crop(30, 10, 1024, 1004)
imCrop.save(f + 'Cropped.bmp', "BMP", quality=100)
crop()
Code 2:
for f in os.listdir("C:\\Users\\xie\\Desktop\\tiff\\Bmp"):
for f in ("C:\\Users\\xie\\Desktop\\tiff\\Bmp"):
if f.endswith('.bmp'):
print (f, end=" ")
i = Image.open(f)
area = (30, 10, 1024, 1004)
cropped_i = i.crop(area)
cropped_i.show()
cropped_i.save('Cropped{}.bmp', "BMP", quality=100, optimize=True)
Thanks, any help or suggestions are greatly appreciated!
Code 1 : Corrected
This is your corrected code, you almost had it right, you have to join the path correctly, in your code you weren't adding a separator / between the path and the filename. by using os.path.join you can combine a directory path and a filename.
Furthermore, crop takes a tuple of 4, not 4 arguments.
from PIL import Image
import os.path, sys
path = "C:\\Users\\xie\\Desktop\\tiff\\Bmp"
dirs = os.listdir(path)
def crop():
for item in dirs:
fullpath = os.path.join(path,item) #corrected
if os.path.isfile(fullpath):
im = Image.open(fullpath)
f, e = os.path.splitext(fullpath)
imCrop = im.crop((30, 10, 1024, 1004)) #corrected
imCrop.save(f + 'Cropped.bmp', "BMP", quality=100)
crop()
This is more or less a rough version of code, I used with opencv, it should work the same for PIL also
import glob
import numpy as np
from PIL import Image
image_list = []
for filename in glob.glob('name_of_folder/*.jpg'):
im=Image.open(filename)
image_list.append(im)
a=0
c=[]
for i in range(0,len(image_list)):
#ur image cropping and other operations in here for each image_list[i]
c.append(image_list[i])
c[i].save()
I am extracting RGB channels from images and saving them as grayscale png files, but I have trouble saving them. Here is my code:
listing = os.listdir(path1)
for f in listing:
im = Image.open(path1 + f)
red, green, blue = im.split()
red = red.convert('LA')
green = green.convert('LA')
blue = blue.convert('LA')
red.save(path2 + f + 'r', 'png')
green.save(path2 + f + 'g', 'png')
blue.save(path2 + f + 'b','png')
Where path1 and path2 are image folder and save destinations respectively. What I want to do is to save the b&w version of color channel of img.png to
imgr.png, imgg.png, imgb.png, but what I get with this code is img.pngr, img.pngg, img.pngb. Any help would be appreciated.
You could do this as follows:
import os
listing = os.listdir(path1)
for f in listing:
im = Image.open(os.path.join(path1, f))
red, green, blue = im.split()
red = red.convert('LA')
green = green.convert('LA')
blue = blue.convert('LA')
file_name, file_ext = os.path.splitext(f)
red.save(os.path.join(path2, "{}r.png".format(file_name))
green.save(os.path.join(path2, "{}g.png".format(file_name))
blue.save(os.path.join(path2, "{}b.png".format(file_name))
I would recommend you make use of the os.path.split() and os.path.join() functions when working with paths and filenames.
You first need to split the filename from the extension.
import os
filename = path2 + f # Consider using os.path.join(path2, f) instead
root, ext = os.path.splitext(filename)
Then you can combine them correctly again doing:
filename = root + "r" + ext
Now filename would be imgr.png instead of img.pngr.
I'm learning Python and try to use Pillow to resize images in a folder, then save them to another folder with the same filename. However, the program runs well, when I check the destination folder, there're no images...
My code is as below:
from PIL import Image
import os, glob, sys
src_path = "D:/Test_A/src/*.png"
dst_path = "D:/Test_A/dst/"
img_list = glob.glob(src_path)
for XXPNG in img_list:
fn = os.path.basename(XXPNG)
im = Image.open(XXPNG)
print(fn, im.size)
nim = im.resize((119, 119), Image.ANTIALIAS)
nim.save("dst_path","PNG")
print("Resize Done")
Please help me find my bug, or give my any advise.
Thank you very much for help and bearing my poor English.
"dst_path" with " is a normal text, not variable dst_path - so you save in file with name "dst_path".
You need dst_path without " - plus filename
nim.save(dst_path + fn, "PNG")
or with os.path.join()
nim.save(os.path.join(dst_path, name), "PNG")
Code:
from PIL import Image
import os, glob, sys
src_path = "D:/Test_A/src/*.png"
dst_path = "D:/Test_A/dst/"
img_list = glob.glob(src_path)
for fullpath in img_list:
name = os.path.basename(fullpath)
im = Image.open(fullpath)
print(name, im.size, '=>', os.path.join(dst_path, name))
nim = im.resize((119, 119), Image.ANTIALIAS)
nim.save(os.path.join(dst_path, name), "PNG")
#nim.save(dst_path + name, "PNG")
print("Resize Done")