Matlab, AppDesigner-Convert image on a good type and use it in "imread" function - arrays

I use AppDesigner inMATLAB to show photos with changed RGB. But there is the problem with character of the photo.
When I switch on my own fuction "changeRGB", finally "choosenImage" has 20bytes, class "char" and size(1x10). OK!
There is no problem in using the "function OpenButtonValueChanged". OK!
There is the problem with "function UploadButtonPushed". OK!
ABOUT THE PROBLEM:
When I click button which callback is "function UploadButtonPushed" I get the error:
"Error using imread>parse_inputs (line 502)
The file name or URL argument must be a character
vector or string scalar."
"Error in imread (line 342)
[source, fmt_s, extraArgs, was_cached_fmt_used] =
parse_inputs(cached_fmt, varargin{:});"
WHY?
Because in the "function UploadButtonPushed" my choosenImage has 1977624bytes, class "uint8" and size(681x968x3). So it's too bug for "imread".
WHAT I TRIED:
When in "function OpenButtonValueChanged" I convert a photo, adding "char": (myimage = char(app.clickedImage)); the class of the photo is changing from uint8 to char but the size.
When I use "num2cell", the claas of the photo is changing on "cell" but size and number of bytes are the same- so big. And I get the Error: "Error using imread>parse_inputs (line 502) The file name or URL argument must be a character vector or string scalar."
In my own function "changeRGB" I used "imread(image)" and here is the problem with the size of the photo. Do you know how to get the correct one?
%my own properties in AppDesigner- to use them in different functions
properties (Access = public)
clickedImage;
addR = 1;
addG = 1;
addB = 1;
end
%first function in AppDeesigner
function OpenButtonValueChanged(app, event)
value = app.OpenButton.Value;
[file, howManyFiles] = chooseImagesFromComputer; %myown function
%I load 3 images which are showed as miniatures
myFile1 = imread(file{1});
imshow(myFile1, 'Parent', app.UIAxes1_1);
myFile2 = imread(file{2});
imshow(myFile2, 'Parent', app.UIAxes1_2);
myFile3 = imread(file{3});
imshow(myFile3, 'Parent', app.UIAxes1_3);
%take values of changed RGB from the slider
app.addR = app.SliderR.Value
app.addG = app.SliderG.Value
app.addB = app.SliderB.Value
%work only on one image to change its colors. app.clickedImage, app.addR, app.addG, app.addB are properties at the beginning of the code
app.clickedImage = file{1};
app.clickedImage = changeRGB(app.clickedImage,app.addR,app.addG,app.addB); %changeRGB- my own function- here is the problem. I add it bottom
imshow(app.clickedImage,'Parent',app.UIAxesMain);
end
%second function in AppDesigner
%here is the button to upload color of the photo
function UploadButtonPushed(app, event)
myimage = app.clickedImage;
myimage = changeRGB(myimage,app.addR,app.addG,app.addB);
imshow(myimage);
end
%here is my own function in matlab, not in AppDesigner, which makes problem:
function [changedImage] = changeRGB(choosenImage, addR, addG, addB)
whos
loadedImage = imread(choosenImage);
R = loadedImage(:,:,1); %extract one of the color channels
G = loadedImage(:,:,2);
B = loadedImage(:,:,3);
RBG = cat(3,R,G,B);
R_adj2 = R + addR;
G_adj2 = G + addG;
B_adj2 = B + addB;
changedImage = cat(3,R_adj2,G_adj2,B_adj2);
end

First, you make unnecessary operations in changeRGB
function [changedImage] = changeRGB(choosenImage, addR, addG, addB)
loadedImage = imread(choosenImage);
loadedImage = bsxfun(#sum, loadedImage, reshape([addR, addG, addB], [1 1 3]);
end
Then this function return an array (the modified image) so in UploadButtonPushed(app, event) when you run myimage = app.clickedImage;, you are passing the modified array instead of the image path, that you set here app.clickedImage = changeRGB(app.clickedImage,app.addR,app.addG,app.addB);
So you have to change the design of your variables, because app.clickedImage is saving either the image path, or the image itself. Consider having 2 different variables.
A good advice also is to use matlab debugger which is really good help to find the source of this kind of problems.

Related

Retrieving datas within an Array

This is probably easy but I just cannot get the answer. Here is a simple Array:
I want the information to be distributed from an Input textBox to different dynamic textBox after a click. I am OK with buttons.
var ERLQ1:Array = ["ERLQ1", "N09°02.61 / E100°49.11", "ErawanLq"];
InputText = "ERLQ1";
//I want to display:
Txt1 = "ERLQ1" //Being first part of the array as main reference.
Txt2 = "N09°02.61 / E100°49.11" // Should be: String(ERLQ1[1])
Txt3 = "ErawanLq" // Should be: String(ERLQ1[2])
First time I write in a forum like this. Please forgive if not perfect. Thanks in advance.
Andre
If I understand correctly, an array of objects would work well. Since you have a set number of textfields I assume that you also have a set number of details that you want to display in them. If that is the case, this solution should work fine.
arr:Array = [{_name:"ERLQ1",ans1:"N09°02.61 / E100°49.11",ans2:"ErawanLq"},
{_name:"ERLQ2",ans1:"question 2 answer 1",ans2:"ques2ans1"}];
So, I don't really "get" your application, but if it were some sort of a quiz, you'd have a new array element for each question, and that element has a name, and two answers. Easy to modify it to grab answers from an answer pool. Now to find the element in the array that has ._name == "ERLQ1" you will need to loop through all the elements and return the one that has the ._name property that matches your search. Here is an example function:
private function matchName(arr:Array, term:String):int{
for (var i:int = 0; i < arr.length; i++){
if (arr[i]._name == term){
return i;
}
}
return -1;
}
This function will return the array index number of the matching term. If no match exists, it returns -1. So you could use it like this (pseudocode):
// on submit search{
// find the index number in the array of the element that matches the search term
var ind:int = matchName(arr, searchTerm);
// assign the textfield texts to the corresponding associated values
textBox1:text = arr[ind]._name;
textBox2:text = arr[ind].ans1;
textBox3:text = arr[ind].ans2;
}
I perhaps misunderstood (because of my English), but :
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
var ERLQ1:Array = ["ERLQ1", "N09°02.61 / E100°49.11", "ErawanLq"];
var Txt1 : TextField = new TextField();
Txt1.autoSize=TextFieldAutoSize.CENTER;
Txt1.type = TextFieldType.INPUT;
Txt1.border = true;
var Txt2 : TextField = new TextField();
Txt2.autoSize=TextFieldAutoSize.CENTER;
Txt2.type = TextFieldType.INPUT;
Txt2.border = true;
var Txt3 : TextField = new TextField();
Txt3.autoSize=TextFieldAutoSize.CENTER;
Txt3.type = TextFieldType.INPUT;
Txt3.border = true;
addChild(Txt1);
addChild(Txt2);
addChild(Txt3);
Txt1.x = 20, y =40;
Txt2.x = 180, y =40;
Txt1.x = 300, y =40;
Txt1.text = ERLQ1[0]; // is now : first part of the array as main reference (String(ERLQ1[0]).
Txt2.text = ERLQ1[1]; // is now : String(ERLQ1[1]);
Txt3.text = ERLQ1[2]; // is now : String(ERLQ1[2]);
This will display 3 TextFiels as input text like this :
If I misunderstood your question, please tell me more about what You expect!
Best regards.
Nicolas

Array of structures in MATLAB Simulink

I am trying to create an array of structures in Simulink and got some problems with it.
first of all i tried to create it directly in Simulink using this:
function a = fcn(Dibhole, t , x, const)
%#codegen
%Output = zeros(10,10);
f1 = 'number';
f2 = 'move';
cube = struct(f1, 0, f2, 0);
a = repmat(cube, 20, 10);
for i = 1:20
for j = 1:10
a(i,j).number = 0;
a(i,j).move = 0;
end
end
and i got this error:
Derived output was of type struct. 'Inherited type' is unsupported for this
type and a defined bus object must be used instead. Click on 'a' and
set data type for 'a' to be 'Bus: ', where '' is
the name of a bus object from the MATLAB workspace.
So i found some example how to create struct in Matlab and receive this to Simulink: http://blogs.mathworks.com/seth/2011/12/05/initializing-buses-using-a-matlab-structure/
That works perfectly but i still can't repeat this with array:
f1 = 'number';
f2 = 'move';
cube = struct(f1, 0, f2, 0);
myStruct2 = repmat(cube, 20, 10);
for i = 1:20
for j = 1:10
myStruct2(i,j).number = 1;
myStruct2(i,j).move = 1;
end
end
busInfo = Simulink.Bus.createObject(myStruct2);
Can anyone clarify to me what's the problem? Or maybe there is different way to create array of struct in Simulink?
Mihail
Simulink wants you to define the output of the function to be a bus.
As 'Bus: My_test_bus', for example.
Take a look at the Simulink Bus Editor. You can find it in any model under the menu, Edit->Bus Editor.
This would be a good start.
Rick, i think you are right!
i have tried this problem for a long time, and have got this results:
the irony is that I was never able to create array of structures BUT i did this with structure of arrays! :D
I made this steps for it:
to use structure of arrays we need to define and initialize it in some MATLAB function. Like this:
number = zeros(10,1);
move = zeros(10,1);
for i = 1:10
number(i,1) = i+1;
move(i,1) = i+2;
end
a = struct('numbers',number,'movement', move);
To work this data we must use Bus Selector.
So we have array in "numbers" and "movement".
BUT! Here we go, Rick: we must define type of output of MATLAB function like Bus! How to do this in simulink? i found this way:
in model properties in simulink Callbacks/PreLoadFcn define some function and in same folder as project create .m file named like this just defined function.
In this file create structure of array and define Bus type for it:
number = zeros(10,1);
move = zeros(10,1);
a = struct('numbers',number,'movement', move);
busInfo = Simulink.Bus.createObject(a);
Now we have Bus type for our structure at first loading of simulink model.
Last step: define MATLAB function output type directly.
in Model Explorer choose your MATLAB function. choose output variable. Set DataType for it: Bus:slBus1 (the name of this Bus type you can see in wokspace of matlab, because its a global variable).
That's all! now it works!
(tried to add pictures, but i have no enough reputation :( )
Now my program works in this way, but i also tried to create array of structures and still have the problems. i tried to create Bus for it, but can't transmit it to Bus Selector - it doesn't know what to do with structures... i also tried to add one more MATLAB function to create some data from structures and then display it, but it doesn't works too(

Clearing my array leaves blank array positions

So I'm facing a problem with an AS3 class that's not operating the way I need it to. It's a simple problem, but a complex set of methods that cause it.
Firstly, the 'quiz' I'm building has 6 questions loaded as external SWFs inside of a Shell, run by a class. First we declared a var "a_quiz" to hold 6 values pushed from the external SWFs. These 6 values are reduced to a string and then checked against another array that contains the correct answers. The following loadQuiz function is designed to launch one of three random quizes and clear the a_quiz array so it can take new answers:
public function loadQuiz():void {
a_quiz.length=0;
trace("loadQuiz");
n_quizCorrect = n_quizScore = 0;
n_currentQuiz = Math.floor(Math.random() * (n_totalTopics - n_quizStart + 1) + n_quizStart);
loadTopic(n_currentQuiz);
}
Now I've tested the Shell and confirmed that the trace "loadQuiz" fires every time. And the first time you load the quiz, everything behaves as it should. The 6 questions trace correct or incorrect responses and push 6 binary values into the a_quiz array. The output looks like this:
loadQuiz
incorrect
correct
incorrect
incorrect
incorrect
incorrect
0,1,0,0,0,0
you failed
Then I jump back to the main menu and launch again. This deploys the loadQuiz function all over again. The first line of the function:
a_quiz.length=0;
should be emptying the a_quiz array to accept new answers to mark against. But when I complete the quiz I get this:
loadQuiz
correct
correct
correct
correct
correct
correct
,,,,,,1,1,1,1,1,1
you failed
For some reason beyond my understanding, the push values are stacking on top of empty positions, so when the strings compare...they won't match. What is going on here?
The push function:
function handleClick(evt:MouseEvent):void{
var tempCORRECT = a_answerSheet.toString();
var tempSELECTION = a_selected.toString();
//
if(tempSELECTION == tempCORRECT){
trace('correct');
parentObj1.a_quiz[ parentObj1.n_currentQuestion - 1 ] = 1;
}else{
trace('incorrect');
parentObj1.a_quiz[ parentObj1.n_currentQuestion - 1 ] = 0;
}
parentObj1.n_currentQuestion ++;
// GOTO NEXT SLIDE
parentObj1.LOADNEXT('up');
}
The problem originated in the loading of the Quiz itself.
as you can see on the handleClick function:
parentObj.n_currentQuestion++
was increasing an integer variable on the parentObj's timeline called n_currentQuestion. The problem then, originated in how the quiz was logging n_currentQuestion when the quiz loads with this function:
public function loadQuiz():void {
a_quiz= [];
trace("loadQuiz");
n_quizCorrect = n_quizScore = 0;
n_currentQuiz = Math.floor(Math.random() * (n_totalTopics - n_quizStart + 1) + n_quizStart);
loadTopic(n_currentQuiz);
}
So to correct the error, I needed to add a line to the loadQuiz, so that it would always load with n_currentQuestion set to 1.
public function loadQuiz():void {
a_quiz= [];
n_currentQuestion = 1;
trace("loadQuiz");
n_quizCorrect = n_quizScore = 0;
n_currentQuiz = Math.floor(Math.random() * (n_totalTopics - n_quizStart + 1) + n_quizStart);
loadTopic(n_currentQuiz);
}

Multi-language GUI setup with a string array

I am working on the Keil uv4 IDE with an ARM Cortex-M3 in a bare metal C application. I have a GUI that I created that is currently in English, but I would like to give the user the ability to go between other languages like you can on a cell phone.
I have created a structure with all the words that are used called string_table_t.
struct string_table_t
{
char *word1;
char *word2;
char *word3;
};
My thought process was to have plain text files for the different languages and the list of words used contained in each one. Then I would do a load function that would link the pointers of the string table with the actual word.
Now, my initial menu is created statically by defining it like so. It is based off of Altium software platform.
// Test structure
struct string_table_t string_table = {"Main Menu","test1","test2"};
form_t mainmenu_form =
{
.obj.x = 0,
.obj.y = 0,
.obj.width = 240,
.obj.height = 320,
.obj.draw = form_draw,
.obj.handler = mainmenu_form_handler,
.obj.parent = NULL,
.obj.agui_index = 0,
.obj.visible = __TRUE,
.obj.enabled = __TRUE,
.caption.x = 0,
.caption.y = 0,
.caption.text = "Main Menu",
.caption.font = &helveticaneueltstdltext18_2BPP,
.caption.color = RGB(230,230,230),
.caption_line_color = RGB(241,101,33),
.caption.fontstyle = FS_NONE,
.caption.align = ALIGN_CENTRE,
.captionbarcolor = RGB(88,89,91),
.children = mainmenu_children,
.n_children = 4,
.relief = RELIEF_NONE,
.color = RGB(65,64,66),
};
What I want to do is replace the "Main Menu" of the caption.text with string_table.word1. Therefore, if I load a different language set, the menu will automatically be pointing to the correct char array. Doing this currently results in a error expression must have a constant value.
Now, I can get this to work by leaving the text null in the menu component and adding:
Link_pointer_to_menu() {
mainmenu_form.caption.text = string_table.Main_menu_text;
}
This will compile and work, but I would rather not have to have 100 or so of these statements. Is there a more optimal way of doing this?
I would recommend something like that:
enum MyWords
{
msgHello,
msgOpen,
msgClose,
msgMainMenu,
num_Messages,
};
char *string_table_t[num_Messages];
You should write code that loads your language file and assigns pointers in this array. After that in your code:
.caption.text = string_table_t[msgMainMenu];
The idea is that you give each string a symbolic name that is an offset in the table of strings. After that you use this offset as an index into the table.

Image Analysis Program Based on Hashcode Method Resulting in Errors

I am trying to write a program that will recognize an image on the screen, compare it against a resource library, and then calculate based on the result of the image source.
The first thing that I did was to create the capture screen function which looks like this:
private Bitmap Screenshot()
{
System.Drawing.Bitmap Table = new System.Drawing.Bitmap(88, 40, PixelFormat.Format32bppArgb);
System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(RouletteTable);
g.CopyFromScreen(1047, 44, 0, 0, Screen.PrimaryScreen.Bounds.Size);
return Table;
}
Then, I analyze this picture. The first method I used was to create two for loops and analyze both the bitmaps pixel by pixel. The problem with this method was time, it took a long time to complete 37 times. I looked around and found the convert to bytes and the convert to hash methods. This is the result:
public enum CompareResult
{
ciCompareOk,
ciPixelMismatch,
ciSizeMismatch
};
public CompareResult Compare(Bitmap bmp1, Bitmap bmp2)
{
CompareResult cr = CompareResult.ciCompareOk;
//Test to see if we have the same size of image
if (bmp1.Size != bmp2.Size)
{
cr = CompareResult.ciSizeMismatch;
}
else
{
//Convert each image to a byte array
System.Drawing.ImageConverter ic = new System.Drawing.ImageConverter();
byte[] btImage1 = new byte[1];
btImage1 = (byte[])ic.ConvertTo(bmp1, btImage1.GetType());
byte[] btImage2 = new byte[1];
btImage2 = (byte[])ic.ConvertTo(bmp2, btImage2.GetType());
//Compute a hash for each image
SHA256Managed shaM = new SHA256Managed();
byte[] hash1 = shaM.ComputeHash(btImage1);
byte[] hash2 = shaM.ComputeHash(btImage2);
for (int i = 0; i < hash1.Length && i < hash2.Length&& cr == CompareResult.ciCompareOk; i++)
{
if (hash1[i] != hash2[i])
cr = CompareResult.ciPixelMismatch;
}
}
return cr;
}
After I analyze the two bitmaps in this function, I call it in my main form with the following:
Bitmap Table = Screenshot();
CompareResult success0 = Compare(Properties.Resources.Result0, Table);
if (success0 == CompareResult.ciCompareOk)
{ double result = 0; Num.Text = result.ToString(); goto end; }
The problem I am getting is that once this has all been accomplished, I am always getting a cr value of ciPixelMismatch. I cannot get the images to match, even though the images are identical.
To give you a bit more background on the two bitmaps, they are approximately 88 by 40 pixels, and located at 1047, 44 on the screen. I wrote a part of the program to automatically take a picture of that area so I did not have to worry about the wrong location or size being captured:
Table.Save("table.bmp");
After I took the picture and saved it, I moved it from the bin folder in the project directly to the resource folder and ran the program again. Despite all of this, the result is still ciPixelMismatch. I believe the problem lies within the format that the pictures are being saved as. I believe that despite them being the same image, they are being analyzed in different formats, maybe one of the pictures contains a bit more information than the other which is causing the mismatch. Can somebody please help me solve this problem? I am just beginning with my c# programming, I am 5 days into the learning process, and I am really at a loss for this.
Yours sincerely,
Samuel

Resources