How can I read image name from a specific folder? - python

I want read image name like flower.png unnamed.png. Is there any way that I can read all images images one by one like we can read text file with open ("data.txt", "r") as myfile:
data = myfile.read().splitlines().. Hope you will give me a solution
thanks
enter code here from PIL import Image
import glob
image_list = []
for filename in glob.glob('yourpath/*.img'):
im=Image.open(filename)
image_list.append(im)

If you want to get all file name from a folder, you can use os.listdir
import os
filename = os.listdir("YOUR_FOLDER_NAME")

Related

Python: JPEGs from folder to a Multipage-PDF with img2pdf

I'm an newbie and I'm trying to create a multipage pdf with img2pdf (recursive), but only the last picture is saved in a pdf file.
from pathlib import Path
import os
import img2pdf
main_dir = Path(Path.cwd(),'MAIN')
for subfolder in main_dir.iterdir():
if subfolder.is_file():
continue
for filename in subfolder.iterdir():
#pdf as foldername
pdf_name = os.path.basename(subfolder)
#write image-file to pdf file
with open(pdf_name+".pdf", "wb") as f:
f.write(img2pdf.convert(str(filename)))
When I test it with print(filename) all images are going through the loop.
Maybe someone can tell me where my misconception is.
img2pdf module can directly take a list of image file names as an argument and converts them into pdf. Take a look at the documentation here
from pathlib import Path
import os
import img2pdf
main_dir = Path(Path.cwd(),'your/path/to/images/folder')
for subfolder in main_dir.iterdir():
imgs = []
if subfolder.is_file():
continue
for filename in subfolder.iterdir():
imgs.append(os.path.join(subfolder, filename))
pdf_name = os.path.basename(subfolder)
with open(pdf_name+".pdf", "wb") as f:
f.write(img2pdf.convert(imgs))

How to get and change file name to time timestamps from image(png or jpg)?

How to get and change file name to time timestamps from image(png or jpg) in same directory with python?
And I want to make a list of that files without file extension in text file.
This will give you the timestamp of image
from PIL import Image
def get_date_taken(path):
return Image.open(path).getexif()[36867]
This will change the filename
import os
os.rename(r'file path\OLD file name.file type',r'file path\NEW file name.file type')
And finally you can find all images with this code
from os import walk
f = []
for (dirpath, dirnames, filenames) in walk(mypath):
f.extend(filenames)
break
Try to combine all of these codes.

Converting all files (.jpg to .png) from a directory in Python

I'm trying to convert all files from a directory from .jpg to .png. The name should remain the same, just the format would change.
I've been doing some researches and came to this:
from PIL import Image
import os
directory = r'D:\PATH'
for filename in os.listdir(directory):
if filename.endswith(".jpg"):
im = Image.open(filename)
im.save('img11.png')
print(os.path.join(directory, filename))
continue
else:
continue
I was expecting the loop to go through all my .jpg files and convert them to .png files. So far I was doing only with 1 name: 'img11.png', I haven't succed to build something able to write the adequate names.
The print(os.path.join(directory, filename)) works, it prints all my files but concerning the converting part, it only works for 1 file.
Do you guys have any idea for helping me going through the process?
You can convert the opened image as RGB and then you can save it in any format.
You can try the following code :
from PIL import Image
import os
directory = r'D:\PATH'
c=1
for filename in os.listdir(directory):
if filename.endswith(".jpg"):
im = Image.open(filename)
name='img'+str(c)+'.png'
rgb_im = im.convert('RGB')
rgb_im.save(name)
c+=1
print(os.path.join(directory, filename))
continue
else:
continue
You're explicitly saving every file as img11.png.
You should get the name of your jpg file and then use that to name and save the png file.
name = filename[:-4]
im.save(name + '.png')
I would have used os.rename() function like below.
import os
directory = r'D:\PATH'
for filename in os.listdir(directory):
prefix = filename.split(".jpg")[0]
os.rename(filename, prefix+".png")
Please let me know if this is what you wanted. Try the code with some copied images inside a test folder, before applying to the intended folder. All the best.
from PIL import Image
import os
directory = r'D:\PATH'
for filename in os.listdir(directory):
if filename.endswith(".jpg"):
prefix = filename.split(".jpg")[0]
im = Image.open(filename)
im.save(prefix+'.png')
else:
continue
Please try this one and let me know.

Open images from a folder one by one using python?

Hi all I need to open images from a folder one by one do some processing on images and save them back to other folder. I am doing this using following sample code.
path1 = path of folder of images
path2 = path of folder to save images
listing = os.listdir(path1)
for file in listing:
im = Image.open(path1 + file)
im.resize((50,50)) % need to do some more processing here
im.save(path2 + file, "JPEG")
Is there any best way to do this?
Thanks!
Sounds like you want multithreading. Here's a quick rev that'll do that.
from multiprocessing import Pool
import os
path1 = "some/path"
path2 = "some/other/path"
listing = os.listdir(path1)
p = Pool(5) # process 5 images simultaneously
def process_fpath(path):
im = Image.open(path1 + path)
im.resize((50,50)) # need to do some more processing here
im.save(os.path.join(path2,path), "JPEG")
p.map(process_fpath, listing)
(edit: use multiprocessing instead of Thread, see that doc for more examples and information)
You can use glob to read the images one by one
import glob
from PIL import Image
images=glob.glob("*.jpg")
for image in images:
img = Image.open(image)
img1 = img.resize(50,50)
img1.save("newfolder\\"+image)

Loading multiple images from a text file

I have got 40 images,and I have written their names in a text file. Now I want to call those images one by one in my program,using that text file (in Python).
I have used glob to find all image names,(instead of text file).
glob list contains of names like that:
img=['image0.jpg','image1.jpg',....]
Now If I access any image like img[0],img[1] it is just image0.jpg not 'image0.jpg',
so I have got trouble loading using opencv function to load it.
I want to load it like
cv.LoadImage('image0.jpg')
If your file contains the fully-qualified names of the files. You can do the following
import cv
with open('textFileOfImages.txt','rb') as f:
img = [line.strip() for line in f]
#load the images at you leisure
for image in img:
loadedImage = cv.LoadImage(image)
#manipulate image
If your file contains the relative path from the current working directory then:
import os
import cv
with open('textFileOfImages.txt','rb') as f:
img = ['%s/%s'%(os.getcwd(),line.strip()) for line in f]
Or if your file contains the relative path from directory the current script is running
import os
import cv
with open('textFileOfImages.txt','rb') as f:
img = ['%s/%s'%(os.path.dirname(os.path.abspath(__file__)),line.strip()) for line in f]
Edit
If you need to load image names from multiple files you can easily incorporate this.
Assuming you have the list of file names, then the easiest way is to loop outside the with statement.
listOfFilenames = ['filename1.txt','filename2.txt','filename3.txt']
for filename in listOfFilenames:
with open(filename,'rb') as f:
...
Try using
for _file in img:
cv.LoadImage("{0}".format(_file))
if your file is in other directory,
import os
for _file in img:
cv.LoadImage("{0}".format(os.path.join(directory, _file)))

Categories

Resources