Import Multiple Images With Unknown Names - image

I need to import multiple images (10.000) in Matlab (2013b) from a subdirectory of the predefined directory of Matlab.
I don't know the exact names of the images.
I tried this:
file = dir('C:\Users\user\Documents\MATLAB\train');
NF = length(file);
for k = 1 : NF
img = imread(fullfile('C:\Users\user\Documents\MATLAB\train', file(k).name));
end
But it throws this error though I ran it with the Admin privileges:
Error using imread (line 347)
Can't open file "C:\Users\user\Documents\MATLAB\train\." for reading;
you may not have read permission.

The "dir" command returns the virtual directory elements "." (self directory) and ".." parent, as your error message shows.
A simple fix is to use a more specific dir call, based on your image types, perhaps:
file = dir('C:\Users\user\Documents\MATLAB\train\*.jpg');

Check the output of dir. The first two "files" are . and .., which is similar to the behaviour of the windows dir command.
file = dir('C:\Users\user\Documents\MATLAB\train');
NF = length(file);
for k = 3 : NF
img = imread(fullfile('C:\Users\user\Documents\MATLAB\train', file(k).name));
end

In R2013b you would have to do
file = dir('C:\Users\user\Documents\MATLAB\train\*.jpg');
If you have R2014b with the Computer Vision System Toolbox then you can use imageSet:
images = imageSet('C:\Users\user\Documents\MATLAB\train\');
This will create an object containing paths to all image files in the train directory, regardless of format. Then you can read the i-th image like this:
im = read(images, i);

Related

How do I access uigetfile elements via a loop?

I have to perform the following steps on set of images via matlab GUI:
Read multiple images from directory
Process them (Apply imadjust on each image)
Store them in user specified or same directory while renaming them
Can someone kindly provide me the code for the same? I am stuck after this:
[filename, pathname,~] = uigetfile( ...
{'*.jpg;*.jpeg;',...
'JPEG Files (*.jpg,*.jpeg)';
'*.png', 'PNG files (*.png)'; ...
'*.bmp','BMP File (*.bmp)'; ...
'*.tiff;*.tif','TIFF Files (*.tiff,*.tif)'; ...
'*.*', 'All Files (*.*)'}, ...
'Pick a file',...
'Multiselect','on');
set(handles.inputpathtext,'String',pathname);
[file_name_list, pathname] = uigetfile({'your filter spec','Multiselect','on');
The line above should give you a cell array containing the names of the files you selected. The following code loops through the cell array, read image, perform some adjustement, and save them with 'processed_' prefix added to the file name in the same folder specified by pathname.
for ii = 1:length(file_name_list)
if iscell(file_name_list)
filename = file_name_list{ii};
else
filename = file_name_list;
end
img = imread(fullfile(pathname, filename));
img = imadjust(img); % Do something to the image
imwrite(img, fullfile(pathname, ['processed_', filename])
end

How to read the latest image in a folder using python?

I have to read the latest image in a folder using python. How can I do this?
Another similar way, with some pragmatic (non-foolproof) image validation added:
import os
def get_latest_image(dirpath, valid_extensions=('jpg','jpeg','png')):
"""
Get the latest image file in the given directory
"""
# get filepaths of all files and dirs in the given dir
valid_files = [os.path.join(dirpath, filename) for filename in os.listdir(dirpath)]
# filter out directories, no-extension, and wrong extension files
valid_files = [f for f in valid_files if '.' in f and \
f.rsplit('.',1)[-1] in valid_extensions and os.path.isfile(f)]
if not valid_files:
raise ValueError("No valid images in %s" % dirpath)
return max(valid_files, key=os.path.getmtime)
Walk over the filenames, get their modification time and keep track of the latest modification time you found:
import os
import glob
ts = 0
found = None
for file_name in glob.glob('/path/to/your/interesting/directory/*'):
fts = os.path.getmtime(file_name)
if fts > ts:
ts = fts
found = file_name
print(found)

Strict searching against two different files

I have two questions regarding the following code:
import subprocess
macSource1 = (r"\\Server\path\name\here\dhcp-dump.txt")
macSource2 = (r"\\Server\path\name\here\dhcp-dump-ops.txt")
with open (r"specific-pcs.txt") as file:
line = []
for line in file:
pcName = line.strip().upper()
with open (macSource1) as source1, open (macSource2) as source2:
items = []
for items in source1:
if pcName in items:
items_split = items.rstrip("\n").split('\t')
ip = items_split[0]
mac = items_split[4]
mac2 = ':'.join(s.encode('hex') for s in mac.decode('hex')).lower() # Puts the :'s between the pairs.
print mac2
print pcName
print ip
Firstly, as you can see, the script is searching for the contents of "specific-pcs.txt" against the contents of macSource1 to get various details. How do I get it to search against BOTH macSource1 & 2 (as the details could be in either file)??
And secondly, I need to have a stricter matching process as at the moment a machine called 'itroom02' will not only find it's own details, but also provide the details for another machine called '2nd-itroom02'. How would I get that?
Many thanks for your assistance in advance!
Chris.
Perhaps you should restructure it a bit more like this:
macSources = [ r"\\Server\path\name\here\dhcp-dump.txt",
r"\\Server\path\name\here\dhcp-dump-ops.txt" ]
with open (r"specific-pcs.txt") as file:
for line in file:
# ....
for target in macSources:
with open (target) as source:
for items in source:
# ....
There's no need to do e.g. line = [] immediately before you do for line in ...:.
As far as the "stricter matching" goes, since you don't give examples of the format of your files, I can only guess - but you might want to try something like if items_split[1] == pcName: after you've done the split, instead of the if pcName in items: before you split (assuming the name is in the second column - adjust accordingly if not).

'File path' use causing program exit in Python 3

I have downloaded a set of html files and saved the file paths which I saved them to in a .txt file. It has each path on a new line. I wanted to look at the first file in the list and then itterate through the whole list, opening the files and extracting data before going on to the next file.
My code works fine with a single path put in directly (for the first file) as:
path = r'C:\path\to\file.html'
and works if I itterate through the text file using:
file_list_fp = r'C:\path\to\file_with_pathlist.txt'
with open(file_list_fp, 'r') as file_list:
for filepath in file_list:
pathend = filepath.find('\n')
path = file[:pathend]
q = open(path, 'r').read()
but it fails when I try getting a single path using either:
with open(file_list_fp, 'r') as file_list:
path_n = file_list.readline()
end = path_n.find('\n')
path_bad1 = path_n[:end]
or:
with open(file_list_fp, 'r') as file_list:
path_bad2 = file_list.readline().split('\n')[0]
With these two my code exits just after that point. I can't figure out why. Any pointers very welcome. (I'm using Python 3.3.1 on windows.)

Cannot open file for output (Matlab)

I am having a problem in matlab and the problem is described as follows:
When i try to read an image ( I have several images) and write them to a specific folder, the matlab triggers an error saying
Error using ==> imwrite at 394
Can't open file "\Temp\\inim735282.4716703009300000.jpg" for writing.
You may not have write permission.
May I know why this is happening?
this is the code where the problem occurs
mkdir('.\Temp');
temp_name = sprintf('%.16f',now);
corner_file = ['\Temp\corners', temp_name,'.in'];
image_file = ['\Temp\inim', temp_name,'.jpg'];
out_file = ['\Temp\out', temp_name,'.desc'];
out_imname = ['\Temp\out', temp_name,'.desc.jpg'];
I tried to change it by omitting
mkdir('.\Temp');
moreoever, i direct the path in the folder to the folder by doing this
binary_path = 'C:\Users\cool\Documents\MATLAB\Experment\experiments\bag_of_words\Temp';
to read and and write in and out of the folder.
Can someone please help me figure out this problem?
Thank you guys
Open MatLAB with admin privileges.
A few suggestions:
To generate a temporary output name use the command tempname.
temp_name = tempname();
To concatenate paths and file names use fullfile.
conrner_file = fullfile( '\', 'Temp', 'corners', [temp_name, '.in'] );
You should be careful not to mix '\Temp' and '.\Temp': as the first is an absolute path, while the second is a relative path to cwd.
EDIT:
How about:
temp_name = tempname(); % temp name + folder name in TEMP
corner_file = [ temp_name,'.in'];
image_file = [ temp_name,'.jpg'];
out_file = [temp_name,'.desc'];
out_imname = [temp_name,'.desc.jpg'];
Is it working now?

Resources