Machine Imagination Technologies
マシン 想像力 テクノロジー

 

Useful Sample C# Codes

 

loadDataToList ============
private void loadDataToList(string filename, List<string> list, bool ignoreFirstLine)
{
    list.Clear();
    try
    {
        StreamReader sr = new System.IO.StreamReader(filename);
        string line = "";
        if (ignoreFirstLine)
        line = sr.ReadLine();

        while ((line = sr.ReadLine()) != null)
        {
            list.Add(line);
        }
    }
    catch
    {
        //something
    }
}

StreamReader ============
using (StreamReader sr = new StreamReader(filename))
{

    string line = "";
    while ((line = sr.ReadLine()) != null)
    {

        list.Add(line);
    }

}

StreamWriter ============
StreamWriter sw = new System.IO.StreamWriter(indexIndexAllCorrectedFile);

for (int j = 0; j < Flist.Count; j++)
    sw.WriteLine(list[j]);
sw.Close()
StreamWriter ============
using (StreamWriter sw = new StreamWriter(fname))
{

    for (int i = 0; i < list.Count; i++)
        sw.WriteLine(list[i]);
}

StreamWriter ============
void printBuffer(string fname)
{
    using (StreamWriter sw = new StreamWriter(fname))
    {
       for (int j = 0; j < img_height; j++)
        {
            string line = "";
            for (int i = 0; i < img_width; i++)
                line += outImgData[j * img_width + i].ToString() + ",";
            sw.WriteLine(line);
        }
    }
}

Convert8to24Image ============
private void Convert8to24Image(Bitmap bmpSource, Bitmap bmpNew)
{
    // copy image
    BitmapData dataSource = bmpSource.LockBits(new Rectangle(0, 0, bmpSource.Width, bmpSource.Height),
    ImageLockMode.ReadOnly, PixelFormat.Format8bppIndexed);
    BitmapData dataNew = bmpNew.LockBits(new Rectangle(0, 0, bmpNew.Width, bmpNew.Height),
    ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
    int i, j;
    unsafe
    {
        int pos_new;
        byte* pSource = (byte*)(dataSource.Scan0);
        byte* p_new = (byte*)(dataNew.Scan0);
        for (i = 0; i < dataNew.Height; i++)
        {
            for (j = 0; j < dataNew.Width; j++)
            {
                pos_new = 3 * j + i * dataNew.Stride;
                p_new[pos_new] = p_new[pos_new + 1] = p_new[pos_new + 2] = pSource[j + i * dataSource.Stride];
            }
        }
    }
    bmpSource.UnlockBits(dataSource);
    bmpNew.UnlockBits(dataNew);
}

Convert24to8Image ============
private void Convert24to8Image(Bitmap bmpSource, Bitmap bmpNew)
{
    // copy image
    BitmapData data24 = bmpSource.LockBits(new Rectangle(0, 0, bmpSource.Width, bmpSource.Height),
    ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
    BitmapData data8 = bmpNew.LockBits(new Rectangle(0, 0, bmpNew.Width, bmpNew.Height),
    ImageLockMode.ReadWrite, PixelFormat.Format8bppIndexed);
    int i, j;
    unsafe
    {
        int pos24, pos8;
        byte* p24 = (byte*)(data24.Scan0);
        byte* p8 = (byte*)(data8.Scan0);
        for (i = 0; i < data8.Height; i++)
        {
            for (j = 0; j < data8.Width; j++)
            {
                pos8 = j + i * data8.Stride;
                pos24 = 3 * j + i * data24.Stride;
                p8[pos8] = (p24[pos24] + p24[pos24 + 1] + p24[pos24 + 2])/3;
            }
        }
    }
    bmpSource.UnlockBits(data24);
    bmpNew.UnlockBits(data8);
}
  ============
private void killThread(ref Thread runningThread)
{
   if (runningThread != null && runningThread.IsAlive){
      runningThread.Interrupt();
      runningThread.Abort();
   }
}
   
Bitmap Clone ============
//Clone ảnh 24 bit từ 8 bit

public static bool mitechBmpClone(ref Bitmap bmpSrc, ref Bitmap bmpNew)
{
    int width = bmpSrc.Width,
    height = bmpSrc.Height;

    if (bmpNew != null)
    {
        if (bmpSrc.PixelFormat != bmpNew.PixelFormat)
        return false;

        if (bmpNew.Width != width || bmpNew.Height != height)
        return false;
    }

    if (bmpNew == null)
        bmpNew = new Bitmap(width, height, bmpSrc.PixelFormat);

    // đặt lại bảng màu cho ảnh 8 bit
    if (bmpSrc.PixelFormat == System.Drawing.Imaging.PixelFormat.Format8bppIndexed)
    {
        System.Drawing.Imaging.ColorPalette pal = bmpNew.Palette;
        for (int i = 0; i < 256; i++)
        {
            pal.Entries[i] = Color.FromArgb(255, i, i, i);
        }
        bmpNew.Palette = pal;
    }

    // Copy từ bitmap source vào bytes
    Rectangle rect = new Rectangle(0, 0, width, height);
    BitmapData bmpDataSrc = bmpSrc.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadOnly,bmpSrc.PixelFormat);
    byte[] imgByte = new byte[bmpDataSrc.Stride * height];

    // Get the address of the first line.
    IntPtr ptrSrc = bmpDataSrc.Scan0;
    // Declare an array to hold the bytes of the bitmap.
    Marshal.Copy(ptrSrc, imgByte, 0, bmpDataSrc.Stride * height); // 24 bits
    bmpSrc.UnlockBits(bmpDataSrc);

    // Copy từ byte vào bitmap destination
    BitmapData bmpDataNew = bmpNew.LockBits(rect, System.Drawing.Imaging.ImageLockMode.WriteOnly, bmpNew.PixelFormat);
    IntPtr ptrNew = bmpDataNew.Scan0;
    // Copy the array values to bimap image.
    Marshal.Copy(imgByte, 0, ptrNew, bmpDataNew.Stride * height); // 24 bits
    bmpNew.UnlockBits(bmpDataNew);

    return true;
}
Convert24to8Image ============
private Bitmap Convert24to8Image(ref Bitmap bmpSource)
{
   Bitmap bmpNew = new Bitmap(bmpSource.Width, bmpSource.Height, PixelFormat.Format8bppIndexed);
   // copy image
   BitmapData data24 = bmpSource.LockBits(new Rectangle(0, 0, bmpSource.Width, bmpSource.Height),
   ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
   BitmapData data8 = bmpNew.LockBits(new Rectangle(0, 0, bmpNew.Width, bmpNew.Height),
   ImageLockMode.ReadWrite, PixelFormat.Format8bppIndexed);
   int i, j;
   unsafe
   {
      int pos24, pos8;
      byte* p24 = (byte*)(data24.Scan0);
      byte* p8 = (byte*)(data8.Scan0);
      for (i = 0; i < data8.Height; i++)
      {
         for (j = 0; j < data8.Width; j++)
         {
            pos8 = j + i * data8.Stride;
            pos24 = 3 * j + i * data24.Stride;
            int val1 = p24[pos24];
            int val2 = p24[pos24 + 1];
            int val3 = p24[pos24 + 2];
            int val = ((int)p24[pos24] + (int)p24[pos24 + 1] + (int)p24[pos24 + 2]) / 3;
            p8[pos8] = (byte)(val);
         }
      }
   }
   bmpSource.UnlockBits(data24);
   bmpNew.UnlockBits(data8);
   bmpSet256ColorPalette(ref bmpNew);
   return bmpNew;
}
Convert8to24Image ============
private Bitmap Convert8to24Image(ref Bitmap bmpSource)
{
   Bitmap bmpNew = new Bitmap(bmpSource.Width, bmpSource.Height, PixelFormat.Format24bppRgb);
   // copy image
   BitmapData data24 = bmpNew.LockBits(new Rectangle(0, 0, bmpSource.Width, bmpSource.Height),
   ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
   BitmapData data8 = bmpSource.LockBits(new Rectangle(0, 0, bmpNew.Width, bmpNew.Height),
   ImageLockMode.ReadWrite, PixelFormat.Format8bppIndexed);
   int i, j;
   unsafe
   {
      int pos24, pos8;
      byte* p24 = (byte*)(data24.Scan0);
      byte* p8 = (byte*)(data8.Scan0);
      for (i = 0; i < data8.Height; i++)
      {
         for (j = 0; j < data8.Width; j++)
         {
            pos8 = j + i * data8.Stride;
            pos24 = 3 * j + i * data24.Stride;
            p24[pos24] = p24[pos24 + 1] = p24[pos24 + 2] = p8[pos8];
         }
      }
   }
   bmpSource.UnlockBits(data24);
   bmpNew.UnlockBits(data8);
   return bmpNew;
}
Bitmat Free ============
public static void mitechBmpFree(ref Bitmap bmpSrc)
{
    if (bmpSrc == null)
        return;
    bmpSrc.Dispose();
    bmpSrc = null;
}
Bitmap Clone ============
public static Bitmap mitechBmpClone(ref Bitmap bmpSrc)
{
    Bitmap bmpNew = new Bitmap(bmpSrc.Width, bmpSrc.Height, bmpSrc.PixelFormat);
    mitechBmpClone(ref bmpSrc, ref bmpNew);
    return bmpNew;
}
Emgu Mat => C# Bitmap ============
// biến đổi Emgu Mat thành C# Bitmap
private static void mitechMatToBitMap(ref Mat mat, ref Bitmap bmp)
{
    if (bmp != null){
        bmp.Dispose();
        bmp = null;
    }

    // 1. clone mat thành Bitmap
    Bitmap tmp = (Bitmap)mat.Bitmap.Clone();

    // 2. clone lại vào biến mới
    bmp = mitechBmpClone(ref tmp);
    tmp.Dispose();
}
Set color pallete ============
// Hàm set color pallete cho ảnh 8 bit
private static void bmpSet256ColorPalette(ref Bitmap bmpIn)
{
    System.Drawing.Imaging.ColorPalette pal = bmpIn.Palette;
    for (int i = 0; i < 256; i++)
    {
        pal.Entries[i] = Color.FromArgb(255, i, i, i);
    }
    bmpIn.Palette = pal;
}

// khi dùng
if (bmpSrc.PixelFormat == System.Drawing.Imaging.PixelFormat.Format8bppIndexed)
    bmpSet256ColorPalette(ref bmpNew);
C# Bitmap => Emgu Mat ============
// biến đổi C# Bitmap sang Emgu Mat
// 1. biến bitmap c#
Bitmap tmp = gInlineCameraBmp.Clone(roiRect, gInlineCameraBmp.PixelFormat);

// 2. khai báo biến Image (emgu)
Image<Bgr, byte> image ;// = new Image<Bgr, byte>(image path or Bitmap)

// 3. trỏ Image này đến bmp
image = new Image<Bgr, byte>(tmp);

// 4. khai báo biến emgu mat trỏ đến Image.Mat
matImage = image.Mat;
C# Bitmap <=> Emgu Mat ============
// ví dụ chuyển đổi giữa Bmp ↔ Image<Gray, Byte> hoặc Mat
private void btnTestConvertImage()
{
   Bitmap bmp = new Bitmap(750,250);
   using (Graphics gr = Graphics.FromImage(bmp))
   {
      gr.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
      gr.Clear(this.BackColor);

      RectangleF rectf = new RectangleF(10, 100, bmp.Width-20, bmp.Height-20);
      gr.SmoothingMode = SmoothingMode.AntiAlias;
      gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
      gr.PixelOffsetMode = PixelOffsetMode.HighQuality;
      gr.DrawString("Machine Imagination Technologies", new Font("Tahoma", 32), Brushes.Black, rectf);
      gr.Flush();
   }
   bmp.Save(@"C:\TMP\bmp.bmp");

   // tạo Image<Gray, Byte> hoặc Mat từ Bitmap
   Image<Gray, Byte> bmp_img = new Image<Gray, byte>(bmp);
   Mat bmp_img_mat = bmp_img.Mat;

   // có thể dispose bmp
   bmp.Dispose();
   bmp = null;

   // lưu ảnh Image<Gray, Byte> hoặc Mat
   bmp_img.Save(@"C:\TMP\bmp_img.bmp");
   bmp_img_mat.Save(@"C:\TMP\bmp_img_mat.bmp");

   // tạo ảnh Bitmap từ Image<Gray, Byte> hoặc Mat
   Bitmap bmp_img_bmp = bmp_img.Bitmap;
   Bitmap bmp_img_mat_bmp = bmp_img_mat.Bitmap;

   // có thể dispose Image<Gray, Byte> hoặc Mat
   bmp_img.Dispose();
   bmp_img_mat.Dispose();

   // lưu ảnh bmp
   bmp_img_bmp.Save(@"C:\TMP\bmp_img_bmp.bmp");
   bmp_img_mat_bmp.Save(@"C:\TMP\bmp_img_mat_bmp.bmp");

   bmp_img_bmp.Dispose();
   bmp_img_mat_bmp.Dispose();
}
Bitwise Example ============
// ví dụ dùng các hàm Bitwise
private void btnTestAndOrImage_Click(object sender, EventArgs e)
{
   Bitmap bmp = new Bitmap(750, 250);
   using (Graphics gr = Graphics.FromImage(bmp))
   {
      gr.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
      gr.Clear(Color.Aquamarine);
      RectangleF rectf = new RectangleF(10, 100, bmp.Width - 20, bmp.Height - 20);
      gr.DrawString("Machine Imagination Technologies", new Font("Tahoma", 32), Brushes.Black, rectf);
      gr.Flush();
   }
   bmp.Save(@"C:\TMP\bmp.bmp");

   // tạo Image<Gray, Byte> hoặc Mat từ Bitmap
   Image<Gray, Byte> bmp_img = new Image<Gray, byte>(bmp);
   Mat bmp_img_mat = bmp_img.Mat;

   // có thể dispose bmp
   bmp.Dispose();
   bmp = null;

   Image<Gray, Byte> bmp_img_dil1 = bmp_img.Dilate(1);
   Image<Gray, Byte> bmp_img_dil2 = bmp_img.Dilate(2);

   Mat imgOR = new Mat();
   Mat imgXOR = new Mat();
   Mat imgAND = new Mat();
   Mat imgNOT = new Mat();


   CvInvoke.BitwiseOr(bmp_img_dil1, bmp_img_dil2, imgOR);
   CvInvoke.BitwiseXor(bmp_img_dil1, bmp_img_dil2, imgXOR);
   CvInvoke.BitwiseAnd(bmp_img_dil1, bmp_img_dil2, imgAND);
   CvInvoke.BitwiseNot(bmp_img_dil1, imgNOT);

   bmp_img_dil1.Save(@"C:\TMP\bmp_img_dil1.bmp");
   bmp_img_dil2.Save(@"C:\TMP\bmp_img_dil2.bmp");

   // có thể save thế này
   // bmp_img_dil1.ToBitmap().Save(@"C:\TMP\bmp_img_dil1.bmp");
   // bmp_img_dil2.ToBitmap().Save(@"C:\TMP\bmp_img_dil2.bmp");

   imgOR.Save(@"C:\TMP\OR.bmp");
   imgXOR.Save(@"C:\TMP\XOR.bmp");
   imgAND.Save(@"C:\TMP\AND.bmp");
   imgNOT.Save(@"C:\TMP\NOT.bmp");
}
  ============
// blur ảnh
CvInvoke.Blur(image, mage, new Size(3, 3), new Point(-1, -1));
CvInvoke.MedianBlur(mage, mage, 5);
Biến đổi Image ↔ Mat ============
//Convert Image<Gray,byte> to Mat
Mat mat = image.Mat;
  ============
// Mat.ToImage
Mat frame = new Mat();
capture.Retrieve(frame, 0);
Image<Bgr, byte> image = frame.ToImage<Bgr, byte>();
   
   
   
Biến đổi _bmpTmp => _eImage ============
// biến đổi _bmpTmp => _eImage, hai ảnh này phải đi với nhau thành một cặp và dispose cùng nhau
private int convertBitmapToEImage(ref Bitmap input, ref EImageBW8 output)
{
    try
    {
        if (input != null)
        {
            if (input.PixelFormat != PixelFormat.Format8bppIndexed)
                return -1;
            BitmapData bmpdata = input.LockBits(new Rectangle(0, 0, input.Width, input.Height),
                    ImageLockMode.ReadOnly, input.PixelFormat);
            IntPtr bufferAddress = default(IntPtr);
            bufferAddress = bmpdata.Scan0;
            output.SetImagePtr(input.Width, input.Height, bufferAddress, 0);
            return 0;
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex);
        throw ex;
    }
        return -1;
}
Khai báo cặp _eImage & _bmpTmp ============
// khai báo cặp _eImage & _bmpTmp
Bitmap _bmpTmp = (Bitmap)gMatImage.Bitmap.Clone();
EImageBW8 _eImage = new EImageBW8();
convertBitmapToEImage(ref _bmpTmp, ref _eImage);

// dispose cặp _eImage & _bmpTmp
_eImage.Dispose();
_eImage = null;
_bmpTmp.Dispose();
_bmpTmp = null;
Copy ảnh ============
//copy ảnh (cần EasyImage License)
EImageBW8 eiOut = new EImageBW8(eiTmp.Width, eiTmp.Height);
eiTmp.CopyTo(eiOut);
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
Get List of Image File Names // return list of image filenames
private List<string> GetImageFileList(string path)
{
   if (!Directory.Exists(path))
      MessageBox.Show("Folder does not exist:\r\n" + path);
      string[] filePaths = Directory.GetFiles(@path);
      List<string> fileList = new List<string>();
      if (Directory.Exists(path))
      {
         for (int i = 0; i < filePaths.Length; i++)
         {
            FileInfo fi = new FileInfo(filePaths[i]);
            if (fi.Extension == ".bmp" || fi.Extension == ".jpg" || fi.Extension == ".png" ||
                  fi.Extension == ".BMP" || fi.Extension == ".JPG" || fi.Extension == ".PNG")
            {
               fileList.Add(filePaths[i]);
            }
         }
      }
   return fileList;
}
Tự động scaling đồ thị ============
// tự động scaling đồ thị (0 ~ 255)
this.chart.Invoke((Action)(() => chart.ChartAreas[0].AxisY.IsStartedFromZero = true));
this.chart.Invoke((Action)(() => chart.ChartAreas[0].AxisY.Maximum = 0));
this.chart.Invoke((Action)(() => chart.ChartAreas[0].AxisY.Minimum = 255));
this.chart.Invoke((Action)(() => chart.ChartAreas[0].RecalculateAxesScale()));
Một số hàm set giá trị ============
// set inside
int set_inside(int x, int a, int b)
{
    return (x<b) ? ((x > a)? x : a) : b;
}
// set x trong [0~255]
byte set_in_0_255(int x)
{
    return (byte)((x < 255) ? ((x > 0) ? x : 0) : 255);
}

// set x has value >= b, such as : x >= 0
int set_more_than(int x, int b)
{
    return (x < b) ? b : x;
}

// set x has value <= b, such as x >= 0)
int set_less_than(int x, int b)
{
    return (x > b) ? b : x;
}
int max(int a, int b)
{
    return (a < b) ? b : a;
}
int min(int a, int b)
{
    return (a < b) ? a : b;
}
   

 

 

 

Copyright©2016 Machine Imagination Technologies. All rights reserved.