public static void readIdx3Train() { trainImages = new List <DigitImage>(); try { FileStream ifsLabels = new FileStream(@"train-labels.idx1-ubyte", FileMode.Open); // test labels FileStream ifsImages = new FileStream(@"train-images.idx3-ubyte", FileMode.Open); // test images BinaryReader brLabels = new BinaryReader(ifsLabels); BinaryReader brImages = new BinaryReader(ifsImages); int magic1 = brImages.ReadInt32(); // discard int numImages = brImages.ReadInt32(); int numRows = brImages.ReadInt32(); int numCols = brImages.ReadInt32(); int magic2 = brLabels.ReadInt32(); int numLabels = brLabels.ReadInt32(); byte[,] pixels = new byte[28, 28]; //for (int i = 0; i < pixels.Length; ++i) // pixels[i] = new byte[28]; // each test image for (int di = 0; di < 60000; ++di) { for (int i = 0; i < 28; ++i) { for (int j = 0; j < 28; ++j) { byte b = brImages.ReadByte(); pixels[i, j] = b; } } byte lbl = brLabels.ReadByte(); DigitImage dImage = new DigitImage(pixels, lbl); trainImages.Add(dImage); } ifsImages.Close(); brImages.Close(); ifsLabels.Close(); brLabels.Close(); } catch (Exception ex) { } }
public static byte Classify(DigitImage digitImage, List <DigitImage> trainingSet, int k) { int[] count = new int[10]; List <KeyValuePair <double, byte> > sortedDiff = new List <KeyValuePair <double, byte> >(); foreach (DigitImage trainingImage in trainingSet) { double diff = 0.0f; for (int i = 0; i < 28; i++) { for (int j = 0; j < 28; j++) { diff += (digitImage.pixels[i, j] - trainingImage.pixels[i, j]) * (digitImage.pixels[i, j] - trainingImage.pixels[i, j]); } } diff = Math.Sqrt(diff); KeyValuePair <double, byte> p = new KeyValuePair <double, byte>(diff, trainingImage.label); sortedDiff.Add(p); } int index = 0; sortedDiff.Sort(Compare); foreach (KeyValuePair <double, byte> diff in sortedDiff) { count[diff.Value]++; index++; if (index == k) { break; } } int max = 0; byte Class = 0; for (byte i = 0; i < 10; i++) { if (count[i] > max) { Class = i; max = count[i]; } } return(Class); }
private void Classify_button_Click(object sender, EventArgs e) { Bitmap drawnImage = new Bitmap(pictureBox1.Image); Bitmap resized = new Bitmap(drawnImage, new Size(28, 28)); pictureBox1.Image = resized; byte[,] arr = new byte[28, 28]; for (int i = 0; i < 28; i++) { for (int j = 0; j < 28; j++) { arr[i, j] = resized.GetPixel(j, i).R; } } DigitImage DI = new DigitImage(arr, 0); byte pred = KNN.Classify(DI, ReadingInput.trainImages, Convert.ToInt32(K_text.Text)); predicion_text.Text = pred.ToString(); }