How do I access uigetfile elements via a loop? - image

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

Related

Python: Opening auto-generated file

As part of my larger program, I want to create a logfile with the current time & date as part of the title. I can create it as follows:
malwareLog = open(datetime.datetime.now().strftime("%Y%m%d - %H.%M " + pcName + " Malware scan log.txt"), "w+")
Now, my app is going to call a number of other functions, so I'll need to open the file, write some output to it and close the file, several times. It doesn't seem to work if I simply go:
malwareLog.open(malwareLog, "a+")
or similar. So how should I open a dynamically created txt file that I don't know the actual filename for...?
When you create malwareLog object, it has name attribute which contains the file name.
Here's an example: (my test is your malwareLog)
import random
test = open(str(random.randint(0,999999))+".txt", "w+")
test.write("hello ")
test.close()
test = open(test.name, "a+")
test.write("world!")
test.close()
with open(test.name, "r") as f: print(f.read())
You also can store the file name in a variable before or after creating the file.
###Before
file_name = "123"
malwareLog = open(file_name, "w")
###After
malwareLog = open(random.randint(0,999999), "w")
file_name = malwareLog.name

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).

Import Multiple Images With Unknown Names

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);

'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