Save converted image into specific path in matlab? - image

Can someone explain to me how to save our converted image (from *.ppm into *.pgm) in specific directory in matlab..
Here is my code.
pathName = 'D:\Matlab\Training\PGM_Files';
% Create it if it doesn't exist.
if ~exist(pathName, 'dir')
mkdir(pathName);
% This will create to the full depth of the path.
% Upper folder levels don't have to exist yet.
end
fullFileName = fullfile(pathName);
pgm_File_Images(loop1,1)=imwrite((Train_Images,['data',num2str(loop1),'.pgm']),
fullFileName);
I want to save all my file into folder PGM_Files.
But everytime I got error
Expression or statement is incorrect--possibly unbalanced (, {, or [.
How to fix it??

The answer was already given in the comments, I will thus post it here to make sure the question does not remain unanswered:
You don't provide the right kind of input arguments to imwrite. That's
why the last ) claims to be unmatched.

Related

Tensorflow’s flow_from_directory returns erroneous Set

I am using ImageDataGenerator to create validation set ( for an image classification using TF (Keras) from a labeled directory of images. The directories are 0,1,2,3,4 corresponding to class of each image, they contain 488, 185, 130, 131, 91 images respectively.
train_image_generator = ImageDataGenerator(rescale=1./255) # Generator for our training data
# validation_image_generator = ImageDataGenerator(rescale=1./255) # Generator for our validation data
train_data_gen = train_image_generator.flow_from_directory(batch_size=batch_size,
directory=train_dir,
shuffle=True,
target_size=(IMG_HEIGHT, IMG_WIDTH),
class_mode='categorical')
returns
Found 0 images belonging to 5 classes.
and the code below
validation_data_generator = train_image_generator.flow_from_directory(
train_dir, # same directory as training data
target_size=(IMG_HEIGHT, IMG_WIDTH),
batch_size=batch_size,
class_mode='categorical',
subset='validation') # set as validation data
outputs:
Found 0 images belonging to 5 classes.
What is wrong please? I suppose the validation set has at least few images for last class!
Any help would be greatly appreciated.
CS
It's hard to say without seeing what your directory string is, but I suspect perhaps the problem could be with characters in your "train_dir" variable. You can try using os.path.exists(train_dir) to see if your code is actually pointing to the right spot, or use os.listdir to see if you're seeing the files that way.
Throwing this line in there before you create your data generators might solve it:
import os
train_dir=os.path.normpath(train_dir)
Usually I find the problem is with the slashes in a path. If you just want to use a string, you usually need to use double backslashes (\) or a single forward slash (/) instead of the single backslashes you usually see in a path. This is especially problematic when your filenames or sub-directories start with a number (as yours do).

Psychopy: Call a conditions file from the outer loop's conditions file

I am a bit new to PsychoPy and Python coding, so please excuse my question if it is basic. In my task, I have a number of files that dictate the position of stimuli. My outer loop has a variable, ExcelList, which has the previously mentioned file names listed under it. The inner loop, which dictates each trial, attempts to call these files at random by entering $ExcelList into the space asking for a conditions file. As I understand it, the command for $ExcelList should access the conditions file in the outer loop and pull one of the files containing stimuli positions for that trial. However, I am instead presented with the following error:
File "/Users/bencline/Desktop/Psychexp/NegPriming2080_lastrun.py",
line 247, in module>
trialList=data.importConditions(ExcelList), File "/Applications/PsychoPy2.app/Contents/Resources/lib/python2.7/psychopy/data.py",
line 1366, in importConditions
raise ImportError('Conditions file not found: %s' %os.path.abspath(fileName)) ImportError: Conditions file not found:
/Users/bencline/Desktop/Psychexp/Trials_20_95.xlsx
It would appear that the inner loop is not finding the condition in the outer loop (or not reading the outer loop altogether). If I try instead writing $eval(ExcelList) I am presented with the following error:
File "/Users/bencline/Desktop/Psychexp/NegPriming2080_lastrun.py",
line 247, in
trialList=data.importConditions(eval(ExcelList)), File "", line 1, in NameError: name 'Trials_20_95' is not
defined
This seems more indicative of the underlying problem, but I'm still not sure how to proceed from here. Do you have any suggestions for why this is happening and how I could potentially fix it?
Thank you,
-Ben
Your strategy is right. It reads your ExcelList in the outer loop but fails to find the filenames in ExcelList on your filesystem. In particular, in your first error message, it fails to find /Users/bencline/Desktop/Psychexp/Trials_20_95.xlsx. So check whether it actually exists. I strongly suspect that it does not because of one or both of these:
It is in a different folder, e.g. a subfolder. The solution is to write out the path (relative or absolute) in the ExcelList file.
It is spelled differently, e.g. with a small T or capital postfix (XLSX), a spacebar or the like. The solution is of course to make the filenames in the ExcelList and the actual filenames match.

TypeError: cannot concatenate 'str' and 'pygame.Surface' objects

I am currently teaching myself game programming, and I've started nice and easy with pygame. I went through a tutorial that showed me how to build a simple game, and now that I am finished with it, I am in the process of trying to reorganize the code in a manner that makes sense to me, and also to edit it and add to it.
Part of what I tried to change is that instead of loading one '.png' file for a character, I load a list of them that will be iterated through in a 'move()' function I designed to make the characters look like they are moving. However I keep running into an error and I don't know why. Near the beginning of my code (all I've done is imported necessary modules and initialized pygame and some necessary variables) I tried to do the following code:
badguyimgs = ['badguy.png', 'badguy2.png', 'badguy3.png', 'badguy4.png']
for img in badguyimgs:
badguyimgs.append(pygame.image.load("resources/images/" + img))
badguyimgs.remove(img)
I keep getting the following error:
TypeError: cannot concatenate 'str' and 'pygame.Surface' objects
So far I have tried to initialize a new variable (resource = "resources/images/" + img) and place that at the beginning of the "for" loop and then insert that into the pygame.image.load(). I've also tried using os.path.join("resource/images/" + img). I've tried using the full path name ("c:\\Users\\ . . . \\resources\\images\\" +img). But any time I try to concatenate the pathname with the file name in the list, I get the above error code. I tried looking in the pygame documentation, but didn't see anything that helped in this situation. I've tried googling the error, but get nothing in reference to this. (a lot of issues with people tring to concatenate int types to strings though. . . ) I would appreciate any help anyone could give in pointing out why I am experiencing this, and what could fix it. Thanks.
It looks like what you're doing is appending the pygame.surface object (that you loaded from a png file) to the list while you're iterating through it. You are loading the images successfully. However after your function adds the first image and removes the string, your list looks like this:
badguyimgs = ['badguy2.png', 'badguy3.png', 'badguy4.png', pygame.image]
You are still iterating through the list, so your function starts trying to concatenate the string and the pygame.surface object. I would recommend creating an empty list, and add your loaded images to that list without adding or removing anything from the original. Hope this helped!
Here's an example to go with PlatypusVenom's explanation:
file_names = ['badguy.png', 'badguy2.png', 'badguy3.png', 'badguy4.png']
images = []
for file_name in file_names:
images.append(pygame.image.load("resources/images/" + file_name))
Now the pygame.Surface objects are in images, and the variable names for the lists are less confusing. Another option is to use a list comprehension:
images = [pygame.image.load("resources/images/" + file_name) for file_name in \
("badguy.png", "badguy2.png", "badguy3.png", "badguy4.png")]
This is similar to what you were going for in the code posted. The list of strings will be removed from memory, leaving only pygame.Surface objects in the images list.

How can I check if a string is a valid file name for windows using R?

I've been writing a program in R that outputs randomization schemes for a research project I'm working on with a few other people this summer, and I'm done with the majority of it, except for one feature. Part of what I've been doing is making it really user friendly, so that the program will prompt the user for certain pieces of information, and therefore know what needs to be randomized. I have it set up to check every piece of user input to make sure it's a valid input, and give an error message/prompt the user again if it's not. The only thing I can't quite figure out is how to get it to check whether or not the file name for the .csv output is valid. Does anyone know if there is a way to get R to check if a string makes a valid windows file name? Thanks!
These characters aren't allowed: /\:*?"<>|. So warn the user if it contains any of those.
Some other names are also disallowed: COM, AUX, NUL, COM1 to COM9, LPT1 to LPT9.
You probably want to check that the filename is valid using a regular expression. See this other answer for a Java example that should take minimal tweaking to work in R.
https://stackoverflow.com/a/6804755/134830
You may also want to check the filename length (260 characters for maximum portability, though longer names are allowed on some systems).
Finally, in R, if you try to create a file in a directory that doesn't exist, it will still fail, so you need to split the name up into the filename and directory name (using basename and dirname) and try to create the directory first, if necessary.
That said, David Heffernan gives good advice in his comment to let Windows do the wok in deciding whether or not it can create the file: you don't want to erroneously tell the user that a filename is invalid.
You want something a little like this:
nice_file_create <- function(filename)
{
directory_name <- dirname(filename)
if(!file.exists(directory_name))
{
ok <- dir.create(directory_name)
if(!ok)
{
warning("The directory of that path could not be created.")
return(invisible())
}
}
tryCatch(
file.create(filename),
error = function(e)
{
warning("The file could not be created.")
}
)
}
But test it thoroughly first! There are all sorts of edge cases where things can fall over: try UNC network path names, "~", and paths with "." and ".." in them.
I'd suggest that the easiest way to make sure a filename is valid is to use fs::path_sanitize().
It removes control characters, reserved characters, and Windows-reserved filenames, truncating the string at 255 bytes in length.

Pass data from workspace to a function

I created a GUI and used uiimport to import a dataset into matlab workspace, I would like to pass this imported data to another function in matlab...How do I pass this imported dataset into another function....I tried doing diz...but it couldnt pick diz....it doesnt pick the data on the matlab workspace....any ideas??
[file_input, pathname] = uigetfile( ...
{'*.txt', 'Text (*.txt)'; ...
'*.xls', 'Excel (*.xls)'; ...
'*.*', 'All Files (*.*)'}, ...
'Select files');
uiimport(file_input);
M = dlmread(file_input);
X = freed(M);
I think that you need to assign the result of this statement:
uiimport(file_input);
to a variable, like this
dataset = uiimport(file_input);
and then pass that to your next function:
M = dlmread(dataset);
This is a very basic feature of Matlab, which suggests to me that you would find it valuable to read some of the on-line help and some of the documentation for Matlab. When you've done that you'll probably find neater and quicker ways of doing this.
EDIT: Well, #Tim, if all else fails RTFM. So I did, and my previous answer is incorrect. What you need to pass to dlmread is the name of the file to read. So, you either use uiimport or dlmread to read the file, but not both. Which one you use depends on what you are trying to do and on the format of the input file. So, go RTFM and I'll do the same. If you are still having trouble, update your question and provide details of the contents of the file.
In your script you have three ways to read the file. Choose one on them depending on your file format. But first I would combine file name with the path:
file_input = fullfile(pathname,file_input);
I wouldn't use UIIMPORT in a script, since user can change way to read the data, and variable name depends on file name and user.
With DLMREAD you can only read numerical data from the file. You can also skip some number of rows or columns with
M = dlmread(file_input,'\t',1,1);
skipping the first row and one column on the left.
Or you can define a range in kind of Excel style. See the DLMREAD documentation for more details.
The filename you pass to DLMREAD must be a string. Don't pass a file handle or any data. You will get "Filename must be a string", if it's not a string. Easy.
FREAD reads data from a binary file. See the documentation if you really have to do it.
There are many other functions to read the data from file. If you still have problems, show us an example of your file format, so we can suggest the best way to read it.

Resources