Why Is My Machine Learning Algorithm Getting Stuck? - machine-learning

So I am hitting a wall with my C# Machine Learning project. I am attempting to train an algorithm to recognize numbers. Since this is only an exercise I have a image set of 200 numbers (20 each for 0 to 9). Obviously if I wanted a properly trained algorithm I would use a more robust training set, but this is just an exercise to see if I can get it working in the first place. I can get it up to 60% accuracy, but not past that. I have been doing some research into activation functions and I from what I understand, LeakyRelu is the function I should be using. However, if I use the LeakyRelu function across the board then it doesn't learn anything, and I'm not sure how to use the LeakyRelu as an output activation function. Using sigmoid or tanh as an output activation function makes more sense to me. Here is a block of code that creates the array that feeds the backpropagation:
public static float ACTIVE_VALUE = 1;
public static float INACTIVE_VALUE = -1;
// This is specifically designed for a algorithm that will detect a number between 0 - 9
public static float[] valueToArray(int value)
{
switch (value)
{
case 0:
return new float[] { ACTIVE_VALUE, INACTIVE_VALUE, INACTIVE_VALUE, INACTIVE_VALUE, INACTIVE_VALUE,
INACTIVE_VALUE, INACTIVE_VALUE, INACTIVE_VALUE, INACTIVE_VALUE, INACTIVE_VALUE };
case 1:
return new float[] { INACTIVE_VALUE, ACTIVE_VALUE, INACTIVE_VALUE, INACTIVE_VALUE, INACTIVE_VALUE,
INACTIVE_VALUE, INACTIVE_VALUE, INACTIVE_VALUE, INACTIVE_VALUE, INACTIVE_VALUE };
case 2:
return new float[] { INACTIVE_VALUE, INACTIVE_VALUE, ACTIVE_VALUE, INACTIVE_VALUE, INACTIVE_VALUE,
INACTIVE_VALUE, INACTIVE_VALUE, INACTIVE_VALUE, INACTIVE_VALUE, INACTIVE_VALUE };
case 3:
return new float[] { INACTIVE_VALUE, INACTIVE_VALUE, INACTIVE_VALUE, ACTIVE_VALUE, INACTIVE_VALUE,
INACTIVE_VALUE, INACTIVE_VALUE, INACTIVE_VALUE, INACTIVE_VALUE, INACTIVE_VALUE };
case 4:
return new float[] { INACTIVE_VALUE, INACTIVE_VALUE, INACTIVE_VALUE, INACTIVE_VALUE, ACTIVE_VALUE,
INACTIVE_VALUE, INACTIVE_VALUE, INACTIVE_VALUE, INACTIVE_VALUE, INACTIVE_VALUE };
case 5:
return new float[] { INACTIVE_VALUE, INACTIVE_VALUE, INACTIVE_VALUE, INACTIVE_VALUE, INACTIVE_VALUE,
ACTIVE_VALUE, INACTIVE_VALUE, INACTIVE_VALUE, INACTIVE_VALUE, INACTIVE_VALUE };
case 6:
return new float[] { INACTIVE_VALUE, INACTIVE_VALUE, INACTIVE_VALUE, INACTIVE_VALUE, INACTIVE_VALUE,
INACTIVE_VALUE, ACTIVE_VALUE, INACTIVE_VALUE, INACTIVE_VALUE, INACTIVE_VALUE };
case 7:
return new float[] { INACTIVE_VALUE, INACTIVE_VALUE, INACTIVE_VALUE, INACTIVE_VALUE, INACTIVE_VALUE,
INACTIVE_VALUE, INACTIVE_VALUE, ACTIVE_VALUE, INACTIVE_VALUE, INACTIVE_VALUE };
case 8:
return new float[] { INACTIVE_VALUE, INACTIVE_VALUE, INACTIVE_VALUE, INACTIVE_VALUE, INACTIVE_VALUE,
INACTIVE_VALUE, INACTIVE_VALUE, INACTIVE_VALUE, ACTIVE_VALUE, INACTIVE_VALUE };
case 9:
return new float[] { INACTIVE_VALUE, INACTIVE_VALUE, INACTIVE_VALUE, INACTIVE_VALUE, INACTIVE_VALUE,
INACTIVE_VALUE, INACTIVE_VALUE, INACTIVE_VALUE, INACTIVE_VALUE, ACTIVE_VALUE };
default:
return new float[] { INACTIVE_VALUE, INACTIVE_VALUE, INACTIVE_VALUE, INACTIVE_VALUE, INACTIVE_VALUE,
INACTIVE_VALUE, INACTIVE_VALUE, INACTIVE_VALUE, INACTIVE_VALUE, INACTIVE_VALUE };
}
}
I don't know how to use something like this to read a LeakyRelu output. So I figured the best option would be to use LeakyRelu for the input and hidden layers and then use tanh or sigmoid for the output layer. However that creates an issue, because sigmoid just returns NAN (due to a rounding error from what I understand) and tanh returns -1 or 1 but nothing in between. If I use tanh across the board it works, and it learns, but it only reaches an accuracy of 60% then stops developing there. I assume this is due to the "vanishing gradient" issue. However, If I use LeakyRelu for inpunt and hidden layers and then tanh for the output, it stays at 12-14% (which is just as good as randomly guessing a number).
I am using a neural network that I got from a github user here:
https://github.com/kipgparker/BackPropNetwork
He posted a research paper online about neural networks, and it was one of the top hits on google. That's how I found it in the first place. I posted my full project in a zip on GitHub here:
https://github.com/JoshuaC0352/Machine-Learning
I am not opposed to using a library I can get from nuget like SiaNet (https://scisharp.github.io/SiaNet/api/SiaNet.Layers.AvgPooling1D.html), however I have gotten so familiar with the one I am currently working with I am somewhat reluctant to switch over because I'd feel like I am almost starting from scratch, because I would have to learn how to interface with a whole new library.
EDIT: additional code. This is my while loop that reads the image and trains the algorithm:
public static void singleThread()
{
int batchSize = 10000;
int rangeLow = 0;
int rangeHi = 9;
int hits = 0;
while (true)
{
// alternates between training and testing
//Console.WriteLine("Training... ");
for (int i = 0; i < batchSize; i++)
{
// Give a training progress report every 100 iterations, this should increase performance
if (i % 100 == 0)
{
Console.SetCursorPosition(0, Console.CursorTop);
Console.Write("Training: ");
Console.Write("(" + (((float)i / (float)batchSize) * 100) + "%)");
Console.Write(" ");
}
// randomly select an image from the list
int number = rng.Next(rangeLow, rangeHi);
int index = rng.Next(1, 20);
Bitmap loadedImage = (Bitmap)Image.FromFile("Train/" + number + "/" +
index + ".png", true);
int indexLocation = 0;
// Convert the image into a grayScale value
for (int x = 0; x < loadedImage.Width; x++)
{
for (int y = 0; y < loadedImage.Height; y++)
{
Color pixel = loadedImage.GetPixel(x, y);
int grayValue = (int)((pixel.R * 0.3) + (pixel.G * 0.59) + (pixel.B * 0.11));
//Console.WriteLine(grayValue);
networkInputs[indexLocation] = grayValue;
indexLocation++;
}
}
// The network will guess what the image is, and return the guess as a float array
float[] guess = currentNetwork.BackPropagate(networkInputs, Interface.valueToArray(number));
// This if statement checks if the guess was correct
if (Interface.guessToValue(guess) == number)
{
hits++;
}
}
currentNetwork.Performance = ((float) hits / (float) batchSize);
hits = 0;
Console.WriteLine("Score: " + (currentNetwork.Performance * 100) + "%");
}
}

added the answer for future visitors
Try converting the grayscale values from 0-255 interval to 0-1
interval. Just divide each pixel with 255. the fact that LeakyRELU
performed better than sigmoid or tanh is because the values are too
large. large in a sense that they get mistreated by tanh and sigmoid
and get rounded by the computer to integers.
Look carefully about how the neural network weights are
initialised if you intend to use tanh or sigmoid.
Since this is a classification problem, I recommend you use a softmax
activation function in your output layer.
after preprocessing the data, #JMC0352 got 88% accuracy only.
the reason why you're getting 88% only is because neural network (alone) is not suitable for image recognition. convolutional neural networks are used for that matter. In order to understand the problem intuitively, you can picture raw neural networks as making sense of all the pixels together, where as conv. nets. make sense of relatively close pixels.

Related

CascadeClassifier in java does not find face with webcam

I am trying to translate the OpenCV CascadeClassifier tutorial from C++ to Java. Working good in C++. Also this java tutorial is working fine.
But the translation is simply not detecting the face. I don't get explicit errors. I can see the processing of the video input from the webcam (grey/histogram...) and the video display. Cascade load doesn't give error. But the CascadeClassifier call just doesn't return any faces... So, you probably can skip all the code and just go to my CascadeClassifier call, down to public Mat detect(Mat inputframe). As I am new to Java and OpenCV, I paste the rest (I removed anything I felt may not be significant), just in case, but don't mean for you to debug that...
I have also tried this call (and other portions) in many different ways and nothing... running out of ideas...
Thank you!!
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
import org.opencv.core.Mat;
import org.opencv.core.MatOfRect;
import org.opencv.highgui.VideoCapture;
import org.opencv.imgproc.Imgproc;
import org.opencv.objdetect.CascadeClassifier;
class My_Panel extends JPanel{
private static final long serialVersionUID = 1L;
private BufferedImage image;
private CascadeClassifier face_cascade;
// Create a constructor method
public My_Panel(){
super();
String face_cascade_name = "/haarcascade_frontalface_alt.xml";
//String face_cascade_name = "/lbpcascade_frontalface.xml";
//-- 1. Load the cascades
String str;
str = getClass().getResource(face_cascade_name).getPath();
str = str.replace("/C:","C:");
face_cascade_name=str;
face_cascade=new CascadeClassifier(face_cascade_name);
if( !face_cascade.empty())
{
System.out.println("--(!)Error loading A\n");
return;
}
else
{
System.out.println("Face classifier loooaaaaaded up");
}
}
private BufferedImage getimage(){
return image;
}
public void setimage(BufferedImage newimage){
image=newimage;
return;
}
/**
* Converts/writes a Mat into a BufferedImage.
*
* #param matrix Mat of type CV_8UC3 or CV_8UC1
* #return BufferedImage of type TYPE_3BYTE_BGR or TYPE_BYTE_GRAY
*/
public BufferedImage matToBufferedImage(Mat matrix) {
int cols = matrix.cols();
int rows = matrix.rows();
int elemSize = (int)matrix.elemSize();
byte[] data = new byte[cols * rows * elemSize];
int type;
matrix.get(0, 0, data);
switch (matrix.channels()) {
case 1:
type = BufferedImage.TYPE_BYTE_GRAY;
break;
case 3:
type = BufferedImage.TYPE_3BYTE_BGR;
// bgr to rgb
byte b;
for(int i=0; i<data.length; i=i+3) {
b = data[i];
data[i] = data[i+2];
data[i+2] = b;
}
break;
default:
return null;
}
BufferedImage image2 = new BufferedImage(cols, rows, type);
image2.getRaster().setDataElements(0, 0, cols, rows, data);
return image2;
}
public void paintComponent(Graphics g){
BufferedImage temp=getimage();
g.drawImage(temp,10,10,temp.getWidth(),temp.getHeight(), this);
}
public Mat detect(Mat inputframe){
Mat mRgba=new Mat();
Mat mGrey=new Mat();
MatOfRect faces = new MatOfRect();
//MatOfRect eyes = new MatOfRect();
inputframe.copyTo(mRgba);
inputframe.copyTo(mGrey);
Imgproc.cvtColor( mRgba, mGrey, Imgproc.COLOR_BGR2GRAY);
Imgproc.equalizeHist( mGrey, mGrey );
face_cascade.detectMultiScale(mGrey, faces);
//face_cascade.detectMultiScale(mGrey, faces, 1.1, 2, 0|Objdetect.CASCADE_SCALE_IMAGE, new Size(30, 30), new Size(200,200) );
//face_cascade.detectMultiScale(mGrey, faces, 1.1, 2, 2//CV_HAAR_SCALE_IMAGE,
// ,new Size(30, 30), new Size(200,200) );
System.out.println(String.format("Detected %s faces", faces.toArray().length));
return mGrey;
}
}
public class window {
public static void main(String arg[]){
// Load the native library.
System.loadLibrary("opencv_java245");
String window_name = "Capture - Face detection";
JFrame frame = new JFrame(window_name);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,400);
My_Panel my_panel = new My_Panel();
frame.setContentPane(my_panel);
frame.setVisible(true);
//-- 2. Read the video stream
BufferedImage temp;
Mat webcam_image=new Mat();
VideoCapture capture =new VideoCapture(0);
if( capture.isOpened())
{
while( true )
{
capture.read(webcam_image);
if( !webcam_image.empty() )
{
frame.setSize(webcam_image.width()+40,webcam_image.height()+60);
//-- 3. Apply the classifier to the captured image
// At this point I was wondering where this should be done.
// I put it within the panel class, but maybe one could actually
// create a processor object...
webcam_image=my_panel.detect(webcam_image);
//-- 4. Display the image
temp=my_panel.matToBufferedImage(webcam_image);
my_panel.setimage(temp);
my_panel.repaint();
}
else
{
System.out.println(" --(!) No captured frame -- Break!");
break;
}
}
}
return;
}
}
PS.: Other info, just in case:
mGrey is: Mat [ 480*640*CV_8UC1, isCont=true, isSubmat=false, nativeObj=0x19d9af48, dataAddr=0x19dc3430 ]
face is: Mat [ 0*0*CV_8UC1, isCont=false, isSubmat=false, nativeObj=0x194bb048, dataAddr=0x0 ]
I have tried your code and it works fine! You have only one issue with haarcascade_frontalface_alt.xml file location. Try to use a full path to the file:
face_cascade= new CascadeClassifier("D:/HelloCV/src/haarcascade_frontalface_alt.xml");

XNA: Position of entities in a list

I am making a vertical platformer. The way I have been placing the platforms is through lists:
public void LoadPlatforms(ContentManager content, Mechanic_Levels mech, Clide clide)
{
platforms.Add(new Entity_Platform());
platforms.Add(new Entity_Platform());
platforms.Add(new Entity_Platform());
platforms.Add(new Entity_Platform());
platforms.Add(new Entity_Platform());
platforms.Add(new Entity_Platform());
platforms.Add(new Entity_Platform());
platforms.Add(new Entity_Platform());
platforms.Add(new Entity_Platform());
// factory.Add(new Entity_Factory());
foreach (Entity_Platform platform in platforms)
{
platform.position = new Vector2(rand.Next(20, 280), rand.Next(20, 580));
platform.currentlevel = rand.Next(12);
platform.LoadPlatform(content);
}
}
This works for if I want randomly placing platforms but how would I set it up so that depending on the current level the platforms reposition themselves individually? I am aware that this will probably mean I can't use lists.
I am not sure if I get you a 100%, but you can sort your Entity_Platforms inside the List<Entity_Platform> by supplying a comparison method like
private static int ComparePlatforms(Entity_Platform x, Entity_Platform y)
{
//compare your platforms according to chosen critieria
//should return 1 if x > y, 0 if x == y, and -1 if x < y
}
Afterwards you can use
platforms.Sort(ComparePlatforms);
See here for an MSDN-example.
I think perhaps a bit of an answer (rather than the comments) is appropriate. I think what you are asking is how to load a collection of platforms for each level based on a predetermine design.
Keeping your current LoadPlatforms method, I would add another method which will get the platforms based on the level. For example:
public List<Entity_Platform> GetPlatformsForLevel(int level)
{
//for this example I will hard-code the platforms, you can pull them from another source if you wish
List<Entity_Platform> platforms = new List<Entity_Platform>();
switch(level)
{
case 1:
{
platforms.Add(new Entity_Platform() { currentLevel = level, position = new Vector2(100, 50) });
platforms.Add(new Entity_Platform() { currentLevel = level, position = new Vector2(200, 100) });
platforms.Add(new Entity_Platform() { currentLevel = level, position = new Vector2(300, 75) });
}
break;
case 2:
{
platforms.Add(new Entity_Platform() { currentLevel = level, position = new Vector2(80, 20) });
platforms.Add(new Entity_Platform() { currentLevel = level, position = new Vector2(160, 200) });
platforms.Add(new Entity_Platform() { currentLevel = level, position = new Vector2(250, 50) });
}
break;
}
return platforms;
}
Then you can call this within your LoadPlatforms method like so:
public void LoadPlatforms(ContentManager content, Mechanic_Levels mech, Clide clide)
{
int currentLevel = 1;//you need to track the current level somewhere
List<Entity_Platform> platforms = GetPlatformsForLevel(currentLevel);
foreach (Entity_Platform platform in platforms)
{
platform.LoadPlatform(content);
}
}

Monogame; Cannot override any methods that have SpriteBatch as parameter

Pretty new to monogame (mono for android to be precise) but with some youtube tutorials the process was fairly pain free.
I'm trying to override some functions (from an "XNA library project" dll) I can override all the functions just fine. But when I try to override anything that passes in a SpriteBatch as an argument I get the follow error:
Error 5 'Parkour.Screens.EditorScreen.Draw(Microsoft.Xna.Framework.Graphics.SpriteBatch)':
no suitable method found to override D:\Data\programming and
such\comps\TIGsport\XNA\Parkour\Parkour\Parkour\Screens\EditorScreen.cs 117 30 ParkourAndroid
I'm absolutely sure the method is there, because the XNA project works just fine.
The Draw function also pops up in autocorrect in the mono for android project. But strange enough it seems to have dissapeared from autocorrect after I received the error.
Here is the entire class which holds the to be override function, just so you guys can be sure nothing is wrong.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
namespace SimpleTilebasedLibrary.Utils
{
public class LoopContainer<T> where T : ILoopable
{
protected List<T> _items = new List<T>();
private List<T> _addList = new List<T>();
private List<T> _removeList = new List<T>();
public List<T> items
{
get{return _items;}
}
public virtual void add(T item)
{
//if (_addList.Contains(item)) return;
//_addList.Add(item);
_items.Add(item);
}
public virtual void remove(T item)
{
if (_removeList.Contains(item)) return;
_removeList.Add(item);
}
public T get(int index)
{
return _items[index];
}
public T get(string name)
{
foreach (T item in items)
{
if (item.getName() == name)
{
return item;
}
}
return default(T);
}
public virtual void Update()
{
items.AddRange(_addList);
_addList.Clear();
foreach (T item in items)
{
if (item.status == Status.DEAD)
{
_removeList.Add(item);
//break; //root of all evil
continue;
}
item.Update();
}
//remove
foreach (T i in _removeList)
{
items.Remove(i);
}
_removeList.Clear();
}
public virtual void postUpdate()
{
foreach (T item in items)
{
item.postUpdate();
}
}
public virtual void Draw(SpriteBatch spritebatch)
{
foreach (T item in items)
{
item.Draw(spritebatch);
}
}
}
}
And the class that is trying to override it
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SimpleTilebasedLibrary;
using SimpleTilebasedLibrary.Entities;
using SimpleTilebasedLibrary.Tilesystem;
using SimpleTilebasedLibrary.Services;
using Microsoft.Xna.Framework.Input;
using SimpleTilebasedLibrary.Components;
using SimpleTilebasedLibrary.Utils;
using SimpleTilebasedLibrary.UI;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace Parkour.Screens
{
public class EditorScreen : GameScreen //need to couple gamescreens with inputcontexts?
{
public ParkourWorld world;
int currentTile = 0;
GameObject tile;
Checkbox editorEnabled;
Checkbox solidCB;
Checkbox autotileCB;
public EditorScreen(ParkourWorld world)
: base("editorscreen")
{
this.world = world;
tile = new GameObject("tileset", 16, 16); //never actually tested this, doesn't work!
tile.GetC<GraphicsC>().setScale(2, 2);
//add(tile); //something fucks up the coordinates when you add it...
editorEnabled = new Checkbox(Color.White, 10);
editorEnabled.GetC<TransformC>().Y = 10;
editorEnabled.GetC<TransformC>().X = 100;
solidCB = new Checkbox(Color.Red, 10);
solidCB.GetC<TransformC>().Y = 10;//30;
solidCB.GetC<TransformC>().X = 120;
//add(solidCB);
autotileCB = new Checkbox(Color.Blue, 10);
autotileCB.GetC<TransformC>().Y = 10;//50;
autotileCB.GetC<TransformC>().X = 140;
//add(autotileCB);
editorEnabled.value = false;
}
public override void Update()
{
base.Update();
if (GameServices.get<InputManager>().hasScrolledDown() && currentTile > 0)
{
currentTile--;
}
if (GameServices.get<InputManager>().hasScrolledUp() && currentTile < tile.GetC<GraphicsC>().totalFrames - 1)
{
currentTile++;
Console.WriteLine(currentTile);
}
tile.GetC<GraphicsC>().gotoAndStop(currentTile);
//
if (Mouse.GetState().LeftButton == ButtonState.Pressed && editorEnabled.value)
{
GameCamera camera = GameServices.get<CameraManager>().getActiveCamera();
int x = TileMath.PixelToTile((Mouse.GetState().X + (camera.GetC<CameraC>().leftX * camera.GetC<CameraC>().zoom)) / camera.GetC<CameraC>().zoom, world.tilegrid.tileWidth);
int y = TileMath.PixelToTile((Mouse.GetState().Y + (camera.GetC<CameraC>().UpY * camera.GetC<CameraC>().zoom)) / camera.GetC<CameraC>().zoom, world.tilegrid.tileHeight);
if (Keyboard.GetState().IsKeyDown(Keys.Z))
{
world.tilegrid.setTile(x, y, 0, null);
//world.tilegrid.getTile(x, y, 0).id = 1;
//world.tilegrid.getTile(x, y, 0).solid = false;
}
else
{
Tile t = world.tilegrid.setTile(x, y, 0, currentTile);
if (t != null) t.solid = solidCB.value;
if(autotileCB.value)world.tilegrid.AutoTile(t, 0, x, y, true);
//world.tilegrid.setTile(x, y, 0, null);
}
}
// enable and disable cb's //
if (GameServices.get<InputManager>().wasKeyPressed(Keys.LeftShift))
{
solidCB.value = !solidCB.value;
}
if (GameServices.get<InputManager>().wasKeyPressed(Keys.Q))
{
autotileCB.value = !autotileCB.value;
}
if (GameServices.get<InputManager>().wasKeyPressed(Keys.E))
{
editorEnabled.value = !editorEnabled.value;
}
solidCB.Update();
autotileCB.Update();
}
public override void Draw(SpriteBatch spritebatch)
{
base.Draw(spritebatch);
tile.Draw(spritebatch);
editorEnabled.Draw(spritebatch);
solidCB.Draw(spritebatch);
autotileCB.Draw(spritebatch);
CameraC camera = GameServices.get<CameraManager>().getActiveCameraC();
int width = TileMath.PixelToTile(camera.viewrect.Left + camera.viewrect.Width + (world.tilegrid.tileWidth * 2), world.tilegrid.tileWidth);
int height = TileMath.PixelToTile(camera.viewrect.Top + camera.viewrect.Height + (world.tilegrid.tileHeight * 2), world.tilegrid.tileHeight);
if (editorEnabled.value)
{
spritebatch.End();
spritebatch.Begin(SpriteSortMode.Deferred, null, SamplerState.PointClamp, null, null, null, GameServices.get<CameraManager>().getActiveCameraC().getTransformation());
//getTile(width - 1, 0).GetComponent<GraphicsC>().sprite.gotoAndStop(4);
Rectangle rect = new Rectangle();
Color trans = new Color(255, 0, 0, 10);
for (int x = TileMath.PixelToTile(camera.viewrect.Left, world.tilegrid.tileWidth); x < width; x++)
{
for (int y = TileMath.PixelToTile(camera.viewrect.Top, world.tilegrid.tileHeight); y < height; y++)
{
if (world.tilegrid.getTile(x, y, 0) != null)
{
if (!world.tilegrid.getTile(x, y, 0).solid) continue;
rect.X = x * world.tilegrid.tileWidth;
rect.Y = y * world.tilegrid.tileHeight;
rect.Width = world.tilegrid.tileWidth;
rect.Height = world.tilegrid.tileHeight;
spritebatch.Draw(GameServices.get<AssetManager>().CreateColoredTexture(trans), rect, Color.White);
}
}
}
spritebatch.End();
spritebatch.Begin();
}
}
}
}
There is alot of useless stuff in there for you guys, but I wanted to include it just for the sake of completeness.
I have the exact same problem with another class that has a Draw(SpriteBatch) function that needs to be overriden.
Turned out that I was passing in a MonoGame spritebatch where the library was requiring an XNA spritebatch. I recompiled the library in a seperate project with MonoGame and all problems are sovled.

How to build a customized list in blackberry 6.0 that can be filtered?

I am new to blackberry development please provide a code snippet if you can?
Check this
You can also check keywordfilterdemo sample app in samples in Blackberry JDE folder
Or you can try this bit of code
Vector v = getElements();
Enumeration iterator = v.elements();
int i = 0;
final Object[] objs = new Object[v.size()];
while (iterator.hasMoreElements()) {
objs[i] = (String) iterator.nextElement();
i++;
}
BasicFilteredList filterList = new BasicFilteredList();
filterList.setMinimumRefreshInterval(250);
filterList.addDataSet(1, objs, "names",
BasicFilteredList.COMPARISON_IGNORE_CASE);
AutoCompleteField autoCompleteField = new AutoCompleteField(
filterList, AutoCompleteField.LIST_STATIC) {
public void drawListRow(ListField listField, Graphics g,
int index, int y, int width) {
super.drawListRow(listField,g,index,y,width);
}
public void onSelect(Object selection, int type) {
super.onSelect(selection, type);
if (selection != null) {
BasicFilteredListResult result = (BasicFilteredListResult) this
.getSelectedObject();
handleResult((String) result._object);
} else {
Dialog.alert("Please pick a valid element");
return;
}
}
};
screenFields.add(autoCompleteField);

Out of memory error when i change the contrast or brightness of an image

I can not find a way to stop the out of memory error. The error occurs when I move the brightness or contrast track bar a few times.
Here is the code from the main form design for the button_click event that that opens the brightness and contrast form and send the value of "foto".
private void menuItemBrightness_Click(object sender, EventArgs e)
{
BrightnessContrast bFrm = new BrightnessContrast();
bFrm.Foto = imageHandler.CurrentBitmap;
if (bFrm.ShowDialog() == DialogResult.OK)
{
this.Cursor = Cursors.WaitCursor;
imageHandler.RestorePrevious();// this is for a undo or redo ... ignore this part
imageHandler.CurrentBitmap = bFrm.Foto1;
pictureBox1.Refresh();
this.Cursor = Cursors.Default;
}
}
Here is the complete code for the brightness and contras form
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
namespace SMART {
public partial class BrightnessContrast : Form {
ImageHandler imageHandler = new ImageHandler();
public int B = 0;
private int C = 0;
private static Bitmap foto;
private static Bitmap foto1;
private static Bitmap NewBitmap;
public BrightnessContrast()
{
this.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint, true);
InitializeComponent();
btnOK.DialogResult = DialogResult.OK;
btnCancel.DialogResult = DialogResult.Cancel;
domainUpDownB.SelectedIndex = 255;
domainUpDownC.SelectedIndex = 75;
}
private void BrightnessForm_Load(object sender, EventArgs e)
{ pictureBox2.Image = foto; }
public Bitmap Foto
{
get { return foto; }
set { foto = value; }
}
public Bitmap Foto1
{
get { return foto1; }
set { foto1 = value; }
}
public void brightnesstrackBar1_ValueChanged(object sender, EventArgs e)
{
domainUpDownB.Text = ((int)brightnessTrackBar.Value).ToString();
B = ((int)brightnessTrackBar.Value);
pictureBox2.Image = AdjustBrightness(foto, B);
foto1 = (Bitmap)pictureBox2.Image;
}
private void domainUpDown_TextChanged(object sender, EventArgs e)
{
try
{
brightnessTrackBar.Value = Convert.ToInt32(domainUpDownB.Text);
brightnesstrackBar1_ValueChanged(sender, e);
}
catch (Exception)
{
MessageBox.Show("Incorect Input Value Format");
}
}
public static Bitmap AdjustBrightness(Bitmap Image, int Value)
{
Bitmap TempBitmap = Image;
float FinalValue = (float)Value / 255.0f;
NewBitmap = new Bitmap(TempBitmap.Width, TempBitmap.Height);
Graphics NewGraphics = Graphics.FromImage(NewBitmap);
float[][] FloatColorMatrix ={
new float[] {1, 0, 0, 0, 0},
new float[] {0, 1, 0, 0, 0},
new float[] {0, 0, 1, 0, 0},
new float[] {0, 0, 0, 1, 0},
new float[] {FinalValue, FinalValue, FinalValue, 1, 1
}
};
ColorMatrix NewColorMatrix = new ColorMatrix(FloatColorMatrix);
ImageAttributes Attributes = new ImageAttributes();
Attributes.SetColorMatrix(NewColorMatrix);
NewGraphics.DrawImage(TempBitmap, new Rectangle(0, 0, TempBitmap.Width, TempBitmap.Height), 0, 0, TempBitmap.Width, TempBitmap.Height, GraphicsUnit.Pixel, Attributes);
Attributes.Dispose();
NewGraphics.Dispose();
return NewBitmap;
}
public void contrastrackBar1_ValueChanged(object sender, EventArgs e)
{
domainUpDownC.Text = ((int)contrastTrackBar.Value).ToString();
C = ((int)contrastTrackBar.Value);
pictureBox2.Image = AdjustContrast(foto, C);
foto1 = (Bitmap)pictureBox2.Image;
}
public static Bitmap AdjustContrast(Bitmap Image, int Value)
{
Bitmap TempBitmap = Image;
float FinalValue = (float)Value*0.04f;
NewBitmap = new Bitmap(TempBitmap.Width, TempBitmap.Height);
Graphics NewGraphics = Graphics.FromImage(NewBitmap);
ImageAttributes Attributes = new ImageAttributes();
ColorMatrix NewColorMatrix = new ColorMatrix (new float[][] {
new float[] {FinalValue, 0f, 0f, 0f, 0f},
new float[] {0f, FinalValue, 0f, 0f, 0f},
new float[] {0f, 0f, FinalValue, 0f, 0},
new float[] {0f, 0f, 0f, 1f, 0f},
new float[] {0.001f, 0.001f, 0.001f, 0f, 1f}
});
Attributes.SetColorMatrix(NewColorMatrix);
NewGraphics.DrawImage(TempBitmap, new Rectangle(0, 0, TempBitmap.Width, TempBitmap.Height), 0, 0, TempBitmap.Width, TempBitmap.Height, GraphicsUnit.Pixel, Attributes);
Attributes.Dispose();
NewGraphics.Dispose();
return NewBitmap;
}
OK here is the problem ... if I load a big image(as in pixels for example) and start moving the track Bar after a few moves it will show the famous "Out of memory exception was unhanded" and the error points to this line
NewGraphics.DrawImage(TempBitmap,
new System.Drawing.Rectangle(0, 0, TempBitmap.Width, TempBitmap.Height), 0, 0,
TempBitmap.Width, TempBitmap.Height, System.Drawing.GraphicsUnit.Pixel,
Attributes);
I am using Attributes.Dispose(); NewGraphics.Dispose(); way i still have the error what I am missing?
Dispose gets rid of the unmanged resources (handles, unmanaged memory). There is probably a managed memory footprint here as well and that only gets free when the garbage collect occurs. My guess is that you need to reuse some of these bigger memory objects rather than having to recreate them each time.

Resources