|
I can't see a problem here; create a loop, parse each line, and calculate min/max. It is elementary.
|
|
|
|
|
sorry for the brief explanation. I am trying to find out the so called average color of an image. for example a red flower right i have to find the min and max color of the red flower in order to do a background strip using the min and max color found. right now i want to find the average R, average G and average B. as u can see from the pic in the link i have posted above, all the color values are listed in a listbox. how can i extract just the RGB values from it and find the min and max color value of the particular red flower as an example.
|
|
|
|
|
Looking at the image, I think you have directly added the colors to the Items collection of the ListBox, so what you see in the list is what ToString() method returns for each one of them. So having each color is as simple as using a foreach loop.
I think the problem you have here is the question itself. How will you define what color is bigger than other one? I mean: Blue color RGB values are 0, 0, 255; Red color RGB values are 255, 0, 0. So, which one is bigger?
Calculating the average color of an image has nothing to do with min or max color or RGB component. You just have to sum the RGB components separatedly, divide each sum by the number of pixels of your image, and you will have the RGB components of the average color of it.
|
|
|
|
|
oh thank you. is there any way i can find the min and max color range of the example the case of a red flower?
I manage to get the RGB color value of every pixel in that image and is being stored in an array which have 100 entries. is it possible to just select example array[0], array[4] and array[8]?
modified on Sunday, November 7, 2010 2:11 AM
|
|
|
|
|
You're still not getting it. How do you define what makes a "minimum color" and "maximum color"?? Since a color is made up of 3 to 4 seperate values, combined, there is no "min" and "max" color as defined by these mathmetical terms.
|
|
|
|
|
Ok I decided to give it a try using Async sockets. I'm trying to get the client and server to talk. Right now I can get the SERVER to receive data from the client.. but when I try to get the server to send data back to the client it doesn't work!!
Client:
static void Checkin()
{
IPEndPoint endPoint = new IPEndPoint(serverIp, 5555);
Socket sendSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sendSocket.Connect(endPoint);
Operations ops = new Operations();
ops.Task = Operations.Tasks.CHECKIN;
ops.NetBios = System.Environment.MachineName;
ops.ClientId = 1;
IFormatter formatter = new BinaryFormatter();
NetworkStream ns = new NetworkStream(sendSocket);
formatter.Serialize(ns, ops);
ns.Flush();
ns.Close();
Console.WriteLine("Beginning to get data");
Receive(sendSocket);
receiveDone.WaitOne();
sendSocket.Shutdown(SocketShutdown.Both);
sendSocket.Close();
}
private static void Receive(Socket client)
{
try
{
StateObject state = new StateObject();
state.workSocket = client;
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
static void ReceiveCallback(IAsyncResult iar)
{
StateObject state = iar.AsyncState as StateObject;
Socket client = state.workSocket;
try
{
int recv = client.EndReceive(iar);
if (recv > 0)
{
state.ms.Write(state.buffer, 0, recv);
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
}
else
{
if (state.ms.Length > 0)
{
state.ms.Seek(0, 0);
IFormatter formatter = new BinaryFormatter();
Operations ops = (Operations)formatter.Deserialize(state.ms);
Console.WriteLine("Got: " + ops.Task.ToString());
Console.ReadKey();
}
receiveDone.Set();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Console.ReadKey();
}
}
Server:
private void StartListening(object p)
{
int port = Convert.ToInt32(p);
try
{
socketlistener = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp);
IPEndPoint iep = new IPEndPoint(IPAddress.Any, port);
socketlistener.Bind(iep);
socketlistener.LingerState.Enabled = false;
socketlistener.Listen(100);
Logging.Debug("Socket initialized and listening on port " + p.ToString());
while (true)
{
allDone.Reset();
socketlistener.BeginAccept(new AsyncCallback(AcceptClient), socketlistener);
allDone.WaitOne();
}
}
catch (Exception ex)
{
Logging.Log(ex.ToString());
}
}
private void AcceptClient(IAsyncResult iar)
{
allDone.Set();
try
{
Socket old = iar.AsyncState as Socket;
Socket client = old.EndAccept(iar);
Logging.Debug("Client (" + client.RemoteEndPoint.ToString() + ") connected");
StateObject state = new StateObject();
state.workSocket = client;
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(GetClientData), state);
}
catch (Exception ex)
{
Logging.Log(ex.ToString());
}
}
private void GetClientData(IAsyncResult iar)
{
StateObject state = iar.AsyncState as StateObject;
Socket client = state.workSocket;
try
{
int recv = client.EndReceive(iar);
if (recv > 0)
{
state.ms.Write(state.buffer, 0, recv);
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(GetClientData), state);
}
else
{
if (state.ms.Length > 0)
{
state.ms.Seek(0, 0);
IFormatter formatter = new BinaryFormatter();
Operations ops = (Operations)formatter.Deserialize(state.ms);
Logging.Debug("Client (" + client.RemoteEndPoint.ToString() + ") sent action " + ops.Task.ToString() +
" with " + Convert.ToInt32(state.ms.Length) + " bytes of data");
Actions.PerformAction(ops);
ops = null;
state = null;
Send(client);
}
Logging.Debug("Client (" + client.RemoteEndPoint.ToString() + ") is disconnecting.");
client.Shutdown(SocketShutdown.Both);
client.Close();
}
}
catch (Exception ex)
{
Logging.Log(ex.ToString());
}
}
private void Send(Socket client)
{
try
{
Operations ops = new Operations();
ops.Task = Operations.Tasks.UPDATE_DEVICES;
ops.NetBios = Environment.MachineName;
Logging.Debug("Sending task (" + ops.Task.ToString() + ") to client " + client.RemoteEndPoint.ToString());
IFormatter formatter = new BinaryFormatter();
NetworkStream ns = new NetworkStream(client);
formatter.Serialize(ns, ops);
ns.Flush();
ns.Close();
client.Disconnect(false);
client.Close();
}
catch (Exception ex)
{
Logging.Log(ex.ToString());
}
}
So what am I doing wrong here? I am trying to get the client to send info to the server (this works if I don't put the code on the client for getting info from the server) and when the server gets it, it needs to send information back to the CLIENT. (this doesn't work).
So Client contacts server and says "Here is the information", the server puts it in a database (not shown), then the server sends information back saying "This is the actions you need to perform right now".
|
|
|
|
|
Figured it out... I wasn't paying attention...
In my code I was only reading the first 1024 bytes. So if it was under 1024 bytes it would work fine. I put in code to check if the amount read equaled the buffer size and then called the beginreceive again until we read all the data.
|
|
|
|
|
Just a friendly suggestion. When you answer your own question like this (or in fact, if anyone answers it well), add "[solved]" to the subject of the original. Helps people searching the archives.
Cheers,
Peter
Software rusts. Simon Stephenson, ca 1994.
|
|
|
|
|
Ahh will do! Thanks for the tip! Sorry I didn't do it before
|
|
|
|
|
Good You did what you want.. Keep it up
|
|
|
|
|
Thanks! Took me a little bit to figure it out but then again I've never worked with sockets before.
|
|
|
|
|
I hate programming.
I prefer work in country with a pain in my back
|
|
|
|
|
hi, ever since i put in a user control, my other buttons don't work why is this ?
The form opens with this user control then once the user clicks "start" it disappears (visible = false) and displays the game behind it, this is the delicate code...
for the Delicate for the useer control
void usrMenu1_ClickMenu(string Button)
{
switch (Button)
{
case "Start":
Gameplay = true;
usrMenu1.Visible= usrSettings1.Visible = false;
usrMenu1.Hide();
usrSettings1.Hide();
break;
case "Settings":
usrMenu1.Visible = false;
usrSettings1.Visible = true;
break;
}
}
This is the button control..
private void FrmGame_KeyDown(object sender, KeyEventArgs e)
{
if(Gameplay == true)
{
if (e.KeyCode == Keys.Up)
{
if (U == true)
{
Player.Direction = 1;
Player.Normal = new Bitmap("images\\playerup.png");
U = true;
R = true;
L = true;
D = false;
}
}
if (e.KeyCode == Keys.Right)
{
if (R == true)
{
Player.Normal = new Bitmap("images\\playerright.png");
Player.Direction = 3;
L = false;
R = true;
D = true;
U = true;
}
}
if (e.KeyCode == Keys.Down)
{
if (D == true)
{
Player.Normal = new Bitmap("images\\playerdown.png");
Player.Direction = 2;
R = true;
L = true;
U = false;
D = true;
}
}
if (e.KeyCode == Keys.Left)
{
if (L == true)
{
Player.Normal = new Bitmap("images\\playerleft.png");
Player.Direction = 4;
R = false;
L = true;
D = true;
U = true;
}
}
if (e.KeyCode == Keys.Up && e.KeyCode == Keys.Right)
{
if (R == true)
{
Player.Normal = new Bitmap("images\\playerright.png");
Player.Direction = 3;
L = false;
R = true;
D = true;
U = true;
}
}
if (e.KeyCode == Keys.Down && e.KeyCode == Keys.Right)
{
if (R == true)
{
Player.Normal = new Bitmap("images\\playerright.png");
Player.Direction = 3;
L = false;
R = true;
D = true;
U = true;
}
}
if (e.KeyCode == Keys.Up && e.KeyCode == Keys.Left)
{
if (L == true)
{
Player.Normal = new Bitmap("images\\playerleft.png");
Player.Direction = 4;
R = false;
L = true;
D = true;
U = true;
}
}
if (e.KeyCode == Keys.Down && e.KeyCode == Keys.Left)
{
if (L == true)
{
Player.Normal = new Bitmap("images\\playerleft.png");
Player.Direction = 4;
R = false;
L = true;
D = true;
U = true;
}
}
}
}
And this is the section of code relivent for you lot to the Setup Game code
protected void Setup_Game()
{
usrMenu1.ClickMenu += new ClickButtonDel(usrMenu1_ClickMenu);
}
|
|
|
|
|
Without looking in too much depth at that monolithic code, I think the first improvement you make should be to these lines:
if (e.KeyCode == Keys.Up && e.KeyCode == Keys.Right)
if (e.KeyCode == Keys.Down && e.KeyCode == Keys.Right)
if (e.KeyCode == Keys.Up && e.KeyCode == Keys.Left)
if (e.KeyCode == Keys.Down && e.KeyCode == Keys.Left)
Perhaps OR might work better than AND?
Real men don't use instructions. They are only the manufacturers opinion on how to put the thing together.
|
|
|
|
|
First of all, it would be good to know if this is Windows.Forms or WPF, becouse the possible solutions might be different.
I guess your usrMenu1 object is an instance of your user control. You have defined a new delegate for the ClickMenu event, so the target method receives an string. It is not strictily bad, the code compiles and works, but it is not the best practice. You should better follow the structure of all event delegates defined in .NET, I mean, the target method should receive two parameters, you know, (object sender, EventArgs e) , and if you need to pass some aditional data, you just have to extend EventArgs class subclassing it and adding what you need. The problem here might be in the code which raises the ClickMenu event, and you have not posted it here, or might be in the KeyDown event handler you have posted becouse there are several mistakes in it. That said, I would like to help you improve this code a little.
In this case, instead of a strange ClickMenu event which sends a string I would have defined two different events using the "standard" delegate EventHandler: one for Start button and another one for Settings button.
On the other hand, there is a huge optimization job you should do on your code. These composed conditions are always false, and the code of these if blocks do never execute:
if (e.KeyCode == Keys.Up && e.KeyCode == Keys.Right)
Considering this, you do not need the if blocks to set the values to the four bool variables you are using, these four lines would do the same:
U = e.KeyCode != Keys.Down;
D = e.KeyCode != Keys.Up;
L = e.KeyCode != Keys.Right;
R = e.KeyCode != Keys.Left;
So setting Player.Normal and Player.Direction properties might be done with a switch.
|
|
|
|
|
Well I'm new to programming using sockets. What i am trying to do is create a client/server model. The client will report into the server every so often, and the server will send back data telling the agent what to do. (Monitoring software).
The problem I am having is closing the socket on the server. I get errors like:
A blocking operation was interrupted by a call to WSACancelBlockingCall
For my code:
while (running)
{
try
{
Socket socket = this.listener.Accept();
if (socket != null)
{
Thread handleThread = new Thread(new ParameterizedThreadStart(HandleTheClient));
handleThread.Start(socket);
}
}
catch (Exception ex)
{
Logging.Log(ex.ToString());
}
}
Closing:
protected override void OnStop()
{
running = false;
if (listener != null)
{
listener.Shutdown(SocketShutdown.Both);
listener.Close();
}
}
Now I know the problem is with;
Socket socket = this.listener.Accept();
But how do I fix this? IS the only way to use AcceptAsync? IF you are wondering why I'm not using that then its because I haven't learned it yet. I need to read up on it first. So can I break this block somehow when the service is trying to stop so the service will stop without error or even stop?
|
|
|
|
|
Before calling the Accept method, you must first call the Listen method to listen for and queue incoming connection requests.
Have you tried it
Whatever,still now if you receive a SocketException,you can use the SocketException.ErrorCode property to obtain the specific error code. After getting code you can refer to the Windows Sockets version 2 API error code documentation in the MSDN library for a detailed description of the error.
I Hope it will work for you.
|
|
|
|
|
I didn't show all of my code.. sorry about that. I called the Listen for the WHILE statement. The problem is when doing it this way it blocks at the Accept() method. The way I have it works. I can accept connections and do what I want with the data (I'm sending / receiving serialized data). The problem is when someone goes and tries to stop the service.
That is when I try to call the Shutdown and Close method and thats when it hangs
I decided to use async sockets
modified on Saturday, November 6, 2010 12:48 PM
|
|
|
|
|
Just watching this VSTS 2008 Unit Testing 1 of 1 lets you know how to test methods that return something, my question here is how do you test methods in Visual Studio 2008 that don't return any value? For example:
private void BtnLoad_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Title = "Select one or more media files";
dlg.Multiselect = IsEnabled;
dlg.Filter = "Media files(*.mp3;*.wav;*.wma;*.avi;*.mp4;*.mpg;*.wmv)|*.mp3;*.wav;*.wma;*.avi;*.mp4;*.mpg;*.wmv|All files(*.*)|*.*";
Nullable<bool> result = dlg.ShowDialog();
if (result == true)
{
string[] files;
files = dlg.FileNames;
foreach (string file in files)
{
lstBxList.Items.Add(file);
}
}
}
|
|
|
|
|
You're trying to run an automated test on against a UI method. I may simply be a little old-school, but I typically don't write unit tests against UI methods because of the interaction required.
I wasn't, now I am, then I won't be anymore.
|
|
|
|
|
Your code is incorrectly written. This is a UI event handler and the code that you hav in it DOES return a value.
This dialog box code should be in its own method that returns a fully qualified path to the caller. It should NOT be sitting inside an event handler.
You also wouldn't run a unit test against a method that requires user interaction.
Another question. Why on earth would you use a nullable boolean to get the return value of a dialog box? It's either going to return true or false, never null. So, what's the point?
|
|
|
|
|
Right I see what your saying...First of all I should have pointed out that I am working with WPF hence use a nullable boolean to get the return value of a dialog box, the other way of calling a dialog box does not seem to work when developing a WPF based app. Secondly I used this as am example which I have to say after the response I got from fock was a bad example of which I was hoping fock would use it to illustrate how to test a method that does not return anything...Please bear in mind that I am a rooky,so if I say something that seems obvious to you, may not be the case with me...
|
|
|
|
|
Dave Kreskowiak wrote: Why on earth would you use a nullable boolean to get the return value of a dialog box? It's either going to return true or false, never null. So, what's the point?
Actually, it should return a DialogResult. The use of a bool condition would indicate that it's a WPF/SL dialog box, and this does return a nullable boolean condition.
|
|
|
|
|
I haven't done any WPF until very recently, and nothing on dialogs yet, so my ignorance is showing through there.
|
|
|
|
|
As defined that method can not be unit tested as it requires user input (to select the file). But as you want an example on how to test a method that doesn't return a value it can be refactored slightly as below.
To test a method that returns void you test for the change in system state that the method call is meant to impose. In this case the listbox should contain 2 items after the call, granted testing if items were added to a listbox is of dubious benefit but this is just for illustrative purposes.
private void BtnLoad_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Title = "Select one or more media files";
dlg.Multiselect = IsEnabled;
dlg.Filter = "Media files(*.mp3;*.wav;*.wma;*.avi;*.mp4;*.mpg;*.wmv)|*.mp3;*.wav;*.wma;*.avi;*.mp4;*.mpg;*.wmv|All files(*.*)|*.*";
Nullable<bool> result = dlg.ShowDialog();
if (result == true)
{
LoadFilesToListbox(dlg.FileNames);
}
}
public void LoadFilesToListbox(string[] files)
{
foreach (string file in files)
{
lstBxList.Items.Add(file);
}
}
[TestMethod]
public void TestLoadFilesToListbox()
{
LoadFilesToListbox(new string[] { "file1.txt", file2.dat" });
Assert.AreEqual(2, lstBxList.Items.Count);
}
|
|
|
|
|