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)))
Related
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")
I have a folder with a .txt files. the name of the files are:
my_file1.txt
my_file2.txt
my_file3.txt
my_file4.txt
In this way, only the last number is different.
import pickle
my_list = []
with open("/Users/users_a/Desktop/website-basic/sub_domain/sub_domain01.txt", "rb") as f1,
open("/Users/users_a/Desktop/website-ba\
sic/sub_domain/sub_domain02.txt", "rb") as f2, open("/Users/users_a/Desktop/website-
basic/sub_domain/sub_domain03.txt", "rb") as f3:
my_list.append(pickle.load(f1))
my_list.append(pickle.load(f2))
my_list.append(pickle.load(f3))
print(my_list)
In this way, I load a file and put it in the my_list variable to make a list and work. As the number of files to work increases, the code becomes too long and cumbersome.
Is there an easier and more pythonic way to load only the desired txt file??
You can use os.listdir():
import os
import pickle
my_list = []
path = "/Users/users_a/Desktop/website-basic/sub_domain"
for file in os.listdir(path):
if file.endswith(".txt"):
with open(f"{path}/{file}","r") as f:
my_list.append(pickle.load(f))
Where file is the filename of a file in path
I suggest using os.path.join() instead of hard coding the file paths
If your folder only contains the files you want to load you can just use:
for file in os.listdir(path):
with open(f"{path}/{file}","r") as f:
my_list.append(pickle.load(f))
Edit for my_file[number].txt
If you only want files in the form of my_file[number].txt, use:
import os
import re
import pickle
my_list = []
path = "/Users/users_a/Desktop/website-basic/sub_domain"
for file in os.listdir(path):
if re.match(r"my_file\d+.txt", file):
with open(f"{path}/{file}","r") as f:
my_list.append(pickle.load(f))
Online regex demo https://regex101.com/r/XJb2DF/1
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.
I want to copy all the pictures from one folder to another folder. I tried to run this code again and again but it returns me False only instead of saving pictures to other folder.
import cv2
import glob
input_path = 'C:\\Users\\Kazmi-PC\\OneDrive\\Pictures\\1\\*.*'
output_path = 'C:\\Users\\Kazmi-PC\\OneDrive\\Pictures\\2\\*.jpg'
for file in glob.glob(input_path):
print("printing.....")
print(file)
a= cv2.imread(file)
cv2.imwrite(output_path, a)
You can't use * in output filename. You would have to use imwrite inside for loop and use unique filenames in output.
You can use shutil.copy(file, directory) to copy. So you can use output without *.jpg and you don't have to add filename in output.
But you still need to copy every file separatelly.
import glob
import shutil
input_path = 'C:\\Users\\Kazmi-PC\\OneDrive\\Pictures\\1\\*.*'
output_dir = 'C:\\Users\\Kazmi-PC\\OneDrive\\Pictures\\2\\'
for file in glob.glob(input_path):
shutil.copy(file, output_dir)
I have a folder image (JPGE_Image) that contains jpg images as follows:
1.jpg
2.jpg
3.jpg
...
100.jpg
I have other text file which contains the path of these selected jpeg images (not all images, just selected as 1.jpg, 3.jpg...) as
/home/users/JPGE_Image/1.jpg
/home/users/JPGE_Image/3.jpg
/home/users/JPGE_Image/5.jpg
...
/home/users/JPGE_Image/99.jpg
I want to copy selected image in the text file to other folder named Selected_Folder. How could I do it in python 2.7. Thank all. This is what I tried, but it does not get information from text file
import os
import shutil
srcfile = '/home/users/JPGE_Image/1.jpg'
dstroot = '/home/users/Selected_Folder'
assert not os.path.isabs(srcfile)
dstdir = os.path.join(dstroot, os.path.dirname(srcfile))
os.makedirs(dstdir) # create all directories, raise an error if it already exists
shutil.copy(srcfile, dstdir)
You can read the paths from txt file line by line, like this:
with open(txtfile_path) as f:
for srcfile in f:
shutil.copy(srcfile, dstdir)
You just need to apply your logic on a line by line basis as follows:
import os
import shutil
text_file_list = 'my_text_file.txt'
dstroot = '/home/users/Selected_Folder'
try:
os.makedirs(dstroot)
except OSError as e: # catch exception if folder already exists
pass
with open(text_file_list) as f_input:
for srcfile_path in f_input:
srcfile_path = srcfile_path.strip()
srcfile = os.path.split(srcfile_path)[1]
dstdir = os.path.join(dstroot, srcfile)
shutil.copy(srcfile_path, dstdir)
As you read each line, use strip() to remove the trailing newline. Then use os.path.split() to get just the filename of the source. This can then be joined to your dstdir.