Search code examples
c#neural-networkocrpicturebox

enlarge / shrink PictureBox but maintain pixel ratio c#


I could not find a better title. So this is what I want to do:

I have a picturebox that is 28x28 pixels

I am working on a AI project and my idea is to make an OCR for numbers,

I found training data but all the images are 28x28 pixels, so my ideea is to make a picturebox that size,

draw on it and feed that info to the neural network.

My problem is graphicly for the moment:

How do I make a 28x28 picturebox and somehow enlarge it but maintain the pixel count. I put the picturebox into a panel and I want the picturebox to fill the panel.

My idea would be to somehow scale it up and after drawing on it scale it back down, but how can I accomplish this?

mathematically how can this be done?

And what would be the best way to draw on that picturebox (line, fillelipse , etc) so the data could be feed into the NN (after normalizing it ofc).


Solution

  • I figured out a solution , maybe it will help someone in the future:

            List<KeyValuePair<int, int>> coordonateList = new List<KeyValuePair<int, int>>();
            // drawPictureBox size is 280 x 280  (28 * 10, 28 * 10)
    
    
    
            private void pbImage_MouseDown(object sender, MouseEventArgs e)
            {
                mouseDown = true;
    
            }
    
            private void drawPictureBox_MouseMove(object sender, MouseEventArgs e)
            {
                if (mouseDown)
                {
                    Point point = drawPictureBox.PointToClient(Cursor.Position);
                    DrawPoint((point.X), (point.Y));
                }
            }
    
            private void drawPictureBox_MouseUp(object sender, MouseEventArgs e)
            {
                mouseDown = false;
            }
    
            public void DrawPoint(int x, int y)
            {
    
                using (Graphics g = Graphics.FromImage(bitmap))
                {
                    SolidBrush brush = new SolidBrush(Color.White);
                    g.FillRectangle(brush, x, y, 10, 10);
                    coordonateList.Add(new KeyValuePair<int,int>(x/10,y/10));
                }
                drawPictureBox.Image = bitmap;
            }
            private void zoomImage(Bitmap bitmap)
            {
                var result = new Bitmap(28,28);
                using (Graphics g1 = Graphics.FromImage(result))
                {
                    SolidBrush brush = new SolidBrush(Color.White);
    
                    foreach (var item in coordonateList)
                    {
                        g1.FillRectangle(brush, item.Key, item.Value, 1, 1);
                    }
                pictureBox1.Image = result;
    
            }