Esempio n. 1
0
 public void Apply(BitmapData tileset, BitmapData background)
 {
     if (this.chunklist == null)
         return;
     foreach (TilesetPatchChunk tilesetPatchChunk in this.chunklist)
         tilesetPatchChunk.Apply(tileset, background);
 }
Esempio n. 2
0
        public static void Circle(BitmapData bmpData, int Size, int X, int Y, Color Colour)
        {
            CacheCircles(Size);

            int tempX;
            int i = 0;
            for (int tempY = Y - Size; tempY < Y + Size; tempY++)
            {
                if (tempY >= 0)
                {
                    if (tempY >= bmpData.Height)
                    {
                        break;
                    }
                    tempX = X - CircleCache[Size][i];
                    while (tempX < CircleCache[Size][i] + X)
                    {
                        if (tempX >= 0)
                        {
                            if (tempX >= bmpData.Width)
                            {
                                break;
                            }
                            IntPtr temp = FindPtr(bmpData, tempX, tempY);
                            System.Runtime.InteropServices.Marshal.WriteInt32(temp, Colour.ToArgb());
                        }

                      tempX++;
                    }
                }
                i++;
            }
        }
Esempio n. 3
0
		/// <summary>
		/// Lock bitmap data
		/// </summary>
		public void Lock() {
			try {
				// Get width and height of bitmap
				Width = Bitmap.Width;
				Height = Bitmap.Height;

				// get total locked pixels count
				int pixelCount = Width * Height;

				// Create rectangle to lock
				Rectangle rect = new Rectangle(0, 0, Width, Height);

				// get Bitmap bitmap pixel format size
				Depth = Image.GetPixelFormatSize(Bitmap.PixelFormat);

				// Check if bpp (Bits Per Pixel) is 8, 24, or 32
				if (Depth != 8 && Depth != 24 && Depth != 32) {
					throw new ArgumentException("Only 8, 24 and 32 bpp images are supported.");
				}

				// Lock bitmap and return bitmap data
				bitmapData = Bitmap.LockBits(rect, ImageLockMode.ReadWrite,
				                             Bitmap.PixelFormat);

				// create byte array to copy pixel values
				int step = Depth / 8;
				Pixels = new byte[pixelCount * step];
				iptr = bitmapData.Scan0;

				// Copy data from pointer to array
				Marshal.Copy(iptr, Pixels, 0, Pixels.Length);
			} catch (Exception ex) {
				throw;
			}
		}
Esempio n. 4
0
 /// <summary>
 /// Copy the image buffer back to bitmapdata, then copy it to the original bitmap (image).
 /// </summary>
 private void releaseArray()
 {
     Marshal.Copy(imageBuffer, 0, bitmapData.Scan0, bitmapData.Stride * bitmap.Height);
     bitmap.UnlockBits(bitmapData);
     bitmapData = null;
     imageBuffer = null;
 }
Esempio n. 5
0
        public JBitmap(int w, int h, JBitmapPixelFormat _format)
        {

            format = _format;
            bitmap = new Bitmap(w, h, GetPixFormat(format));
            bitmapData = bitmap.LockBits(new Rectangle(0, 0, w, h),ImageLockMode.ReadWrite, GetPixFormat(format));
        }
Esempio n. 6
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DesktopSurfaceSource"/> class.
        /// </summary>
        /// <param name="bmp">The bitmap from which to read surface data.</param>
        public DesktopSurfaceSource(Bitmap bmp)
        {
            Contract.Require(bmp, nameof(bmp));

            this.bmp = bmp;
            this.bmpData = bmp.LockBits(new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
        }
Esempio n. 7
0
 public static void BltBitmap(IntPtr dstPixels, Size dstSize,
     int dstX, int dstY, int width, int height,
     BitmapData srcBD, int srcX, int srcY)
 {
     Debug.Assert(srcBD.PixelFormat == PixelFormat.Format32bppArgb);
     Size srcSize = new Size(srcBD.Width, srcBD.Height);
     if (!ModifyRectangle(dstSize, ref dstX, ref dstY, ref width, ref height, srcSize, ref srcX, ref srcY))
     {
         return;
     }
     unsafe
     {
         int dstStride = (dstSize.Width * 4 + 3) / 4 * 4;
         Debug.Assert(srcBD.Stride % 4 == 0);
         int* dst = (int*)dstPixels + dstX + (dstY * dstStride / 4);
         int* src = (int*)srcBD.Scan0 + srcX + (srcY * srcBD.Stride / 4);
         int paddingDst = dstStride / 4 - width;
         int paddingSrc = srcBD.Stride / 4 - width;
         Debug.Assert(0 <= paddingDst);
         Debug.Assert(0 <= paddingSrc);
         for (int j = 0; j < height; j++, dst += paddingDst, src += paddingSrc)
         {
             for (int i = 0; i < width; i++, dst++, src++)
             {
                 *dst = *src;
             }
         }
     }
 }
Esempio n. 8
0
        public static unsafe void GammaCorrect(double gamma, BitmapData imageData)
        {
            gamma = Math.Max(0.1, Math.Min(5.0, gamma));
            var y = 1.0 / gamma;
            var table = new byte[0x100];
            for (var x = 0; x < 0x100; x++)
            {
                table[x] = (byte)Math.Min(0xff,
                    (int)((Math.Pow((x) / 255.0, y) * 255.0) + 0.5));
            }

            var width = imageData.Width;
            var height = imageData.Height;
            var num3 = width * ((imageData.PixelFormat == PixelFormat.Format8bppIndexed) ? 1 : 3);
            var num4 = imageData.Stride - num3;
            var numPtr = (byte*)imageData.Scan0.ToPointer();
            for (var i = 0; i < height; i++)
            {
                var num6 = 0;
                while (num6 < num3)
                {
                    numPtr[0] = table[numPtr[0]];
                    num6++;
                    numPtr++;
                }
                numPtr += num4;
            }
        }
Esempio n. 9
0
        /// <summary>
        /// Returns try if the given pixel is empty (i.e. alpha is zero)
        /// </summary>
        public static unsafe bool EmptyAlphaPixel(BitmapData bitmapData, int px, int py, byte alphaEmptyPixelTolerance)
        {

            byte* addr = (byte*)(bitmapData.Scan0) + bitmapData.Stride * py + px * 4;
            return (*(addr + 3) <= alphaEmptyPixelTolerance);

        }
Esempio n. 10
0
 public void DrawImg()
 {
     imgData = img.LockBits(
         new Rectangle(0, 0, Width, Height),
         ImageLockMode.ReadWrite,
         PixelFormat.Format32bppArgb);
 }
        public Bitmap Apply(Bitmap srcimg, Hashtable positive_table,int tnum)
        {
            this.srcimg = ImageUtils.AnyToFormat24bppRgb(srcimg);

            Height = srcimg.Height;
            Width = srcimg.Width;
            this.tnum = tnum;
            this.positive_table = positive_table;

            dstimg = new Bitmap(srcimg.Width, srcimg.Height, PixelFormat.Format24bppRgb);

            srcData = srcimg.LockBits(
                new Rectangle(0, 0, srcimg.Width, srcimg.Height),
                ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);

            dstData = dstimg.LockBits(
                new Rectangle(0, 0, srcimg.Width, srcimg.Height),
                ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);

            Thread[] thread_array = new Thread[tnum];
            for (int i = 0; i < tnum; i++)
            {
                thread_array[i] = new Thread(new ParameterizedThreadStart(Run));
                thread_array[i].Start(i);
            }
            for (int i = 0; i < tnum; i++)
                thread_array[i].Join();

            srcimg.UnlockBits(srcData);
            dstimg.UnlockBits(dstData);
            return dstimg;
        }
Esempio n. 12
0
 internal static Bitmap Apply(BitmapData bitmapData1)
 {
     Bitmap returnMap = new Bitmap(bitmapData1.Width, bitmapData1.Height, PixelFormat.Format32bppArgb);
     BitmapData bitmapData2 = returnMap.LockBits(new Rectangle(0, 0,
                              returnMap.Width, returnMap.Height),
                              ImageLockMode.ReadOnly,
                              PixelFormat.Format32bppArgb);
     unsafe
     {
         byte* imagePointer1 = (byte*)bitmapData1.Scan0;
         byte* imagePointer2 = (byte*)bitmapData2.Scan0;
         for (int i = 0; i < bitmapData1.Height; i++)
         {
             for (int j = 0; j < bitmapData1.Width; j++)
             {
                 // Standard Invert algorithm
                 imagePointer2[0] = (byte)(255 - imagePointer1[0]);
                 imagePointer2[1] = (byte)(255 - imagePointer1[1]);
                 imagePointer2[2] = (byte)(255 - imagePointer1[2]);
                 imagePointer2[3] = imagePointer1[3];
                 //4 bytes per pixel
                 imagePointer1 += 4;
                 imagePointer2 += 4;
             }
             //4 bytes per pixel
             imagePointer1 += bitmapData1.Stride - (bitmapData1.Width * 4);
             imagePointer2 += bitmapData1.Stride - (bitmapData1.Width * 4);
         }
     }
     returnMap.UnlockBits(bitmapData2);
     return returnMap;
 }
Esempio n. 13
0
        // Process the filter
        private unsafe void ProcessFilter( BitmapData data )
        {
            int width	= data.Width;
            int height	= data.Height;
            int offset	= data.Stride - width * 3;

            // do the job
            byte * ptr = (byte *) data.Scan0.ToPointer( );
            byte t;

            // for each line
            for ( int y = 0; y < height; y++ )
            {
                // for each pixel
                for ( int x = 0; x < width; x++, ptr += 3 )
                {
                    // rotate colors of each pixel
                    t = ptr[RGB.R];
                    ptr[RGB.R] = ptr[RGB.G];
                    ptr[RGB.G] = ptr[RGB.B];
                    ptr[RGB.B] = t;
                }
                ptr += offset;
            }
        }
Esempio n. 14
0
        /// <summary>
        /// Returns try if the given pixel is empty (i.e. black)
        /// </summary>
        public static unsafe bool EmptyPixel(BitmapData bitmapData, int px, int py)
        {

            byte* addr = (byte*)(bitmapData.Scan0) + bitmapData.Stride * py + px * 3;
            return (*addr == 0 && *(addr + 1) == 0 && *(addr + 2) == 0);

        }
Esempio n. 15
0
 protected virtual void Draw_PANEL_Image(BitmapData data_bac)
 {
     foreach (var a in CONTROLS)
     {
         a.Value.DrawImage(data_bac);
     }
 }
        private void InitializeBuffer()
        {
            bitmapData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height),
                ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);

            imageBuffer = new byte[bitmapData.Stride * bitmap.Height];
        }
Esempio n. 17
0
 public static void DrawImageAll(BitmapData data_bac)
 {
     for (int i = 0; i < STATIONS.Count; i++)
     {
         STATIONS[i].Draw_Image(data_bac);
     }
 }
 /// <summary>
 /// Bitmap処理の高速化開始
 /// </summary>
 public void BeginAccess()
 {
     // Bitmapに直接アクセスするためのオブジェクト取得(LockBits)
     _img = _bmp.LockBits(new Rectangle(0, 0, _bmp.Width, _bmp.Height),
         System.Drawing.Imaging.ImageLockMode.ReadWrite,
         System.Drawing.Imaging.PixelFormat.Format24bppRgb);
 }
Esempio n. 19
0
 public static void DrawExteriorAll(BitmapData data_bac)
 {
     for (int i = 0; i < STATIONS.Count; i++)
     {
         STATIONS[i].Draw_Exterior(data_bac);
     }
 }
Esempio n. 20
0
 public RawBitmap(Bitmap originBitmap)
 {
     OriginBitmap = originBitmap;
     _bitmapData = OriginBitmap.LockBits(new Rectangle(0, 0, OriginBitmap.Width, OriginBitmap.Height),
                                         ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
     _begin = (byte*) (void*) _bitmapData.Scan0;
 }
Esempio n. 21
0
 public static unsafe void drawClearWithBackground(Rectangle srcArea, BitmapData srcData, Rectangle dstArea, BitmapData dstData, BitmapData bgData)
 {
     if (srcData == null)
         return;
     int stride1 = srcData.Stride;
     int num1 = (int)srcData.Scan0 + srcArea.X * 4 + srcArea.Y * stride1;
     if (dstData == null)
         return;
     int stride2 = dstData.Stride;
     int num2 = (int)dstData.Scan0 + dstArea.X * 4 + dstArea.Y * stride2;
     if (bgData == null)
         return;
     int stride3 = bgData.Stride;
     int num3 = (int)bgData.Scan0 + dstArea.X * 4 + dstArea.Y * stride3;
     int width = srcArea.Width;
     int height = srcArea.Height;
     for (int index1 = 0; index1 < height; ++index1) {
         int num4 = num1 + index1 * stride1;
         int num5 = num2 + index1 * stride2;
         int num6 = num3 + index1 * stride3;
         for (int index2 = 0; index2 < width; ++index2) {
             *(PixelData*)num5 = PixelData.overlayPixelData(*(PixelData*)num4, *(PixelData*)num6);
             num4 += 4;
             num5 += 4;
             num6 += 4;
         }
     }
 }
        public virtual Bitmap Apply(BitmapData imageData)
        {
            if (imageData.PixelFormat != PixelFormat.Format24bppRgb &&
                imageData.PixelFormat != PixelFormat.Format32bppArgb &&
                imageData.PixelFormat != PixelFormat.Format32bppRgb)
            {
                throw new ArgumentException();
            }

            int width = imageData.Width;
            int height = imageData.Height;

            Bitmap bitmap = new Bitmap(
                width, height, PixelFormat.Format24bppRgb);
            BitmapData bitmapdata = bitmap.LockBits(
                new Rectangle(0, 0, width, height),
                ImageLockMode.ReadWrite,
                PixelFormat.Format24bppRgb);

            NativeMethods.memcpy(
                bitmapdata.Scan0,
                imageData.Scan0,
                imageData.Stride * height);
            ProcessFilter(bitmapdata);
            bitmap.UnlockBits(bitmapdata);
            return bitmap;
        }
Esempio n. 23
0
 public override void DrawImage(BitmapData data_bac)
 {
     for(int i=0;i<CANNONS.Length;i++)
     {
         CANNONS[i].DrawImage(data_bac);
     }
 }
Esempio n. 24
0
 /// <summary>
 /// Creates a new instance of Smoother
 /// </summary>
 public Smoother(BitmapData inBmpData, byte[] inRgbData, IProgressHandler progHandler)
 {
     _bmpData = inBmpData;
     _rgbData = inRgbData;
     _result = new byte[inRgbData.Length];
     pm = new ProgressMeter(progHandler, "Smoothing Image", inBmpData.Height);
 }
Esempio n. 25
0
 /// <summary>
 /// Required to use the image after editing.
 /// </summary>
 public void Unlock()
 {
     System.Runtime.InteropServices.Marshal.Copy(PixelData, 0, BmpData.Scan0, PixelData.Length);
     BitmapImage.UnlockBits(BmpData);
     BmpData = null;
     PixelData = null;
 }
Esempio n. 26
0
        /// <summary>
        /// Lock bitmap data
        /// </summary>
        public void LockBits()
        {
            // Get width and height of bitmap
            Width = Source.Width;
            Height = Source.Height;

            // get total locked pixels count
            var pixelCount = Width*Height;

            // Create rectangle to lock
            var rect = new Rectangle(0, 0, Width, Height);

            // get source bitmap pixel format size
            Depth = Image.GetPixelFormatSize(Source.PixelFormat);

            // Check if bpp (Bits Per Pixel) is 8, 24, or 32
            if (Depth != 8 && Depth != 24 && Depth != 32)
                throw new ArgumentException("Only 8, 24 and 32 bpp images are supported.");

            // Lock bitmap and return bitmap data
            _bitmapData = Source.LockBits(rect, ImageLockMode.ReadWrite, Source.PixelFormat);

            // create byte array to copy pixel values
            var step = Depth/8;
            Pixels = new byte[pixelCount*step];
            _ptr = _bitmapData.Scan0;

            // Copy data from pointer to array
            Marshal.Copy(_ptr, Pixels, 0, Pixels.Length);
        }
        public void Calculate(Bitmap srcimg, int tnum)
        {
            if (srcimg.PixelFormat != PixelFormat.Format24bppRgb)
            {
                using (Bitmap tmp = new Bitmap(srcimg.Width, srcimg.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb))
                using (Graphics gr = Graphics.FromImage(tmp))
                {
                    gr.DrawImage(srcimg, new Rectangle(0, 0, srcimg.Width, srcimg.Height));
                    srcimg = new Bitmap(tmp);
                }
            }
            Height = srcimg.Height;
            Width = srcimg.Width;
            PixelsCount = Height * Width;
            this.tnum = tnum;

            srcData = srcimg.LockBits(
                new Rectangle(0, 0, srcimg.Width, srcimg.Height),
                ImageLockMode.ReadOnly, srcimg.PixelFormat);

            Thread[] thread_array = new Thread[tnum];
            for (int i = 0; i < tnum; i++)
            {
                thread_array[i] = new Thread(new ParameterizedThreadStart(Run));
                thread_array[i].Start(i);
            }
            for (int i = 0; i < tnum; i++)
                thread_array[i].Join();

            srcimg.UnlockBits(srcData);
        }
Esempio n. 28
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ImageBuffer"/> class.
        /// </summary>
        public ImageBuffer(Bitmap bitmap, ImageLockMode lockMode)
        {
            // locks the image data
            this.bitmap = bitmap;
            this.lockMode = lockMode;

            // gathers the informations
            Width = bitmap.Width;
            Height = bitmap.Height;
            PixelFormat = bitmap.PixelFormat;
            IsIndexed = PixelFormat.IsIndexed();
            BitDepth = PixelFormat.GetBitDepth();
            BytesPerPixel = Math.Max(1, BitDepth >> 3);

            // determines the bounds of an image, and locks the data in a specified mode
            Rectangle bounds = Rectangle.FromLTRB(0, 0, Width, Height);

            // locks the bitmap data
            lock (bitmap) bitmapData = bitmap.LockBits(bounds, lockMode, PixelFormat);

            // creates internal buffer
            Stride = bitmapData.Stride < 0 ? -bitmapData.Stride : bitmapData.Stride;
            Size = Stride*Height;

            // precalculates the offsets
            Precalculate();
        }
Esempio n. 29
0
        public void LockBits()
        {
            try
            {
                Width = source.Width;
                Height = source.Height;

                int PixelCount = Width * Height;

                Rectangle rect = new Rectangle(0, 0, Width, Height);

                Depth = System.Drawing.Bitmap.GetPixelFormatSize(source.PixelFormat);

                if (Depth != 8 && Depth != 24 && Depth != 32)
                {
                    throw new ArgumentException("Only 8, 24 and 32 bpp images are supported.");
                }

                bitmapData = source.LockBits(rect, ImageLockMode.ReadWrite,
                                             source.PixelFormat);

                int step = Depth / 8;
                Pixels = new byte[PixelCount * step];
                Iptr = bitmapData.Scan0;

                Marshal.Copy(Iptr, Pixels, 0, Pixels.Length);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Esempio n. 30
0
 public static void DrawImageAll(BitmapData data_bac)
 {
     for(int i=0;i<ON_SCREEN.Count;i++)
     {
         ON_SCREEN[i].DrawImage(data_bac);
     }
 }
Esempio n. 31
0
        /***
         * /// <summary>
         * ///  抠出的数字图像灰度化
         * /// </summary>
         * /// <param name="sender"></param>
         * /// <param name="e"></param>
         * private void btnImageGray_Click(object sender, EventArgs e)
         * {
         *  // 获取图片
         *  Bitmap bmp = (Bitmap)Image.FromFile(testPath);
         *  // 处理图片
         *  this.progressBar1.Maximum = bmp.Width * bmp.Height;
         *
         *  for (int i = 0; i < bmp.Width; i++)
         *  {
         *      for (int j = 0; j < bmp.Height; j++)
         *      {
         *          //获取该点的像素的RGB的颜色
         *          Color color = bmp.GetPixel(i, j);
         *          //利用公式计算灰度值
         *          int gray = (int)(color.R * 0.3 + color.G * 0.59 + color.B * 0.11);
         *          Color newColor = Color.FromArgb(gray, gray, gray);
         *          bmp.SetPixel(i, j, newColor);
         *          this.progressBar1.Value++;
         *      }
         *  }
         *  this.picGray.Image = bmp;
         *
         * }
         ****/
        #endregion

        /// <summary>
        /// 图像二值化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnBitValue_Click(object sender, EventArgs e)
        {
            // 文件路径
            Bitmap curBitmap = (Bitmap)Image.FromFile(Environment.CurrentDirectory + "//images//gray.jpg");

            if (curBitmap != null)
            {
                Rectangle rect = new Rectangle(0, 0, curBitmap.Width, curBitmap.Height);
                System.Drawing.Imaging.BitmapData bmpData = curBitmap.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, curBitmap.PixelFormat);
                IntPtr ptr        = bmpData.Scan0;
                int    bytes      = curBitmap.Width * curBitmap.Height * 3;
                byte[] grayValues = new byte[bytes];

                System.Runtime.InteropServices.Marshal.Copy(ptr, grayValues, 0, bytes);

                byte   T          = 0;
                byte[] neighb     = new byte[bytes];
                byte   temp       = 0;
                byte   maxGray    = 0;
                byte   minGray    = 255;
                int[]  countPixel = new int[256];

                // 进度条显示
                this.progressBar1.Minimum = 0;
                this.progressBar1.Maximum = grayValues.Length + bytes;
                this.progressBar1.Value   = 0;

                for (int i = 0; i < grayValues.Length; i++)
                {
                    temp = grayValues[i];
                    countPixel[temp]++;
                    if (temp > maxGray)
                    {
                        maxGray = temp;
                    }
                    if (temp < minGray)
                    {
                        minGray = temp;
                    }
                    this.progressBar1.Value++;
                }
                double mu1, mu2;
                int    numerator;
                double sigma;
                double tempMax = 0;

                // 大津法二值化图像
                double w1 = 0, w2 = 0;
                double sum = 0;
                numerator = 0;
                for (int i = minGray; i <= maxGray; i++)
                {
                    sum += i * countPixel[i];
                }
                for (int i = minGray; i < maxGray; i++)
                {
                    w1        += countPixel[i];
                    numerator += i * countPixel[i];
                    mu1        = numerator / w1;
                    w2         = grayValues.Length - w1;
                    mu2        = (sum - numerator) / w2;
                    sigma      = w1 * w2 * (mu1 - mu2) * (mu1 - mu2);

                    if (sigma > tempMax)
                    {
                        tempMax = sigma;
                        T       = Convert.ToByte(i);
                    }
                }

                for (int i = 0; i < bytes; i++)
                {
                    if (grayValues[i] < T)
                    {
                        grayValues[i] = 0;
                    }
                    else
                    {
                        grayValues[i] = 255;
                    }
                    this.progressBar1.Value++;
                }

                System.Runtime.InteropServices.Marshal.Copy(grayValues, 0, ptr, bytes);
                curBitmap.UnlockBits(bmpData);


                curBitmap.Save(Environment.CurrentDirectory + "//images//bValue.jpg");

                this.picBitValue.Image = curBitmap;

                // 修改界面
                btnCut.Enabled     = true;
                pictureBox23.Image = Image.FromFile(@"skin/004.png");
                pictureBox27.Image = Image.FromFile(@"skin/004.png");
            }// end of if
        }
Esempio n. 32
0
        private void ReadPixel()
        {
            String pathOfBitmapMap = String.Format(@"{0}\{1}", Application.StartupPath, @"Gfx\provinces.bmp");

            if (File.Exists(pathOfBitmapMap))
            {
                int idProvince = GetMaxIdProvince();

                //------------------------------------------------------------------

                StringBuilder colorKey = new StringBuilder();

                Dictionary <String, ProvinceDefinitionItem> dictCache = new Dictionary <string, ProvinceDefinitionItem> ();

                foreach (ProvinceDefinitionItem provinceDefinitionItemCache in m_listProvinceDefinition)
                {
                    colorKey.Clear();

                    colorKey.Append(provinceDefinitionItemCache.R);
                    colorKey.Append(provinceDefinitionItemCache.G);
                    colorKey.Append(provinceDefinitionItemCache.B);

                    dictCache.Add(colorKey.ToString(), provinceDefinitionItemCache);
                }

                //------------------------------------------------------------------

                String colorKeyString = "";

                Color pixelColor;

                m_bitmapMap = new Bitmap(Bitmap.FromFile(pathOfBitmapMap));

                m_mapProvinceDefinitionItem = new ProvinceDefinitionItem[m_bitmapMap.Width, m_bitmapMap.Height];

                Rectangle rectangle = new Rectangle(0, 0, m_bitmapMap.Width, m_bitmapMap.Height);

                System.Drawing.Imaging.BitmapData bitmapData = m_bitmapMap.LockBits(rectangle, System.Drawing.Imaging.ImageLockMode.ReadOnly, m_bitmapMap.PixelFormat);

                int length = bitmapData.Stride * m_bitmapMap.Height;

                byte[] rawBytes = new byte[length];

                System.Runtime.InteropServices.Marshal.Copy(bitmapData.Scan0, rawBytes, 0, length);

                m_bitmapMap.UnlockBits(bitmapData);

                ProvinceDefinitionItem provinceDefinitionItem = new ProvinceDefinitionItem();

                for (int nXndex = 0; nXndex < m_bitmapMap.Width; nXndex++)
                {
                    for (int nYndex = 0; nYndex < m_bitmapMap.Height; nYndex++)
                    {
                        pixelColor = Color.FromArgb(rawBytes[nYndex * bitmapData.Stride + nXndex * 4 + 3], rawBytes[nYndex * bitmapData.Stride + nXndex * 4 + 2], rawBytes[nYndex * bitmapData.Stride + nXndex * 4 + 1], rawBytes[nYndex * bitmapData.Stride + nXndex * 4]);

                        if (!((provinceDefinitionItem.R == pixelColor.R) && (provinceDefinitionItem.G == pixelColor.G) && (provinceDefinitionItem.B == pixelColor.B)))
                        {
                            colorKey.Clear();

                            colorKey.Append(pixelColor.R);
                            colorKey.Append(pixelColor.G);
                            colorKey.Append(pixelColor.B);

                            colorKeyString = colorKey.ToString();

                            if (dictCache.ContainsKey(colorKeyString))
                            {
                                provinceDefinitionItem = dictCache[colorKeyString];
                            }
                            else
                            {
                                String name = String.Format("NewProvince_{0}", idProvince);

                                provinceDefinitionItem = new ProvinceDefinitionItem(++idProvince, pixelColor.R, pixelColor.G, pixelColor.B, name, "");
                            }
                        }

                        provinceDefinitionItem.ListPixel.Add(new Pixel(nXndex, nYndex));

                        m_mapProvinceDefinitionItem[nXndex, nYndex] = provinceDefinitionItem;
                    }
                }

                m_bitmapMapOverlay = new Bitmap(m_bitmapMap);
            }
        }
Esempio n. 33
0
        private void btCaptureBmp_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();

            saveFileDialog1.FileName         = "fingertemplate.bmp";
            saveFileDialog1.RestoreDirectory = true;

            DialogResult result = saveFileDialog1.ShowDialog();

            if (result == DialogResult.OK)
            {
                string fileName = saveFileDialog1.FileName.ToString();
                if (fileName != "" && fileName != null && picFPImg.Image != null)
                {
                    //http://www.wischik.com/lu/programmer/1bpp.html
                    Bitmap bmp = new Bitmap(picFPImg.Image.Width, picFPImg.Image.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);

                    using (Graphics g = Graphics.FromImage(bmp))
                    {
                        g.DrawImage(picFPImg.Image, 0, 0, bmp.Width, bmp.Height);
                    }
                    Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
                    System.Drawing.Imaging.BitmapData bmpData = bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, bmp.PixelFormat);
                    IntPtr ptr       = bmpData.Scan0;
                    int    bytes     = bmpData.Stride * bmpData.Height;
                    byte[] rgbValues = new byte[bytes];
                    System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);
                    Rectangle rect2 = new Rectangle(0, 0, bmp.Width, bmp.Height);

                    Bitmap bit = new Bitmap(bmp.Width, bmp.Height, System.Drawing.Imaging.PixelFormat.Format8bppIndexed);
                    System.Drawing.Imaging.BitmapData bmpData2 = bit.LockBits(rect2, System.Drawing.Imaging.ImageLockMode.ReadWrite, bit.PixelFormat);
                    IntPtr ptr2       = bmpData2.Scan0;
                    int    bytes2     = bmpData2.Stride * bmpData2.Height;
                    byte[] rgbValues2 = new byte[bytes2];
                    System.Runtime.InteropServices.Marshal.Copy(ptr2, rgbValues2, 0, bytes2);
                    double colorTemp = 0;
                    for (int i = 0; i < bmpData.Height; i++)
                    {
                        for (int j = 0; j < bmpData.Width * 3; j += 3)
                        {
                            colorTemp = rgbValues[i * bmpData.Stride + j + 2] * 0.299 + rgbValues[i * bmpData.Stride + j + 1] * 0.578 + rgbValues[i * bmpData.Stride + j] * 0.114;
                            rgbValues2[i * bmpData2.Stride + j / 3] = (byte)colorTemp;
                        }
                    }
                    System.Runtime.InteropServices.Marshal.Copy(rgbValues2, 0, ptr2, bytes2);
                    bmp.UnlockBits(bmpData);
                    ColorPalette tempPalette;
                    {
                        using (Bitmap tempBmp = new Bitmap(1, 1, System.Drawing.Imaging.PixelFormat.Format8bppIndexed))
                        {
                            tempPalette = tempBmp.Palette;
                        }
                        for (int i = 0; i < 256; i++)
                        {
                            tempPalette.Entries[i] = Color.FromArgb(i, i, i);
                        }
                        bit.Palette = tempPalette;
                    }
                    bit.UnlockBits(bmpData2);

                    bit.Save(fileName, picFPImg.Image.RawFormat);

                    bit.Dispose();
                }
            }
        }
Esempio n. 34
0
        public static Bitmap equalizing(Bitmap img)
        {
            Bitmap    bmp  = (Bitmap)img.Clone();
            Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);

            System.Drawing.Imaging.BitmapData bmpData = bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, bmp.PixelFormat);
            IntPtr ptr   = bmpData.Scan0;
            int    bytes = bmpData.Stride * bmp.Height;

            byte[] grayValues = new byte[bytes];
            int[]  R          = new int[256];
            byte[] N          = new byte[256];
            byte[] left       = new byte[256];
            byte[] right      = new byte[256];
            System.Runtime.InteropServices.Marshal.Copy(ptr, grayValues, 0, bytes);
            for (int i = 0; i < grayValues.Length; i++)
            {
                ++R[grayValues[i]];
            }
            int z    = 0;
            int Hint = 0;
            int Havg = grayValues.Length / R.Length;

            for (int i = 0; i < N.Length - 1; i++)
            {
                N[i] = 0;
            }
            for (int j = 0; j < R.Length; j++)
            {
                if (z > 255)
                {
                    left[j] = 255;
                }
                else
                {
                    left[j] = (byte)z;
                }
                Hint += R[j];
                while (Hint > Havg)
                {
                    Hint -= Havg;
                    z++;
                }
                if (z > 255)
                {
                    right[j] = 255;
                }
                else
                {
                    right[j] = (byte)z;
                }

                N[j] = (byte)((left[j] + right[j]) / 2);
            }
            for (int i = 0; i < grayValues.Length; i++)
            {
                if (left[grayValues[i]] == right[grayValues[i]])
                {
                    grayValues[i] = left[grayValues[i]];
                }
                else
                {
                    grayValues[i] = N[grayValues[i]];
                }
            }

            System.Runtime.InteropServices.Marshal.Copy(grayValues, 0, ptr, bytes);
            bmp.UnlockBits(bmpData);
            return(bmp);
        }
Esempio n. 35
0
        private void btnABC_Click(object sender, RoutedEventArgs e)
        {
            abcFile abc;

            string abcname = "";

            Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog();
            ofd.RestoreDirectory = true;
            ofd.Title            = "Open ABC File";
            ofd.Filter           = "FontMaker ABC File (*.abc)|*.abc";
            if ((bool)ofd.ShowDialog())
            {
                FileStream      fs = new FileStream(ofd.FileName, FileMode.Open);
                BigEndianReader br = new BigEndianReader(fs);

                br.BaseStream.Position = 0;

                abc = new abcFile();

                abc.Read(br);

                br.Close();
                fs.Close();

                abcname = ofd.SafeFileName;
            }
            else
            {
                return;
            }

            if (abc.Height < 0 || abc.Height > 64)
            {
                WriteLog("ABC import failed: Height " + abc.Height + " out of range (0-64).");
                return;
            }
            if (abc.TopPadding < 0 || abc.TopPadding > 64)
            {
                WriteLog("ABC import failed: Top padding " + abc.TopPadding + " out of range (0-64).");
                return;
            }
            if (abc.BottomPadding < 0 || abc.BottomPadding > 64)
            {
                WriteLog("ABC import failed: Bottom padding " + abc.BottomPadding + " out of range (0-64).");
                return;
            }
            if (abc.YAdvance < 0 || abc.YAdvance > 64)
            {
                WriteLog("ABC import failed: Indent " + abc.YAdvance + " out of range (0-64).");
                return;
            }

            ofd = new Microsoft.Win32.OpenFileDialog();
            ofd.RestoreDirectory = true;
            ofd.Title            = "Open Font Sheet";
            ofd.Filter           = "Converted FontMaker Image (*.png)|*.png";
            if ((bool)ofd.ShowDialog())
            {
                System.Drawing.Image sheet = System.Drawing.Image.FromFile(ofd.FileName);

                for (int i = 0; i < abc.GlyphCount; i++)
                {
                    System.Drawing.Rectangle rect = new System.Drawing.Rectangle(abc.GlyphTable[i].Left,
                                                                                 abc.GlyphTable[i].Top,
                                                                                 (abc.GlyphTable[i].Right - abc.GlyphTable[i].Left),
                                                                                 (abc.GlyphTable[i].Bottom - abc.GlyphTable[i].Top));

                    if (rect.Left + rect.Width > sheet.Width)
                    {
                        rect.Width = sheet.Width - rect.Left;
                    }

                    if (rect.Top + rect.Height > sheet.Height)
                    {
                        rect.Height = sheet.Height - rect.Top;
                    }

                    //today i learned about empty characters
                    if (rect.Width == 0)
                    {
                        rect.Width = 1;
                    }
                    if (rect.Height == 0)
                    {
                        rect.Height = 1;
                    }

                    Bitmap bm = new Bitmap(sheet);
                    System.Drawing.Imaging.BitmapData bd = bm.LockBits(rect,
                                                                       System.Drawing.Imaging.ImageLockMode.WriteOnly,
                                                                       bm.PixelFormat);

                    var sauce = BitmapSource.Create(bd.Width, bd.Height, 96, 96, System.Windows.Media.PixelFormats.Bgra32, null, bd.Scan0, bd.Stride * bd.Height, bd.Stride);

                    MemoryStream ms      = new MemoryStream();
                    var          encoder = new System.Windows.Media.Imaging.PngBitmapEncoder();
                    encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(sauce));
                    encoder.Save(ms);
                    ms.Flush();

                    var dispwidth = abc.GlyphTable[i].Width;

                    if (abc.CharCodes[i] == 0x20)
                    {
                        var periodindex = package.Fonts[fontslist.SelectedIndex].FindCharacter(0x2C);

                        if (periodindex != -1)
                        {
                            dispwidth = package.Fonts[fontslist.SelectedIndex].Characters[periodindex].Data.dispWidth;
                        }
                        else
                        {
                            dispwidth = 4;
                        }
                    }


                    package.AddCustomCharacter(abc.CharCodes[i], fontslist.SelectedIndex, System.Drawing.Image.FromStream(ms), CharTint.None, true, dispwidth);

                    ms.Close();
                    bm.Dispose();
                }

                //for (int i = 0; i < package.Fonts[fontslist.SelectedIndex].Characters.Count; i++)
                //{
                //	package.Fonts[fontslist.SelectedIndex].Characters[i].Data.dispHeight = (ushort)abc.YAdvance;
                //}
                //
                //UpdateFontInfo((short)abc.Height, (short)abc.TopPadding, (short)abc.BottomPadding, 0);
                UpdateFontDisplay();

                WriteLog("Characters successfully imported from abc file \"" + abcname + "\".");
            }
        }
        public void TestGDITextToTexture2D()
        {
            var bmp = new Bitmap(100, 100, PixelFormat.Format32bppArgb);



            var canvasSize     = new Point(bmp.Width, bmp.Height);
            var c              = Color.Red;
            var textCoordinate = new Point(0, 0);



            //Then create a graphics object to be able to write in the bmp image
            var g = System.Drawing.Graphics.FromImage(bmp);

            //g.MeasureString(text, font, canvasSize, sf);
            g.PageUnit = GraphicsUnit.Pixel;
            g.Clear(Color.Transparent);
            g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;

            //then create a brush (with a color) and write the text in the bmp file specifying text coordinates and alignment
            Brush brush = new SolidBrush(c);

            g.DrawString("Hello Wizard", new Font("Verdana", 10), brush, textCoordinate.X, textCoordinate.Y, StringFormat.GenericDefault);

            g.Flush();



            // Lock the bitmap's bits.
            Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);

            System.Drawing.Imaging.BitmapData bmpData =
                bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite,
                             bmp.PixelFormat);

            // Get the address of the first line.
            IntPtr ptr = bmpData.Scan0;

            // Declare an array to hold the bytes of the bitmap.
            int bytes = Math.Abs(bmpData.Stride) * bmp.Height;

            byte[] rgbValues = new byte[bytes];

            // Copy the RGB values into the array.
            System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);

            // Unlock the bits.
            bmp.UnlockBits(bmpData);


            var game = new DX11Game();

            game.InitDirectX();

            var tex = new Texture2D(game.Device, new Texture2DDescription
            {
                ArraySize         = 1,
                MipLevels         = 1,
                Format            = Format.B8G8R8A8_UNorm,
                Usage             = ResourceUsage.Dynamic,
                CpuAccessFlags    = CpuAccessFlags.Write,
                Width             = bmp.Width,
                Height            = bmp.Height,
                SampleDescription = new SampleDescription(1, 0),
                BindFlags         = BindFlags.ShaderResource
            });

            var box = game.Device.ImmediateContext.MapSubresource(tex, 0, 0, MapMode.WriteDiscard,
                                                                  SlimDX.Direct3D11.MapFlags.None);

            for (int iRow = 0; iRow < bmp.Height; iRow++)
            {
                box.Data.Seek(iRow * box.RowPitch, SeekOrigin.Begin);
                box.Data.Write(rgbValues, iRow * 4 * bmp.Width, bmp.Width * 4);
            }

            game.Device.ImmediateContext.UnmapSubresource(tex, 0);

            var view = new ShaderResourceView(game.Device, tex);

            game.GameLoopEvent += delegate
            {
                game.TextureRenderer.Draw(view, Vector2.Zero, new Vector2(bmp.Width, bmp.Height));
            };
            game.Run();
        }
Esempio n. 37
0
        public int CompareGrpah(string CmpGraphFile, ref string SysMsg, ref List <string> lCmpInfo)
        {
            int        ret        = SystemInfo.ERROR_RESULT_OK;
            string     AddrTmp    = null;
            SL_IO_Util FileVerfiy = new SL_IO_Util();

            if (!FileVerfiy.isFileExist(ImgPath))
            {
                return(SystemInfo.ERROR_CMP_FILENOTEXIST);
            }
            if (!FileVerfiy.isFileExist(CmpGraphFile))
            {
                return(SystemInfo.ERROR_CMP_FILENOTEXIST);
            }
            Bitmap    DefaultBmp  = new Bitmap(ImgPath);
            Bitmap    CmpBmp      = new Bitmap(CmpGraphFile);
            Rectangle DefaultRect = new Rectangle(0, 0, DefaultBmp.Width, DefaultBmp.Height);
            Rectangle CmpRect     = new Rectangle(0, 0, CmpBmp.Width, CmpBmp.Height);

            System.Drawing.Imaging.BitmapData DefaultBmpData =
                DefaultBmp.LockBits(DefaultRect, System.Drawing.Imaging.ImageLockMode.ReadWrite, DefaultBmp.PixelFormat);

            System.Drawing.Imaging.BitmapData CmpBmpData =
                CmpBmp.LockBits(CmpRect, System.Drawing.Imaging.ImageLockMode.ReadWrite, CmpBmp.PixelFormat);

            // Get the address of the first line.
            IntPtr DefualtPtr = DefaultBmpData.Scan0;
            IntPtr CmpPtr     = CmpBmpData.Scan0;

            // Declare an array to hold the bytes of the bitmap.
            int DefaultBytes = Math.Abs(DefaultBmpData.Stride) * DefaultBmp.Height;
            int CmpBytes     = Math.Abs(CmpBmpData.Stride) * CmpBmpData.Height;
            int ResultBytes  = Math.Abs(DefaultBmpData.Stride) * DefaultBmpData.Height;

            byte[] DrgbValues = new byte[DefaultBytes];
            byte[] CrgbValues = new byte[CmpBytes];
            byte[] RrgbValues = new byte[ResultBytes];

            // Copy the RGB values into the array.
            System.Runtime.InteropServices.Marshal.Copy(DefualtPtr, DrgbValues, 0, DefaultBytes);
            System.Runtime.InteropServices.Marshal.Copy(CmpPtr, CrgbValues, 0, CmpBytes);

            // Set every third value to 255. A 24bpp bitmap will look red.
            for (int Counter = 0; Counter < DrgbValues.Length; Counter += 3)
            {
                if (DrgbValues[Counter] == CrgbValues[Counter] && DrgbValues[Counter + 1] == CrgbValues[Counter + 1] &&
                    DrgbValues[Counter + 2] == CrgbValues[Counter + 2])
                {
                    RrgbValues[Counter] = RrgbValues[Counter + 1] = RrgbValues[Counter + 2] = 255;
                }
                else
                {
                    RrgbValues[Counter + 2] = 255;
                    RrgbValues[Counter + 1] = RrgbValues[Counter] = 0;
                    AddrTmp = CountLocation(DefaultBmp.Width, DefaultBmp.Height, Counter);
                    ShowCmpMsg(ref lCmpInfo, AddrTmp, DrgbValues[Counter + 2], DrgbValues[Counter + 1], DrgbValues[Counter],
                               CrgbValues[Counter + 2], CrgbValues[Counter + 1], CrgbValues[Counter]);
                    ret = SystemInfo.ERROR_CMP_ERROR;
                }
            }

            // Copy the RGB values back to the bitmap
            System.Runtime.InteropServices.Marshal.Copy(DrgbValues, 0, DefualtPtr, DefaultBytes);
            System.Runtime.InteropServices.Marshal.Copy(CrgbValues, 0, CmpPtr, CmpBytes);

            // Unlock the bits.
            DefaultBmp.UnlockBits(DefaultBmpData);
            CmpBmp.UnlockBits(CmpBmpData);

            ResultBmp = CreateBmp(RrgbValues, DefaultBmp.Width, DefaultBmp.Height);

            return(ret);
        }
Esempio n. 38
0
        private void Map_Robot_Image_Processing2(ref Bitmap bmSource, int Width, int Height, byte[] sourcemapvalue, string strfiltername)
        {
            try
            {
                //
                // 여기서 부터 Picture Box의 이미지를 복사해 오는 부분입니다
                //
                Rectangle rect = new Rectangle(0, 0, bmSource.Width, bmSource.Height);
                System.Drawing.Imaging.BitmapData bmpData =
                    bmSource.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite,
                                      bmSource.PixelFormat);

                IntPtr ptr = bmpData.Scan0;
                byte[] rgbValues;


                if (bmSource.PixelFormat == PixelFormat.Format32bppArgb || bmSource.PixelFormat == PixelFormat.Format32bppRgb)
                {
                    rgbValues = new byte[Width * Height * 4];
                }
                else
                {
                    rgbValues = new byte[Width * Height];
                }

                if (bmSource.PixelFormat == PixelFormat.Format32bppArgb || bmSource.PixelFormat == PixelFormat.Format32bppRgb)
                {
                    var k = 0;
                    for (var y = 0; y < Height; y++)
                    {
                        for (var x = 0; x < Width; x++)
                        {
                            byte btemp = sourcemapvalue[y * Width + x];

                            if (strfiltername == "gray" || strfiltername == "cost" || strfiltername == "globalcost")
                            {
                                //if (btemp == 0) btemp = 0xff;
                                //else if (btemp == 0xff) btemp = 0xf0;
                            }
                            else
                            {
                                if (btemp == 0)
                                {
                                    btemp = 0xff;
                                }
                            }


                            #region  gray filter 그레이는 r,g,b가 동일 값으로 들어감
                            if (strfiltername == "gray" || strfiltername == "cost" || strfiltername == "globalcost")
                            {
                                rgbValues[k]     = btemp;
                                rgbValues[k + 1] = btemp;
                                rgbValues[k + 2] = btemp;
                            }


                            #endregion

                            k += 4;
                        }
                    }
                }

                else
                {
                    for (int i = 0; i < Width * Height; i++)
                    {
                        rgbValues[i] = sourcemapvalue[i];
                    }
                }

                //
                // 여기까지가 Marshal Copy로 rgbValues 버퍼로 영상을 Copy해 오는 부분입니다.
                //

                //
                // 여기서부터 2차원 배열로 1차원 영상을 옮기는 부분입니다
                //
                double[,] Source = new double[Width, Height];
                double[,] Target = new double[Width, Height];

                int XPos, YPos = 0;
                if (bmSource.PixelFormat == PixelFormat.Format32bppArgb || bmSource.PixelFormat == PixelFormat.Format32bppRgb)
                {
                    for (int nH = 0; nH < Height; nH++)
                    {
                        XPos = 0;

                        if (strfiltername == "gray")
                        {
                            XPos = 0; //gray xpos
                        }
                        for (int nW = 0; nW < Width; nW++)
                        {
                            Source[nW, nH] = rgbValues[XPos + YPos];
                            Target[nW, nH] = rgbValues[XPos + YPos];
                            XPos          += 4;
                        }
                        YPos += Width * 4;
                    }
                }
                else
                {
                    for (int nH = 0; nH < Height; nH++)
                    {
                        XPos = 0;
                        for (int nW = 0; nW < Width; nW++)
                        {
                            Source[nW, nH] = rgbValues[XPos + YPos];
                            Target[nW, nH] = rgbValues[XPos + YPos];
                            XPos++;
                        }
                        YPos += Width;
                    }
                }

                //
                // 여기까지는 2차원 배열로 영상을 복사하는 부분입니다.
                //

                //좌우반전//
                int nconvert = 0;

                //상하반전
                nconvert = 0;
                double[,] bconvertTarget = new double[Width, Height];
                for (int nh = 0; nh < Height; nh++)
                {
                    nconvert = 0;
                    for (int nw = 0; nw < Width; nw++)
                    {
                        bconvertTarget[nw, Height - nh - 1] = Target[nw, nh];
                        //nconvert++;
                    }
                }



                //
                // 여기서 부터는 2차원 배열을 다시 1차원 버터로 옮기는 부분입니다
                //

                if (bmSource.PixelFormat == PixelFormat.Format32bppArgb || bmSource.PixelFormat == PixelFormat.Format32bppRgb)
                {
                    rgbValues = new byte[Width * Height * 4];
                }
                else
                {
                    rgbValues = new byte[Width * Height];
                }

                YPos = 0;
                if (bmSource.PixelFormat == PixelFormat.Format32bppArgb || bmSource.PixelFormat == PixelFormat.Format32bppRgb)
                {
                    for (int nH = 0; nH < Height; nH++)
                    {
                        XPos = 0;
                        for (int nW = 0; nW < Width; nW++)
                        {
                            #region  gray filter 그레이는 r,g,b가 동일 값으로 들어감
                            if (strfiltername == "gray")
                            {
                                bconvertTarget[nW, nH]     = (byte)(255 - (255 * bconvertTarget[nW, nH]) / 100);
                                rgbValues[XPos + YPos]     = (byte)bconvertTarget[nW, nH];
                                rgbValues[XPos + YPos + 1] = (byte)bconvertTarget[nW, nH];
                                rgbValues[XPos + YPos + 2] = (byte)bconvertTarget[nW, nH];
                            }

                            #endregion

                            if (strfiltername == "globalcost")
                            {
                                bconvertTarget[nW, nH]     = (byte)(255 - (255 * bconvertTarget[nW, nH]) / 100);
                                rgbValues[XPos + YPos]     = (byte)bconvertTarget[nW, nH];
                                rgbValues[XPos + YPos + 1] = (byte)bconvertTarget[nW, nH];
                                rgbValues[XPos + YPos + 2] = (byte)bconvertTarget[nW, nH];
                            }

                            #region  cost map filter
                            if (strfiltername == "cost")
                            {
                                //cost map 색상 테스트
                                if (bconvertTarget[nW, nH] < 36)
                                {
                                    rgbValues[XPos + YPos]     = 0xff;
                                    rgbValues[XPos + YPos + 1] = 0xff;
                                    rgbValues[XPos + YPos + 2] = 0xff;
                                    rgbValues[XPos + YPos + 3] = 255;
                                }

                                else if (bconvertTarget[nW, nH] == 100) // lethal obstacle values (100) in purple
                                {
                                    rgbValues[XPos + YPos]     = 255;
                                    rgbValues[XPos + YPos + 1] = 0;
                                    rgbValues[XPos + YPos + 2] = 255;
                                    rgbValues[XPos + YPos + 3] = 255;
                                }
                                else if (bconvertTarget[nW, nH] > 101 && bconvertTarget[nW, nH] < 128) // illegal positive values in green
                                {
                                    rgbValues[XPos + YPos]     = 0;
                                    rgbValues[XPos + YPos + 1] = 255;
                                    rgbValues[XPos + YPos + 2] = 0;
                                    rgbValues[XPos + YPos + 3] = 255;
                                }

                                else if (bconvertTarget[nW, nH] > 155 && bconvertTarget[nW, nH] < 255) // illegal negative (char) values in shades of red/yellow
                                {
                                    rgbValues[XPos + YPos]     = 255;
                                    rgbValues[XPos + YPos + 1] = (byte)((255 * (bconvertTarget[nW, nH] - 128)) / (254 - 128));
                                    rgbValues[XPos + YPos + 2] = 0;
                                    rgbValues[XPos + YPos + 3] = 255;
                                }
                                else
                                {
                                    rgbValues[XPos + YPos]     = 255;
                                    rgbValues[XPos + YPos + 1] = 255;
                                    rgbValues[XPos + YPos + 2] = (byte)bconvertTarget[nW, nH];
                                    rgbValues[XPos + YPos + 3] = 255;
                                }
                            }
                            #endregion

                            XPos += 4;
                        }
                        YPos += Width * 4;
                    }
                }
                else
                {
                    for (int nH = 0; nH < Height; nH++)
                    {
                        XPos = 0;
                        for (int nW = 0; nW < Width; nW++)
                        {
                            rgbValues[XPos + YPos] = (byte)bconvertTarget[nW, nH];

                            XPos++;
                        }
                        YPos += Width;
                    }
                }


                //
                // 다시 Marshal Copy로 Picture Box로 옮기는 부분입니다
                //
                if (bmSource.PixelFormat == PixelFormat.Format32bppArgb || bmSource.PixelFormat == PixelFormat.Format32bppRgb)
                {
                    System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, Width * Height * 4);
                }
                else
                {
                    System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, Width * Height);
                }

                bmSource.UnlockBits(bmpData);

                //System.Drawing.Rectangle cropArea = new System.Drawing.Rectangle(6, 6, Width - 12, Height - 12);
                System.Drawing.Rectangle cropArea = new System.Drawing.Rectangle(0, 0, Width, Height);
                Bitmap bmpTemp = bmSource.Clone(cropArea, bmSource.PixelFormat);
                bmSource.Dispose();
                bmSource = null;
                bmSource = (Bitmap)(bmpTemp.Clone());
            }
            catch (Exception ex)
            {
                Console.Out.WriteLine("Map_Robot_Image_Processing2 err :={0}", ex.Message.ToString());
            }
        }
        /// <summary>
        /// Convert raw data to bitmap
        /// </summary>
        /// <param name="scan0">The pointer to the raw data</param>
        /// <param name="step">The step</param>
        /// <param name="size">The size of the image</param>
        /// <param name="srcColorType">The source image color type</param>
        /// <param name="numberOfChannels">The number of channels</param>
        /// <param name="srcDepthType">The source image depth type</param>
        /// <param name="tryDataSharing">Try to create Bitmap that shares the data with the image</param>
        /// <returns>The Bitmap</returns>
        public static Bitmap RawDataToBitmap(IntPtr scan0, int step, Size size, Type srcColorType, int numberOfChannels, Type srcDepthType, bool tryDataSharing = false)
        {
            if (tryDataSharing)
            {
                if (srcColorType == typeof(Gray) && srcDepthType == typeof(Byte))
                {   //Grayscale of Bytes
                    Bitmap bmpGray = new Bitmap(
                        size.Width,
                        size.Height,
                        step,
                        System.Drawing.Imaging.PixelFormat.Format8bppIndexed,
                        scan0
                        );

                    bmpGray.Palette = GrayscalePalette;

                    return(bmpGray);
                }
                // Mono in Linux doesn't support scan0 constructure with Format24bppRgb, use ToBitmap instead
                // See https://bugzilla.novell.com/show_bug.cgi?id=363431
                // TODO: check mono buzilla Bug 363431 to see when it will be fixed
                else if (
                    Emgu.Util.Platform.OperationSystem == Emgu.Util.TypeEnum.OS.Windows &&
                    Emgu.Util.Platform.ClrType == Emgu.Util.TypeEnum.ClrType.DotNet &&
                    srcColorType == typeof(Bgr) && srcDepthType == typeof(Byte) &&
                    (step & 3) == 0)
                {   //Bgr byte
                    return(new Bitmap(
                               size.Width,
                               size.Height,
                               step,
                               System.Drawing.Imaging.PixelFormat.Format24bppRgb,
                               scan0));
                }
                else if (srcColorType == typeof(Bgra) && srcDepthType == typeof(Byte))
                {   //Bgra byte
                    return(new Bitmap(
                               size.Width,
                               size.Height,
                               step,
                               System.Drawing.Imaging.PixelFormat.Format32bppArgb,
                               scan0));
                }

                //PixelFormat.Format16bppGrayScale is not supported in .NET
                //else if (typeof(TColor) == typeof(Gray) && typeof(TDepth) == typeof(UInt16))
                //{
                //   return new Bitmap(
                //      size.width,
                //      size.height,
                //      step,
                //      PixelFormat.Format16bppGrayScale;
                //      scan0);
                //}
            }

            System.Drawing.Imaging.PixelFormat format; //= System.Drawing.Imaging.PixelFormat.Undefined;

            if (srcColorType == typeof(Gray))          // if this is a gray scale image
            {
                format = System.Drawing.Imaging.PixelFormat.Format8bppIndexed;
            }
            else if (srcColorType == typeof(Bgra)) //if this is Bgra image
            {
                format = System.Drawing.Imaging.PixelFormat.Format32bppArgb;
            }
            else if (srcColorType == typeof(Bgr))  //if this is a Bgr Byte image
            {
                format = System.Drawing.Imaging.PixelFormat.Format24bppRgb;
            }
            else
            {
                using (Mat m = new Mat(size.Height, size.Width, CvInvoke.GetDepthType(srcDepthType), numberOfChannels, scan0, step))
                    using (Mat m2 = new Mat())
                    {
                        CvInvoke.CvtColor(m, m2, srcColorType, typeof(Bgr));
                        return(RawDataToBitmap(m2.DataPointer, m2.Step, m2.Size, typeof(Bgr), 3, srcDepthType, false));
                    }
            }

            Bitmap bmp = new Bitmap(size.Width, size.Height, format);

            System.Drawing.Imaging.BitmapData data = bmp.LockBits(
                new Rectangle(Point.Empty, size),
                System.Drawing.Imaging.ImageLockMode.WriteOnly,
                format);
            using (Mat bmpMat = new Mat(size.Height, size.Width, CvEnum.DepthType.Cv8U, numberOfChannels, data.Scan0, data.Stride))
                using (Mat dataMat = new Mat(size.Height, size.Width, CvInvoke.GetDepthType(srcDepthType), numberOfChannels, scan0, step))
                {
                    if (srcDepthType == typeof(Byte))
                    {
                        dataMat.CopyTo(bmpMat);
                    }
                    else
                    {
                        double scale = 1.0, shift = 0.0;
                        RangeF range = dataMat.GetValueRange();
                        if (range.Max > 255.0 || range.Min < 0)
                        {
                            scale = range.Max.Equals(range.Min) ? 0.0 : 255.0 / (range.Max - range.Min);
                            shift = scale.Equals(0) ? range.Min : -range.Min * scale;
                        }
                        CvInvoke.ConvertScaleAbs(dataMat, bmpMat, scale, shift);
                    }
                }
            bmp.UnlockBits(data);

            if (format == System.Drawing.Imaging.PixelFormat.Format8bppIndexed)
            {
                bmp.Palette = GrayscalePalette;
            }
            return(bmp);
        }
Esempio n. 40
0
        private void thread_DoWork(CancellationToken token)
        {
            MFFactoryClass _factory = new MFFactoryClass();

            while (!token.IsCancellationRequested)
            {
                if (decode)
                {
                    MFFrame frame = null;

                    string path = String.Format(@"\\MLDiskStation\MLFiles\Trash\Roman\NetTestFiles\LG_jazz\LG_jazz\LG_jazz{0:d7}.jpg", index);

                    Debug.WriteLine("Picture:" + index.ToString());
                    index = ++index == 291 ? 0 : index; //291 is count of pictures in image sequences

                    {
                        Bitmap bmp = (Bitmap)System.Drawing.Image.FromFile(path);

                        Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
                        System.Drawing.Imaging.BitmapData bmpData = bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadOnly, PixelFormat.Format32bppPArgb);

                        M_AV_PROPS avProps = new M_AV_PROPS();
                        avProps.vidProps.eVideoFormat = eMVideoFormat.eMVF_HD1080_30p;
                        avProps.vidProps.fccType      = eMFCC.eMFCC_RGB32;
                        avProps.vidProps.nWidth       = bmp.Width;
                        avProps.vidProps.nHeight      = -1 * bmp.Height; // Negative height for top-bottom RGB images (if positive->bottom-top)
                        avProps.vidProps.nRowBytes    = bmpData.Stride;  // distance between lines

                        _factory.MFFrameCreateFromMem(ref avProps, bmpData.Scan0.ToInt64(), 0, 0, out frame, "");

                        bmp.UnlockBits(bmpData);

                        bmp.Dispose();
                    }

                    M_AV_PROPS props;
                    int        samples;
                    frame.MFAVPropsGet(out props, out samples);
                    props.vidProps.eVideoFormat = eMVideoFormat.eMVF_HD1080_30p;
                    props.vidProps.dblRate      = 30.0;
                    props.vidProps.nAspectX     = 16;
                    props.vidProps.nAspectY     = 9;

                    MFFrame frameConvert;
                    int     nRest = 0;
                    frame.MFConvert(ref props, out frameConvert, out nRest, "", "");

                    m_objPreview.ReceiverFramePut(frameConvert, 0, "");
                    m_objWriter.ReceiverFramePut(frameConvert, -1, "");
                    if (stopWr)
                    {
                        m_objWriter.WriterClose(0);
                    }

                    Marshal.ReleaseComObject(frameConvert);
                    Marshal.ReleaseComObject(frame);

                    GC.Collect();
                }
            }
        }
Esempio n. 41
0
        //边缘检测算法
        private static Bitmap smoothed(Bitmap a)
        {
            int w = a.Width;
            int h = a.Height;

            try
            {
                Bitmap dstBitmap = new Bitmap(w, h, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                System.Drawing.Imaging.BitmapData srcData = a.LockBits(new Rectangle
                                                                           (0, 0, w, h), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                BitmapData dstData = dstBitmap.LockBits(new Rectangle
                                                            (0, 0, w, h), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                unsafe
                {
                    byte *pIn  = (byte *)srcData.Scan0.ToPointer();
                    byte *pOut = (byte *)dstData.Scan0.ToPointer();
                    byte *p;
                    int   stride = srcData.Stride;
                    for (int y = 0; y < h; y++)
                    {
                        for (int x = 0; x < w; x++)
                        {
                            //边缘八个点像素不变
                            if (x == 0 || x == w - 1 || y == 0 || y == h - 1)
                            {
                                pOut[0] = pIn[0];
                                pOut[1] = pIn[1];
                                pOut[2] = pIn[2];
                            }
                            else
                            {
                                int    r0, r1, r2, r3, r4, r5, r6, r7, r8;
                                int    g1, g2, g3, g4, g5, g6, g7, g8, g0;
                                int    b1, b2, b3, b4, b5, b6, b7, b8, b0;
                                double vR, vG, vB;
                                //左上
                                p  = pIn - stride - 3;
                                r1 = p[2];
                                g1 = p[1];
                                b1 = p[0];
                                //正上
                                p  = pIn - stride;
                                r2 = p[2];
                                g2 = p[1];
                                b2 = p[0];
                                //右上
                                p  = pIn - stride + 3;
                                r3 = p[2];
                                g3 = p[1];
                                b3 = p[0];
                                //左
                                p  = pIn - 3;
                                r4 = p[2];
                                g4 = p[1];
                                b4 = p[0];
                                //右
                                p  = pIn + 3;
                                r5 = p[2];
                                g5 = p[1];
                                b5 = p[0];
                                //左下
                                p  = pIn + stride - 3;
                                r6 = p[2];
                                g6 = p[1];
                                b6 = p[0];
                                //正下
                                p  = pIn + stride;
                                r7 = p[2];
                                g7 = p[1];
                                b7 = p[0];
                                // 右下
                                p  = pIn + stride + 3;
                                r8 = p[2];
                                g8 = p[1];
                                b8 = p[0];
                                //中心点
                                p  = pIn;
                                r0 = p[2];
                                g0 = p[1];
                                b0 = p[0];
                                //使用模板
                                vR = (double)(Math.Abs(r3 + r5 + r8 - r1 - r4 - r6) + Math.Abs(r1 + r2 + r3 - r6 - r7 - r8));
                                vG = (double)(Math.Abs(g3 + g5 + g8 - g1 - g4 - g6) + Math.Abs(g1 + g2 + g3 - g6 - g7 - g8));
                                vB = (double)(Math.Abs(b3 + b5 + b8 - b1 - b4 - b6) + Math.Abs(b1 + b2 + b3 - b6 - b7 - b8));
                                if (vR > 0)
                                {
                                    vR = Math.Min(255, vR);
                                }
                                else
                                {
                                    vR = Math.Max(0, vR);
                                }

                                if (vG > 0)
                                {
                                    vG = Math.Min(255, vG);
                                }
                                else
                                {
                                    vG = Math.Max(0, vG);
                                }

                                if (vB > 0)
                                {
                                    vB = Math.Min(255, vB);
                                }
                                else
                                {
                                    vB = Math.Max(0, vB);
                                }
                                pOut[0] = (byte)vB;
                                pOut[1] = (byte)vG;
                                pOut[2] = (byte)vR;
                            }
                            pIn  += 3;
                            pOut += 3;
                        }
                        pIn  += srcData.Stride - w * 3;
                        pOut += srcData.Stride - w * 3;
                    }
                }
                a.UnlockBits(srcData);
                dstBitmap.UnlockBits(dstData);

                return(dstBitmap);
            }
            catch
            {
                return(null);
            }
        }
        public void TestCreateTexture2DFromBitmap()
        {
            Bitmap bitmap = createBitmap();

            var bmp = bitmap;

            // Lock the bitmap's bits.
            Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);

            System.Drawing.Imaging.BitmapData bmpData =
                bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite,
                             bmp.PixelFormat);

            // Get the address of the first line.
            IntPtr ptr = bmpData.Scan0;

            // Declare an array to hold the bytes of the bitmap.
            int bytes = Math.Abs(bmpData.Stride) * bmp.Height;

            byte[] rgbValues = new byte[bytes];

            // Copy the RGB values into the array.
            System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);

            // Unlock the bits.
            bmp.UnlockBits(bmpData);


            var game = new DX11Game();

            game.InitDirectX();

            var tex = new Texture2D(game.Device, new Texture2DDescription
            {
                ArraySize         = 1,
                MipLevels         = 1,
                Format            = Format.R8G8B8A8_UNorm,
                Usage             = ResourceUsage.Dynamic,
                CpuAccessFlags    = CpuAccessFlags.Write,
                Width             = bmp.Width,
                Height            = bmp.Height,
                SampleDescription = new SampleDescription(1, 0),
                BindFlags         = BindFlags.ShaderResource
            });

            var box = game.Device.ImmediateContext.MapSubresource(tex, 0, 0, MapMode.WriteDiscard,
                                                                  SlimDX.Direct3D11.MapFlags.None);

            for (int iRow = 0; iRow < bmp.Height; iRow++)
            {
                box.Data.Seek(iRow * box.RowPitch, SeekOrigin.Begin);
                box.Data.Write(rgbValues, iRow * 4 * bmp.Width, bmp.Width * 4);
            }

            game.Device.ImmediateContext.UnmapSubresource(tex, 0);

            var view = new ShaderResourceView(game.Device, tex);

            game.GameLoopEvent += delegate
            {
                game.TextureRenderer.Draw(view, Vector2.Zero, new Vector2(100, 100));
            };
            game.Run();
        }
        public void TrimSpace(Document doc, int i)
        {
            // Render the page to image with 72 DPI
            PngDevice device = new PngDevice(new Resolution(72));

            using (MemoryStream imageStr = new MemoryStream())
            {
                device.Process(doc.Pages[i], imageStr);
                Bitmap bmp = (Bitmap)Bitmap.FromStream(imageStr);

                System.Drawing.Imaging.BitmapData imageBitmapData = null;

                // Determine white areas
                try
                {
                    imageBitmapData = bmp.LockBits(new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height),
                                                   System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb);

                    Aspose.Pdf.Rectangle prevCropBox = doc.Pages[i].CropBox;

                    int toHeight = bmp.Height;
                    int toWidth  = bmp.Width;

                    int?leftNonWhite   = null;
                    int?rightNonWhite  = null;
                    int?topNonWhite    = null;
                    int?bottomNonWhite = null;

                    for (int y = 0; y < toHeight; y++)
                    {
                        byte[] imageRowBytes = new byte[imageBitmapData.Stride];

                        // Copy the row data to byte array
                        if (IntPtr.Size == 4)
                        {
                            System.Runtime.InteropServices.Marshal.Copy(new IntPtr(imageBitmapData.Scan0.ToInt32() + y * imageBitmapData.Stride), imageRowBytes, 0, imageBitmapData.Stride);
                        }
                        else
                        {
                            System.Runtime.InteropServices.Marshal.Copy(new IntPtr(imageBitmapData.Scan0.ToInt64() + y * imageBitmapData.Stride), imageRowBytes, 0, imageBitmapData.Stride);
                        }


                        int?leftNonWhite_row  = null;
                        int?rightNonWhite_row = null;

                        for (int x = 0; x < toWidth; x++)
                        {
                            if (imageRowBytes[x * 4] != 255 ||
                                imageRowBytes[x * 4 + 1] != 255 ||
                                imageRowBytes[x * 4 + 2] != 255)
                            {
                                if (leftNonWhite_row == null)
                                {
                                    leftNonWhite_row = x;
                                }

                                rightNonWhite_row = x;
                            }
                        }

                        if (leftNonWhite_row != null || rightNonWhite_row != null)
                        {
                            if (topNonWhite == null)
                            {
                                topNonWhite = y;
                            }

                            bottomNonWhite = y;
                        }

                        if (leftNonWhite_row != null &&
                            (leftNonWhite == null || leftNonWhite > leftNonWhite_row))
                        {
                            leftNonWhite = leftNonWhite_row;
                        }
                        if (rightNonWhite_row != null &&
                            (rightNonWhite == null || rightNonWhite < rightNonWhite_row))
                        {
                            rightNonWhite = rightNonWhite_row;
                        }
                    }

                    leftNonWhite   = leftNonWhite ?? 0;
                    rightNonWhite  = rightNonWhite ?? toWidth;
                    topNonWhite    = topNonWhite ?? 0;
                    bottomNonWhite = bottomNonWhite ?? toHeight;

                    // Set crop box with correction to previous crop box
                    doc.Pages[i].CropBox =
                        new Aspose.Pdf.Rectangle(
                            leftNonWhite.Value + prevCropBox.LLX,
                            (toHeight + prevCropBox.LLY) - bottomNonWhite.Value,
                            rightNonWhite.Value + doc.Pages[i].CropBox.LLX,
                            (toHeight + prevCropBox.LLY) - topNonWhite.Value
                            );
                }
                finally
                {
                    if (imageBitmapData != null)
                    {
                        bmp.UnlockBits(imageBitmapData);
                    }
                }
            }

            // Save the document
            doc.Save(@"D:\hoctap\webasp\CongVan\CongVan\Areas\Admin\Files\Tmp\spacePdf" + i + ".pdf");
        }
Esempio n. 44
0
    public static Rectangle AutoCropRect(System.Drawing.Bitmap bitmap, System.Drawing.Color color, int seuil)
    {
        try
        {
            unsafe
            {
                int  x, y, xMin, xMax, yMin, yMax, dR, dG, dB, cR, cG, cB, w, h, PixelSize, scanline, stride;
                bool broken;

                byte *p;

                // aide utile http://www.bobpowell.net/lockingbits.htm
                System.Drawing.Imaging.BitmapData bmd = bitmap.LockBits(
                    new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height),
                    System.Drawing.Imaging.ImageLockMode.ReadOnly,
                    bitmap.PixelFormat);

                if (bitmap.PixelFormat == System.Drawing.Imaging.PixelFormat.Format32bppArgb)
                {
                    PixelSize = 4;
                }
                else if (bitmap.PixelFormat == System.Drawing.Imaging.PixelFormat.Format24bppRgb)
                {
                    PixelSize = 3;
                }
                else
                {
                    bitmap.UnlockBits(bmd);
                    return(Rectangle.Empty);
                }

                w = bmd.Width;
                h = bmd.Height;

                yMin = h;
                yMax = 0;
                xMin = w;
                xMax = 0;

                cR = color.R;
                cG = color.G;
                cB = color.B;

                stride   = bmd.Stride;
                scanline = stride - bmd.Width * PixelSize;

                // detection bord haut
                broken = false;
                p      = (byte *)bmd.Scan0;
                for (y = 0; y < h; y++)
                {
                    for (x = 0; x < w; x++)
                    {
                        dR = p[2] - cR;
                        dG = p[1] - cG;
                        dB = p[0] - cB;
                        if (dR > seuil || dR < -seuil || dG > seuil || dG < -seuil || dB > seuil || dB < -seuil)
                        {
                            yMin   = y;
                            broken = true;
                            break;
                        }
                        p += PixelSize;
                    }
                    if (broken)
                    {
                        break;
                    }
                    p += scanline;
                }
                if (yMin == h)
                {
                    // gros pb de detection : exemple image unie ...
                    bitmap.UnlockBits(bmd);
                    return(Rectangle.Empty);
                }

                // detection bord bas
                broken = false;
                p      = (byte *)bmd.Scan0 + (h - 1) * stride;
                for (y = h - 1; y >= 0; y--)
                {
                    for (x = 0; x < w; x++)
                    {
                        dR = p[2] - cR;
                        dG = p[1] - cG;
                        dB = p[0] - cB;
                        if (dR > seuil || dR < -seuil || dG > seuil || dG < -seuil || dB > seuil || dB < -seuil)
                        {
                            yMax   = y;
                            broken = true;
                            break;
                        }
                        p += PixelSize;
                    }
                    if (broken)
                    {
                        break;
                    }
                    if (y <= yMin)
                    {
                        yMax = y; break;
                    }
                    p -= stride + PixelSize * w;
                }

                if (yMin >= yMax)
                {
                    // gros pb de detection : exemple image unie ...
                    bitmap.UnlockBits(bmd);
                    return(Rectangle.Empty);
                }

                // detection bord gauche
                broken = false;
                for (x = 0; x < w; x++)
                {
                    p = (byte *)bmd.Scan0 + yMin * stride;
                    for (y = yMin; y <= yMax; y++)
                    {
                        dR = p[x * PixelSize + 2] - cR;
                        dG = p[x * PixelSize + 1] - cG;
                        dB = p[x * PixelSize] - cB;
                        if (dR > seuil || dR < -seuil || dG > seuil || dG < -seuil || dB > seuil || dB < -seuil)
                        {
                            xMin   = x;
                            broken = true;
                            break;
                        }
                        p += stride;
                    }
                    if (broken)
                    {
                        break;
                    }
                }
                if (xMin == w)
                {
                    // gros pb de detection : exemple image unie ...
                    bitmap.UnlockBits(bmd);
                    return(Rectangle.Empty);
                }

                // detection bord droit
                broken = false;
                for (x = w - 1; x >= 0; x--)
                {
                    p = (byte *)bmd.Scan0 + yMin * stride;
                    for (y = yMin; y <= yMax; y++)
                    {
                        dR = p[x * PixelSize + 2] - cR;
                        dG = p[x * PixelSize + 1] - cG;
                        dB = p[x * PixelSize] - cB;
                        if (dR > seuil || dR < -seuil || dG > seuil || dG < -seuil || dB > seuil || dB < -seuil)
                        {
                            xMax   = x;
                            broken = true;
                            break;
                        }
                        p += stride;
                    }
                    if (broken)
                    {
                        break;
                    }
                    if (x <= xMin)
                    {
                        xMax = x; break;
                    }
                }

                if (xMin >= xMax)
                {
                    // gros pb de detection : exemple image unie ...
                    bitmap.UnlockBits(bmd);
                    return(Rectangle.Empty);
                }

                bitmap.UnlockBits(bmd);

                return(new System.Drawing.Rectangle(xMin, yMin, xMax - xMin + 1, yMax - yMin + 1));
            }
        }
        catch { return(Rectangle.Empty); }
    }
Esempio n. 45
0
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            shader = new Shader(@"vertexShader.vs", @"fragShader.fs");
            shader.Create();

            GL.GenVertexArrays(1, out VAO);
            GL.BindVertexArray(VAO);

            GL.GenBuffers(1, out VBO);
            GL.BindBuffer(BufferTarget.ArrayBuffer, VBO);
            GL.BufferData(BufferTarget.ArrayBuffer, sizeof(float) * vertices.Length, vertices, BufferUsageHint.StaticDraw);

            GL.GenBuffers(1, out EBO);
            GL.BindBuffer(BufferTarget.ElementArrayBuffer, EBO);
            GL.BufferData(BufferTarget.ElementArrayBuffer, sizeof(uint) * indices.Length, indices, BufferUsageHint.StaticDraw);

            // position attribute
            GL.VertexAttribPointer(0, 3, VertexAttribPointerType.Float, false, 8 * sizeof(float), 0);
            GL.EnableVertexAttribArray(0);

            // color attribute
            GL.VertexAttribPointer(1, 3, VertexAttribPointerType.Float, false, 8 * sizeof(float), 3 * sizeof(float));
            GL.EnableVertexAttribArray(1);

            // texture attribute
            GL.VertexAttribPointer(2, 2, VertexAttribPointerType.Float, false, 8 * sizeof(float), 6 * sizeof(float));
            GL.EnableVertexAttribArray(2);

            GL.GenTextures(1, out texture1);
            GL.BindTexture(TextureTarget.Texture2D, texture1);

            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.Repeat);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.Repeat);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);

            Bitmap bitmap = new Bitmap(@"container.jpg");

            Imaging.BitmapData data = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), Imaging.ImageLockMode.ReadOnly,
                                                      Imaging.PixelFormat.Format32bppRgb);
            GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba,
                          bitmap.Width, bitmap.Height, 0,
                          PixelFormat.Bgra, PixelType.UnsignedByte, data.Scan0);

            bitmap.UnlockBits(data);

            GL.GenTextures(1, out texture2);
            GL.BindTexture(TextureTarget.Texture2D, texture2);

            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.Repeat);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.Repeat);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);

            bitmap = new Bitmap(@"awesomeface.png");
            bitmap.RotateFlip(RotateFlipType.Rotate180FlipX);
            data = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), Imaging.ImageLockMode.ReadOnly,
                                   Imaging.PixelFormat.Format32bppRgb);
            GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba,
                          bitmap.Width, bitmap.Height, 0,
                          PixelFormat.Bgra, PixelType.UnsignedByte, data.Scan0);

            bitmap.UnlockBits(data);
        }
Esempio n. 46
0
        public void BuildRateMap()
        {
            // Create bitmap.
            isVRateSet = false;

            string fileAndDirectory = mf.fieldsDirectory + mf.currentFieldDirectory + "\\VR.JPG";

            if (!File.Exists(fileAndDirectory))
            {
                return;
            }

            //create a bitmap mage from the jpeg
            using (Bitmap bmpRate = (Bitmap)Image.FromFile(fileAndDirectory))
            {
                // Lock the bitmap's bits.
                Rectangle rect = new Rectangle(0, 0, bmpRate.Width, bmpRate.Height);
                System.Drawing.Imaging.BitmapData bmpData =
                    bmpRate.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, bmpRate.PixelFormat);

                if (bmpRate.PixelFormat != System.Drawing.Imaging.PixelFormat.Format24bppRgb)
                {
                    return;
                }

                // Get the address of the first line.
                IntPtr ptr = bmpData.Scan0;

                // Declare an array to hold the bytes of the bitmap.
                int    bytes     = Math.Abs(bmpData.Stride) * bmpRate.Height;
                byte[] rgbValues = new byte[bytes];

                // Copy the RGB values into the array.
                System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);

                //save the width and height
                bmpWidth  = bmpRate.Width * 3;
                bmpHeight = bmpRate.Height;

                //24 bits per pixel - 3 bytes format is BGR
                byte[] allBytes = new byte[(int)(bmpWidth * bmpHeight)];
                byte[] flipped  = new byte[(int)(bmpWidth * bmpHeight)];

                ////extract the red values
                int rc = 0;
                for (var r = 0; r < bmpHeight; r++)                         //each scanline row
                {
                    for (var c = 0; c < bmpWidth; c++)                      //each red pixel
                    {
                        allBytes[rc] = rgbValues[(r * bmpData.Stride) + c]; //remove padding bytes
                        rc++;
                    }
                }

                //flip the image top to bottom
                for (int i = 0, j = allBytes.Length - bmpWidth; i < allBytes.Length; i += bmpWidth, j -= bmpWidth)
                {
                    for (int k = 0; k < bmpWidth; ++k)
                    {
                        flipped[i + k] = allBytes[j + k];
                    }
                }

                int bmpPixelCount = flipped.Length;

                double fieldHeight = (mf.maxFieldY - mf.minFieldY); // field height
                double fieldWidth  = (mf.maxFieldX - mf.minFieldX); // field width

                int rateMapScale = 1;

                if (fieldHeight > fieldWidth)
                {
                    rateMapScale = (int)(fieldHeight / 75);
                }
                else
                {
                    rateMapScale = (int)(fieldWidth / 75);
                }

                if (rateMapScale < 4)
                {
                    rateMapScale = 4;                   //blocks no smaller then 8 meters
                }
                //rateMapScale = 4;

                //how many points of height width of the field grid based on 8 meter square blocks
                int gridHeight = (int)fieldHeight / rateMapScale;
                int gridWidth  = (int)fieldWidth / rateMapScale;

                //return to how many pixels wide from color triples
                //bmpWidth /= 3;

                //how much bigger or smaller the bmp is to the field grid
                double bmpToGridScaleWidth  = ((double)bmpWidth) / (double)gridWidth / 3.0;
                double bmpToGridScaleHeight = (double)bmpHeight / (double)gridHeight;

                //put bitmap in 2d array for magnification or minification
                int[,] bmpArr = new int[bmpHeight, bmpWidth];

                for (int i = 0; i < bmpHeight; i++)
                {
                    for (int j = 0; j < bmpWidth; j++)
                    {
                        bmpArr[i, j] = flipped[(i * bmpWidth) + j];
                    }
                }

                // [y,x] or [height,width] or [i,j]
                mapList?.Clear();

                for (int i = 0; i < gridHeight; i++)
                {
                    for (int j = 0; j < gridWidth; j++)
                    {
                        //create map point
                        CMapPt pt = new CMapPt((j * rateMapScale) + (int)mf.minFieldX,
                                               (i * rateMapScale) + (int)mf.minFieldY,
                                               bmpArr[(int)(i * bmpToGridScaleHeight), ((int)(j * bmpToGridScaleWidth) * 3) + 0],
                                               bmpArr[(int)(i * bmpToGridScaleHeight), ((int)(j * bmpToGridScaleWidth) * 3) + 1],
                                               bmpArr[(int)(i * bmpToGridScaleHeight), ((int)(j * bmpToGridScaleWidth) * 3) + 2]
                                               );
                        //add the point
                        mapList.Add(pt);
                    }
                }

                // Unlock the bits, add transparency, make png
                bmpRate.UnlockBits(bmpData);
                bmpRate.MakeTransparent(Color.Black);
                {
                    bmpRate.Save("output.png", ImageFormat.Png);  // Or Png
                }

                try
                {
                    string text2 = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "Output.png");
                    if (File.Exists(text2))
                    {
                        using (Bitmap bitmap2 = new Bitmap(text2))
                        {
                            GL.GenTextures(1, out mf.texture[4]);
                            GL.BindTexture(TextureTarget.Texture2D, mf.texture[4]);
                            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, 9729);
                            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, 9729);
                            BitmapData bitmapData2 = bitmap2.LockBits(new Rectangle(0, 0, bitmap2.Width, bitmap2.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                            GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, bitmapData2.Width, bitmapData2.Height, 0, OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, bitmapData2.Scan0);
                            bitmap2.UnlockBits(bitmapData2);
                        }
                    }
                }
                catch (Exception ex2)
                {
                    //WriteErrorLog("Loading Floor Texture" + ex2);
                    MessageBox.Show("Texture File OUPUT.PNG is Missing", ex2.Message);
                }
            }
        }
Esempio n. 47
0
        private void depthSet(ref DepthImagePixel[] data, int Width, int Height)
        {
            if (prevData == null)
            {
                prevData = data;
            }

            // Lock the bitmap's bits.
            Rectangle rect = new Rectangle(0, 0, Width, Height);

            System.Drawing.Imaging.BitmapData bmpData =
                bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite,
                             bmp.PixelFormat);

            // Get the address of the first line.
            IntPtr ptr = bmpData.Scan0;

            // Declare an array to hold the bytes of the bitmap.
            int bytes = Math.Abs(bmpData.Stride) * bmp.Height;

            byte[] rgbValues = new byte[bytes];

            // Copy the RGB values into the array.
            System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);

            for (int counter = 0, rgb = 0; counter < rgbValues.Length / 4; counter++, rgb += 4)
            {
                int clrComponent = (int)(data[counter].Depth * RGB_RATIO);

                //if ((prevData[counter].Depth == 0 && data[counter].Depth != 0) || (prevData[counter].Depth != 0 && data[counter].Depth == 0))
                //{
                //    rgbValues[rgb] = 0;
                //    rgbValues[rgb + 1] = 0;
                //    rgbValues[rgb + 2] = 0;
                //    continue;
                //}

                if (data[counter].Depth == 0)
                {
                    //Look for non zero pixel

                    int newIndex = findClearPoint(ref data, counter, Width, Height, 5);

                    clrComponent = (int)(data[newIndex].Depth * RGB_RATIO);

                    rgbValues[rgb]     = (byte)clrComponent;
                    rgbValues[rgb + 1] = (byte)clrComponent;
                    rgbValues[rgb + 2] = (byte)clrComponent;

                    continue;
                    //bool flag = false;
                    //for (int iterator = counter; iterator > 0; iterator--)
                    //{
                    //    if (data[iterator].Depth != 0)
                    //    {
                    //        int temp = (int)(data[iterator].Depth * RGB_RATIO);

                    //        rgbValues[rgb] = (byte)temp;
                    //        rgbValues[rgb + 1] = (byte)temp;
                    //        rgbValues[rgb + 2] = (byte)temp;

                    //        flag = true;
                    //        break;

                    //    }
                    //}

                    //if (!flag)
                    //{
                    //    rgbValues[rgb] = 0;
                    //    rgbValues[rgb + 1] = 0;
                    //    rgbValues[rgb + 2] = 0;
                    //}
                    //continue;
                }

                if (InvertColor)
                {
                    clrComponent = 255 - clrComponent;
                }


                rgbValues[rgb]     = (byte)clrComponent;
                rgbValues[rgb + 1] = (byte)clrComponent;
                rgbValues[rgb + 2] = (byte)clrComponent;

                //if (data[counter].IsKnownDepth)
                //{
                //    rgbValues[rgb] = (byte)clrComponent;
                //    rgbValues[rgb + 1] = (byte)clrComponent;
                //    rgbValues[rgb + 2] = (byte)clrComponent;
                //}
                //else
                //{
                //    rgbValues[rgb] = 255;
                //    rgbValues[rgb + 1] = 255;
                //    rgbValues[rgb + 2] = 255;
                //}
            }

            // Copy the RGB values back to the bitmap
            System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, bytes);

            // Unlock the bits.
            bmp.UnlockBits(bmpData);

            // Draw the modified image.
            contentGraphics.DrawImage(bmp, 0, 0);

            //Check Depth Change
            if (focusSet)
            {
                int fData = pointToIndex(Width, focusPoint);

                int Difference = Math.Abs(data[fData].Depth - focusPoint.Depth);

                if (Difference > 20)
                {
                    //Debug.WriteLine("Depth Has Changed (New Distance : " + (float)data[fData].Depth / 1000 + " Meters)");
                    focusPoint.Depth = data[fData].Depth;
                }
            }



            isWorking = false;

            prevData = data;
        }
Esempio n. 48
0
        public void WriteImage(Image image)
        {
            if (image.PixelFormat != PixelFormat.Format32bppArgb)
            {
                throw new Exception("Pixel Format not yet supported.");
            }

            Image tempImage = image;
            float scale     = tempImage.Height / tempImage.Width;

            if (tempImage.Width > 255)
            {
                tempImage = new Bitmap(image, new Size(255, (int)(255 / scale)));
            }
            if (tempImage.Height > 255)
            {
                tempImage = new Bitmap(image, new Size((int)(scale / 255), 255));
            }
            image = tempImage;

            Bitmap    bmp  = new Bitmap(image);
            Rectangle rect = new Rectangle(0, 0, image.Width, bmp.Height);

            System.Drawing.Imaging.BitmapData bmpData =
                bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite,
                             bmp.PixelFormat);

            // Get the address of the first line.
            IntPtr ptr = bmpData.Scan0;

            // Declare an array to hold the bytes of the bitmap.
            int bytes = Math.Abs(bmpData.Stride) * bmp.Height;

            byte[] rgbValues = new byte[bytes];

            // Copy the RGB values into the array.
            System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);

            List <int[]> tempList  = new List <int[]>();
            List <int>   tempList2 = new List <int>();
            int          nonzero   = 0;

            for (int i = 0; i < rgbValues.Length;)
            {
                int byte1    = (((int)rgbValues[i]) << 24);
                int byte2    = (((int)rgbValues[i + 1]) << 16);
                int byte3    = (((int)rgbValues[i + 1]) << 8);
                int byte4    = (((int)rgbValues[i + 1]));
                int finalInt = byte1 | byte2 | byte3 | byte4;
                if (finalInt != -1)
                {
                    nonzero++;
                }
                tempList2.Add(finalInt);
                if (((i += 4) % bmpData.Stride) == 0)
                {
                    tempList.Add(tempList2.ToArray());
                    tempList2 = new List <int>();
                }
            }
            int[][] thefinalarray = tempList.ToArray();

            int[][] anotherarray = (int[][])thefinalarray.Clone();
            for (int i = 0; i < anotherarray.Length; i++)
            {
                for (int j = 0; j < anotherarray[i].Length; j++)
                {
                    if (anotherarray[i][j] != -1)
                    {
                        anotherarray[i][j] = 1;
                    }
                    else
                    {
                        anotherarray[i][j] = 0;
                    }
                }
            }
            // Unlock the bits.
            bmp.UnlockBits(bmpData);
            betterPrintImage(anotherarray);
        }
        private async Task <Form> RenderNewExpansion(int scale)
        {
            // var tasks = new List<Task<bool>>();
            int imageArea = mWidth * mHeight;
            //int groupsize = imageArea / 2; //Environment.ProcessorCount;
            //int leftovers = imageArea % 2;//Environment.ProcessorCount;
            Form window = new Form();

            tWidth = mWidth;
            if (scale == 2)
            {
                if ((mWidth * scale) % 4 != 0)
                {
                    int tempMod = mWidth % 4;
                    mWidth -= tempMod;
                }
            }
            PixelFormat format = imageDepth == 3 ? PixelFormat.Format24bppRgb : PixelFormat.Format32bppArgb;

            bigImage  = new Bitmap(mWidth * scale, mHeight * scale, format);
            bBigImage = ConvToByteArray(bigImage);
            PictureBox newImageHolder = new PictureBox {
                Height = bigImage.Height, Width = bigImage.Width
            };

            window.Height     = bigImage.Height < 100?bigImage.Height:1000;
            window.Width      = bigImage.Width;
            window.AutoScroll = true;
            // for (int a = 0; a < 2; a++)
            // {
            //     if (a != 1 - 2)
            //         tasks.Add(Task.Run(() => ProcessImageChunk((a * groupsize), (groupsize - 1) + (a * groupsize), a, scale)));
            //     else
            //         tasks.Add(Task.Run(() => ProcessImageChunk((a * groupsize), groupsize + (a * groupsize) + leftovers, a, scale)));
            // }
            //// Task.WaitAll(tasks.ToArray());
            ProcessImageChunk(0, imageArea, 0, scale);

            var   ms    = new MemoryStream(bBigImage);
            Image image = Image.FromStream(ms);

            if (mWidth * scale % 4 != 0)
            {
                Bitmap    temp = new Bitmap(image);
                Rectangle rect = new Rectangle(0, 0, mWidth, mHeight);
                System.Drawing.Imaging.BitmapData mInfo = temp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, temp.PixelFormat);
                for (int y = 0; y < mHeight; ++y)
                {
                    IntPtr mem = (IntPtr)((long)mInfo.Scan0 + y * mInfo.Stride);
                    Marshal.Copy(mem, bBigImage, y * mWidth * 3, mWidth * 3);
                }
            }
            mWidth = tWidth;
            ms     = new MemoryStream(bBigImage);
            image  = Image.FromStream(ms);
            if (flip)
            {
                image.RotateFlip(RotateFlipType.Rotate180FlipX);
            }
            newImageHolder.Image = image;

            window.Controls.Add(newImageHolder);
            return(window);
        }
Esempio n. 50
0
        public unsafe CVImage(System.Drawing.Bitmap sourceImage)
        {
            System.Drawing.Rectangle rect = new System.Drawing.Rectangle();
            rect.X      = 0;
            rect.Y      = 0;
            rect.Width  = sourceImage.Width;
            rect.Height = sourceImage.Height;

            System.Drawing.Imaging.BitmapData bData =
                sourceImage.LockBits(rect,
                                     System.Drawing.Imaging.ImageLockMode.ReadWrite,
                                     PixelFormat.Format24bppRgb);

            // New implementation:
            int pixelSizeInBytes = 8;
            int numberOfChannels = 3;

            this.image =
                PInvoke.cvCreateImage(
                    new __CvSize(sourceImage.Width, sourceImage.Height),
                    pixelSizeInBytes,
                    numberOfChannels);
            CVUtils.CheckLastError();

            unsafe
            {
                int   height = sourceImage.Height;
                int   width  = sourceImage.Width;
                byte *pRead  = (byte *)bData.Scan0.ToPointer();
                byte *pWrite = this.Internal.ToPointer()->imageData;

                int nReadStride  = bData.Stride - width * numberOfChannels;
                int nWriteStride = this.Internal.ToPointer()->widthStep - width * numberOfChannels;

                for (int row = 0; row < height; ++row, pRead += nReadStride, pWrite += nWriteStride)
                {
                    for (int col = 0; col < width; ++col, pRead += numberOfChannels, pWrite += numberOfChannels)
                    {
                        pWrite[0] = pRead[0]; // Blue
                        pWrite[1] = pRead[1]; // Green
                        pWrite[2] = pRead[2]; // Red
                    }
                }
            }


            #region Old Implementation
            //__IplImagePtr tempImage = PInvoke.cvCreateImageHeader(new __CvSize(sourceImage.Width, sourceImage.Height), 8, Bitmap.GetPixelFormatSize(sourceImage.PixelFormat) / 8);
            //tempImage.ToPointer()->imageData = (byte*)bData.Scan0.ToPointer();

            //__IplImagePtr[] dst = new __IplImagePtr[4];
            //for (int i = 0; i < 4; ++i)
            //{
            //    dst[i] = IntPtr.Zero;
            //}
            //for (int i = 0; i < tempImage.ToPointer()->nChannels; i++)
            //{
            //    dst[i] = PInvoke.cvCreateImage(new __CvSize(sourceImage.Width, sourceImage.Height), 8, 1);
            //}

            //PInvoke.cvSplit(
            //    tempImage,
            //    dst[0],
            //    dst[1],
            //    dst[2],
            //    dst[3]);

            //image = PInvoke.cvCreateImage(new __CvSize(sourceImage.Width, sourceImage.Height), 8, 3);
            //PInvoke.cvMerge(dst[0], dst[1], dst[2], IntPtr.Zero, image) ;

            //for (int i = 0; i < tempImage.ToPointer()->nChannels; i++)
            //{
            //    PInvoke.cvReleaseImage(ref dst[i]);
            //}
            #endregion

            created = true;
            sourceImage.UnlockBits(bData);
        }
Esempio n. 51
0
        private Bitmap BmpFrame()
        {
            Bitmap bitmap = null;

            if (_iconData != null && _bestBitDepth == 32)
            {
                // GDI+ doesnt handle 32 bpp icons with alpha properly
                // we load the icon ourself from the byte table
                bitmap = new Bitmap(Size.Width, Size.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                Debug.Assert(_bestImageOffset >= 0 && (_bestImageOffset + _bestBytesInRes) <= _iconData.Length, "Illegal offset/length for the Icon data");

                unsafe
                {
                    System.Drawing.Imaging.BitmapData bmpdata = bitmap.LockBits(new Rectangle(0, 0, Size.Width, Size.Height),
                                                                                System.Drawing.Imaging.ImageLockMode.WriteOnly,
                                                                                System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                    try
                    {
                        uint *pixelPtr = (uint *)bmpdata.Scan0.ToPointer();

                        // jumping the image header
                        int newOffset = _bestImageOffset + Marshal.SizeOf(typeof(SafeNativeMethods.BITMAPINFOHEADER));
                        // there is no color table that we need to skip since we're 32bpp

                        int lineLength = Size.Width * 4;
                        int width      = Size.Width;
                        for (int j = (Size.Height - 1) * 4; j >= 0; j -= 4)
                        {
                            Marshal.Copy(_iconData, newOffset + j * width, (IntPtr)pixelPtr, lineLength);
                            pixelPtr += width;
                        }

                        // note: we ignore the mask that's available after the pixel table
                    }
                    finally
                    {
                        bitmap.UnlockBits(bmpdata);
                    }
                }
            }
            else if (_bestBitDepth == 0 || _bestBitDepth == 32)
            { // we don't know or we are 32bpp for sure
                //we don't have any icon data, let's fish out the data from the handle that we got...
                // we have to fish out the data for this icon if the icon is a 32bpp icon
                SafeNativeMethods.ICONINFO info = new SafeNativeMethods.ICONINFO();
                SafeNativeMethods.GetIconInfo(new HandleRef(this, _handle), info);
                SafeNativeMethods.BITMAP bmp = new SafeNativeMethods.BITMAP();
                try
                {
                    if (info.hbmColor != IntPtr.Zero)
                    {
                        SafeNativeMethods.GetObject(new HandleRef(null, info.hbmColor), Marshal.SizeOf(typeof(SafeNativeMethods.BITMAP)), bmp);
                        if (bmp.bmBitsPixel == 32)
                        {
                            Bitmap     tmpBitmap  = null;
                            BitmapData bmpData    = null;
                            BitmapData targetData = null;
                            try
                            {
                                tmpBitmap = Bitmap.FromHbitmap(info.hbmColor);

                                // In GDI+ the bits are there but the bitmap was created with no alpha channel
                                // so copy the bits by hand to a new bitmap
                                // we also need to go around a limitation in the way the ICON is stored (ie if it's another bpp
                                // but stored in 32bpp all pixels are transparent and not opaque)
                                // (Here you mostly need to remain calm....)
                                bmpData = tmpBitmap.LockBits(new Rectangle(0, 0, tmpBitmap.Width, tmpBitmap.Height), ImageLockMode.ReadOnly, tmpBitmap.PixelFormat);

                                // we need do the following if the image has alpha because otherwise the image is fully transparent even though it has data
                                if (BitmapHasAlpha(bmpData))
                                {
                                    bitmap     = new Bitmap(bmpData.Width, bmpData.Height, PixelFormat.Format32bppArgb);
                                    targetData = bitmap.LockBits(new Rectangle(0, 0, bmpData.Width, bmpData.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);

                                    CopyBitmapData(bmpData, targetData);
                                }
                            }
                            finally
                            {
                                if (tmpBitmap != null && bmpData != null)
                                {
                                    tmpBitmap.UnlockBits(bmpData);
                                }
                                if (bitmap != null && targetData != null)
                                {
                                    bitmap.UnlockBits(targetData);
                                }
                            }
                            tmpBitmap.Dispose();
                        }
                    }
                }
                finally
                {
                    if (info.hbmColor != IntPtr.Zero)
                    {
                        SafeNativeMethods.IntDeleteObject(new HandleRef(null, info.hbmColor));
                    }
                    if (info.hbmMask != IntPtr.Zero)
                    {
                        SafeNativeMethods.IntDeleteObject(new HandleRef(null, info.hbmMask));
                    }
                }
            }


            if (bitmap == null)
            {
                // last chance... all the other cases (ie non 32 bpp icons coming from a handle or from the bitmapData)

                // we have to do this rather than just return Bitmap.FromHIcon because
                // the bitmap returned from that, even though it's 32bpp, just paints where the mask allows it
                // seems like another GDI+ weirdness. might be interesting to investigate further. In the meantime
                // this looks like the right thing to do and is not more expansive that what was present before.

                Size size = Size;
                bitmap = new Bitmap(size.Width, size.Height); // initialized to transparent
                Graphics graphics = null;
                try
                {
                    graphics = Graphics.FromImage(bitmap);
                    try
                    {
                        using (Bitmap tmpBitmap = Bitmap.FromHicon(Handle))
                        {
                            graphics.DrawImage(tmpBitmap, new Rectangle(0, 0, size.Width, size.Height));
                        }
                    }
                    catch (ArgumentException)
                    { // GDI+ weirdness episode MMMCLXXXXIVI, sometime FromHicon crash with no real reason,
                        // backup plan is to just draw the image like we used to.
                        // NOTE: FromHIcon is also where we have the buffer overrun
                        // if width and height are mismatched
                        Draw(graphics, new Rectangle(0, 0, size.Width, size.Height));
                    }
                }
                finally
                {
                    if (graphics != null)
                    {
                        graphics.Dispose();
                    }
                }


                // gpr: GDI+ is filling the surface with a sentinel color for GetDC,
                // but is not correctly cleaning it up again, so we have to for it.
                Color fakeTransparencyColor = Color.FromArgb(0x0d, 0x0b, 0x0c);
                bitmap.MakeTransparent(fakeTransparencyColor);
            }

            Debug.Assert(bitmap != null, "Bitmap cannot be null");
            return(bitmap);
        }
Esempio n. 52
0
    private Bitmap TrimImage(Bitmap img, int margin)
    {
        try
        {
            // Bitmap img = (Bitmap)Image.FromFile(path);
            //get image data
            System.Drawing.Imaging.BitmapData bd = img.LockBits(new Rectangle(Point.Empty, img.Size),
                                                                ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
            int[] rgbValues = new int[img.Height * img.Width];
            Marshal.Copy(bd.Scan0, rgbValues, 0, rgbValues.Length);
            img.UnlockBits(bd);


            #region determine bounds
            int left   = bd.Width - margin;
            int top    = bd.Height - margin;
            int right  = margin;
            int bottom = margin;

            //determine top
            for (int i = 0; i < rgbValues.Length; i++)
            {
                int color = rgbValues[i] & 0xffffff;
                if (color != 0xffffff)
                {
                    int r = i / bd.Width;
                    int c = i % bd.Width;

                    if (left > c)
                    {
                        left = c;
                    }
                    if (right < c)
                    {
                        right = c;
                    }
                    bottom = r;
                    top    = r;
                    break;
                }
            }

            //determine bottom
            for (int i = rgbValues.Length - 1; i >= 0; i--)
            {
                int color = rgbValues[i] & 0xffffff;
                if (color != 0xffffff)
                {
                    int r = i / bd.Width;
                    int c = i % bd.Width;

                    if (left > c)
                    {
                        left = c;
                    }
                    if (right < c)
                    {
                        right = c;
                    }
                    bottom = r;
                    break;
                }
            }

            if (bottom > top)
            {
                for (int r = top + 1; r < bottom; r++)
                {
                    //determine left
                    for (int c = 0; c < left; c++)
                    {
                        int color = rgbValues[r * bd.Width + c] & 0xffffff;
                        if (color != 0xffffff)
                        {
                            if (left > c)
                            {
                                left = c;
                                break;
                            }
                        }
                    }

                    //determine right
                    for (int c = bd.Width - 1; c > right; c--)
                    {
                        int color = rgbValues[r * bd.Width + c] & 0xffffff;
                        if (color != 0xffffff)
                        {
                            if (right < c)
                            {
                                right = c;
                                break;
                            }
                        }
                    }
                }
            }

            int width  = right - left + 1;
            int height = bottom - top + 1;
            #endregion

            //copy image data
            int[] imgData = new int[width * height];
            for (int r = top; r <= bottom; r++)
            {
                Array.Copy(rgbValues, r * bd.Width + left, imgData, (r - top) * width, width);
            }

            //create new image
            Bitmap     newImage = new Bitmap(width, height, PixelFormat.Format32bppArgb);
            BitmapData nbd
                = newImage.LockBits(new Rectangle(0, 0, width, height),
                                    ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
            Marshal.Copy(imgData, 0, nbd.Scan0, imgData.Length);
            newImage.UnlockBits(nbd);
            img.Dispose();
            img = null;
            return(newImage);
        }
        catch (Exception ex)
        {
            Log("TrimImage", ex.Message, true, ex);
        }
        return(null);
    }
Esempio n. 53
0
        static void Main(string[] args)
        {
            double[] Intensities = new double[90];
            bool[]   Phases      = new bool[90];

            // Calculation of mean intensity for each image
            for (int i = 1; i <= 90; i++)
            {
                if (i > 65)
                {
                    Phases[i - 1] = false;
                }
                else
                {
                    Phases[i - 1] = true;
                }

                String path = "c:\\Data/" + i.ToString() + ".jpeg";
                Bitmap bmp  = new Bitmap(path);

                Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
                System.Drawing.Imaging.BitmapData bmpData =
                    bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite,
                                 bmp.PixelFormat);

                // Get the address of the first line.
                IntPtr ptr = bmpData.Scan0;

                // Declare an array to hold the bytes of the bitmap.
                int    bytes     = Math.Abs(bmpData.Stride) * bmp.Height;
                byte[] rgbValues = new byte[bytes];

                // Copy the RGB values into the array.
                System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);

                double mean_r = 0.0, mean_g = 0.0, mean_b = 0.0, mean_f;
                int    p_num = 0;

                for (int counter = 0; counter < rgbValues.Length; counter += 3)
                {
                    mean_r += rgbValues[counter];
                    mean_g += rgbValues[counter + 1];
                    mean_b += rgbValues[counter + 2];
                }

                p_num   = bmp.Width * bmp.Height;
                mean_r /= p_num;
                mean_g /= p_num;
                mean_b /= p_num;
                mean_f  = mean_r * 0.36 + 0.53 * mean_g + 0.11 * mean_b;

                Intensities[i - 1] = mean_f;
                //Console.WriteLine("mean_f: " + mean_f);
                bmp.UnlockBits(bmpData);
            }

            var range = new Microsoft.ML.Probabilistic.Models.Range(90);
            VariableArray <bool> DayPhase = Variable.Array <bool>(range);
            //DayPhase[range] = Variable.Bernoulli(0.5).ForEach(range);
            Variable <double>      Mean      = Variable.GaussianFromMeanAndVariance(100, 100).Named("Mean");
            Variable <double>      Sigma     = Variable.GammaFromShapeAndScale(1, 1).Named("Sigma");
            Variable <double>      Threshold = Variable.GaussianFromMeanAndPrecision(Mean, Sigma).Named("Threshold");
            VariableArray <double> v         = Variable.Constant(Intensities, range);

            using (Variable.ForEach(range))
            {
                using (Variable.If(v[range] >= Threshold))
                {
                    DayPhase[range] = true;
                }
                using (Variable.IfNot(v[range] >= Threshold))
                {
                    DayPhase[range] = false;
                }
            }

            DayPhase.ObservedValue = Phases;

            InferenceEngine engine = new InferenceEngine();

            engine.Algorithm = new ExpectationPropagation();
            //InferenceEngine.Visualizer = new WindowsVisualizer();
            engine.ShowFactorGraph = false;
            Gaussian InfThreshold = engine.Infer <Gaussian>(Threshold);
            Gaussian InfMean      = engine.Infer <Gaussian>(Mean);

            Console.WriteLine("inf threshold: " + InfThreshold);
            Console.WriteLine("inf mean: " + InfMean);
            Console.WriteLine();
        }
Esempio n. 54
0
        /// <summary>
        /// Checks to see if bitmap contians a grayscale image.
        /// </summary>
        /// <param name="testImage">Image to test</param>
        /// <returns>true if grayscale.</returns>
        public unsafe static bool IsGrayScale(Bitmap testImage)
        {
            bool      result = true;
            int       h, w;
            int       r, g, b;
            int       margin = 2;                             // margin for error in intensity values (pixel color's within two points of eachother
            Rectangle rect;
            byte *    ptr;                                    // the use of pointers is what makes this "unsafe" code.

            System.Drawing.Imaging.BitmapData bmpData = null; // will hold the data about the bitmap image stored in managed memory.

            try
            {
                // Force the image to 32 bit ARGB memory bitmap format, lock it in manage memory, and validate that it is the type of image data expected.

                rect    = new Rectangle(0, 0, testImage.Width, testImage.Height);
                bmpData = testImage.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);  // lock it and get it's descriptor
                if (bmpData.Stride < 0)
                {
                    throw new ApplicationException("ToSingle only works on images with a positive stride.");
                }
                if (bmpData.PixelFormat != System.Drawing.Imaging.PixelFormat.Format32bppArgb)
                {
                    throw new ApplicationException("Wrong Pixel Format. ToSingle only works on 32 bit ARGB pixels.");
                }

                // Get a C style pointer to the image data

                ptr = (byte *)bmpData.Scan0.ToPointer();

                // Test pixel color planes for same value
                // 32 bit Memory Bitmap image data is ordered blue byte, green byte, red byte, and Alpha channel byte (transparancy).

                for (h = 0; h < testImage.Height; h++)    // cross the image rows
                {
                    for (w = 0; w < testImage.Width; w++) // cross the image columns
                    {
                        b = *ptr++;
                        g = *ptr++;
                        r = *ptr++;
                        ptr++;  // skip the transparency byte
                        if ((Math.Abs(r - b) + Math.Abs(b - g) + Math.Abs(g - r)) > margin)
                        {
                            result = false;
                        }
                        if (!result)
                        {
                            break;
                        }
                    }
                    if (!result)
                    {
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (bmpData != null)
                {
                    testImage.UnlockBits(bmpData);                      // Unlock the image data in managed code
                }
            }
            return(result);
        }
Esempio n. 55
0
        private static void SendTestPattern()
        {
            try
            {
                unsafe
                {
                    Bitmap testPattern = new Bitmap(TEST_PATTERN_IMAGE_PATH);

                    // Get the stride.
                    Rectangle rect = new Rectangle(0, 0, testPattern.Width, testPattern.Height);
                    System.Drawing.Imaging.BitmapData bmpData =
                        testPattern.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite,
                                             testPattern.PixelFormat);

                    // Get the address of the first line.
                    int stride = bmpData.Stride;

                    testPattern.UnlockBits(bmpData);

                    // Initialise the video codec and color converter.
                    SIPSorceryMedia.VpxEncoder vpxEncoder = new VpxEncoder();
                    vpxEncoder.InitEncoder((uint)testPattern.Width, (uint)testPattern.Height, (uint)stride);

                    SIPSorceryMedia.ImageConvert colorConverter = new ImageConvert();

                    byte[] sampleBuffer  = null;
                    byte[] encodedBuffer = null;
                    int    sampleCount   = 0;
                    uint   rtpTimestamp  = 0;

                    while (!_exit)
                    {
                        if (OnTestPatternSampleReady != null)
                        {
                            var stampedTestPattern = testPattern.Clone() as System.Drawing.Image;
                            AddTimeStampAndLocation(stampedTestPattern, DateTime.UtcNow.ToString("dd MMM yyyy HH:mm:ss:fff"), "Test Pattern");
                            sampleBuffer = BitmapToRGB24(stampedTestPattern as System.Drawing.Bitmap);

                            fixed(byte *p = sampleBuffer)
                            {
                                byte[] convertedFrame = null;
                                colorConverter.ConvertRGBtoYUV(p, VideoSubTypesEnum.BGR24, testPattern.Width, testPattern.Height, stride, VideoSubTypesEnum.I420, ref convertedFrame);

                                fixed(byte *q = convertedFrame)
                                {
                                    int encodeResult = vpxEncoder.Encode(q, convertedFrame.Length, 1, ref encodedBuffer);

                                    if (encodeResult != 0)
                                    {
                                        logger.LogWarning("VPX encode of video sample failed.");
                                        continue;
                                    }
                                }
                            }

                            stampedTestPattern.Dispose();
                            stampedTestPattern = null;

                            OnTestPatternSampleReady?.Invoke(SDPMediaTypesEnum.video, rtpTimestamp, encodedBuffer);

                            encodedBuffer = null;

                            sampleCount++;
                            rtpTimestamp += VP8_TIMESTAMP_SPACING;
                        }

                        Thread.Sleep(30);
                    }
                }
            }
            catch (Exception excp)
            {
                logger.LogError("Exception SendTestPattern. " + excp);
            }
        }
Esempio n. 56
0
        private Bitmap GrayPicture(string filename, int index, PictureOpticflowDataResultStruct[] PictureOpticflowDataResultArray)
        {
            Bitmap bmp           = (Bitmap)Image.FromFile(filename);
            int    PictureWidth  = bmp.Width;
            int    PictureHeight = bmp.Height;

            int    strideValue;
            double max = 0, min = 255;
            float  AverageOrigingray = 0;
            double SumCurentgray     = 0;
            int    lenth             = PictureWidth * PictureHeight;

            if (lenth == PictureOpticflowDataResultArray[index].OpticflowResultFOfPixelArray.Length)
            {
                Apicturegrayinformation[] ApicturegrayinformationArray = new Apicturegrayinformation[lenth];

                Rectangle rect = new Rectangle(0, 0, PictureWidth, PictureHeight);
                System.Drawing.Imaging.BitmapData bmpData = bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, bmp.PixelFormat);
                IntPtr ptr = bmpData.Scan0;

                if (grayed == true) // 灰度化显示
                {
                    if (PictureWidth % 4 == 0)
                    {
                        strideValue = PictureWidth * 3;

                        byte[] rgbValues = new byte[lenth * 3];
                        System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, lenth * 3);
                        //灰度化
                        Dogray(ref ApicturegrayinformationArray, rgbValues, strideValue, PictureWidth, PictureHeight, false, ref max, ref min, ref AverageOrigingray);

                        //灰度拉伸
                        graystretch(ref ApicturegrayinformationArray, max, min, ref SumCurentgray);
                    }
                    else
                    {
                        strideValue = bmpData.Stride;
                        int    bytes     = strideValue * PictureHeight;
                        byte[] rgbValues = new byte[bytes];
                        System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);

                        //灰度化
                        Dogray(ref ApicturegrayinformationArray, rgbValues, strideValue, PictureWidth, PictureHeight, false, ref max, ref min, ref AverageOrigingray);
                        //灰度拉伸
                        graystretch(ref ApicturegrayinformationArray, max, min, ref SumCurentgray);
                        //光滑去噪
                        //showgussSmooth(ref ApicturegrayinformationArray);
                    }

                    bmp.UnlockBits(bmpData);
                    bmp.Dispose();
                    GC.Collect();

                    curBitmap = CreateBmpByGrays(ApicturegrayinformationArray, index, PictureWidth, PictureHeight, PictureOpticflowDataResultArray);
                    return(curBitmap);
                }    // 灰度化显示
                else // 彩色显示
                {
                    float tmp = 0;

                    if (PictureWidth % 4 == 0)
                    {
                        strideValue = PictureWidth * 3;

                        byte[] rgbValues = new byte[lenth * 3];
                        System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, lenth * 3);

                        for (int i = 0; i < lenth; i++)
                        {
                            for (int j = 0; j < 3; j++)
                            {
                                if (biaodingDsp == true)
                                {
                                    tmp = rgbValues[i * 3 + j];
                                }
                                else
                                {
                                    tmp = 0;
                                }
                                if (graydeltaAdd == true)   // 灰度叠加
                                {
                                    if (forwardAdd == true) // 正向叠加
                                    {
                                        tmp += PictureOpticflowDataResultArray[index].OpticflowResultFOfPixelArray[i].Greyvalue * FactorOfGreygrad;
                                    }
                                    else
                                    {
                                        tmp -= PictureOpticflowDataResultArray[index].OpticflowResultFOfPixelArray[i].Greyvalue * FactorOfGreygrad;
                                    }
                                }
                                if (tmp > 255)
                                {
                                    rgbValues[i * 3 + j] = 255;
                                }
                                if (tmp < 0)
                                {
                                    rgbValues[i * 3 + j] = 0;
                                }
                                if ((tmp >= 0) & (tmp <= 255))
                                {
                                    rgbValues[i * 3 + j] = (byte)tmp;
                                }
                            }
                        }
                        System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, lenth * 3);
                    }
                    else
                    {
                        strideValue = bmpData.Stride;
                        int    bytes     = strideValue * PictureHeight;
                        byte[] rgbValues = new byte[bytes];
                        System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);

                        for (int i = 0; i < rgbValues.Length; i++)
                        {
                            if (biaodingDsp == true)
                            {
                                tmp = rgbValues[i];
                            }
                            else
                            {
                                tmp = 0;
                            }
                            if (graydeltaAdd == true)   // 灰度叠加
                            {
                                if (forwardAdd == true) // 正向叠加
                                {
                                    tmp += PictureOpticflowDataResultArray[index].OpticflowResultFOfPixelArray[i].Greyvalue * FactorOfGreygrad;
                                }
                                else
                                {
                                    tmp -= PictureOpticflowDataResultArray[index].OpticflowResultFOfPixelArray[i].Greyvalue * FactorOfGreygrad;
                                }
                            }
                            if (tmp > 255)
                            {
                                rgbValues[i] = 255;
                            }
                            if (tmp < 0)
                            {
                                rgbValues[i] = 0;
                            }
                            if ((tmp >= 0) & (tmp <= 255))
                            {
                                rgbValues[i] = (byte)tmp;
                            }
                        }
                        System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, bytes);
                    }

                    bmp.UnlockBits(bmpData);

                    return(bmp);
                }
            }
            else
            {
                MessageBox.Show("计算灰度差的照片大小与当前照片大小不一致!!!");
                return(bmp);
            }
        }
Esempio n. 57
0
        public ImageManip(string _imageLocation)
        {
            Location = _imageLocation;



            if (File.Exists(_imageLocation))
            {
                //int offset = 0;
                Byte[] fsBuffer;

                //string[] Path = { _imageLocation, _name };
                FileStream fs = File.Open(path: _imageLocation, mode: FileMode.Open, access: FileAccess.Read);

                // Start by reading file header..
                fsBuffer = new Byte[14]; // size 40 bytes
                fs.Read(fsBuffer, 0, 14);
                bmpfh = new BMPFileHeader(fsBuffer);

                // Then image header, 40 bytes
                fsBuffer = new Byte[40];
                fs.Read(fsBuffer, 0, 40);
                bmpih = new BMPImageHeader(fsBuffer);


                // How many bytes per pixel
                bytesperpixel = bmpih.BiBitCount / 8;

                // Read pixel array
                int totalBytes  = (int)bmpih.BiWidth * (int)bmpih.BiHeight * bytesperpixel;
                int totalWidth  = (int)bmpih.BiWidth;
                int totalHeight = (int)bmpih.BiHeight;

                fsBuffer = new Byte[totalBytes];
                fs.Read(fsBuffer, 0, totalBytes);
                //int indeks = 0;


                if (totalHeight == totalWidth)
                {
                    while (SIZE <= totalHeight)
                    {
                        SIZE *= 2;
                    }
                }
                else if (totalHeight < totalWidth)
                {
                    while (SIZE <= totalHeight)
                    {
                        SIZE *= 2;
                    }
                }
                else if (totalHeight > totalWidth)
                {
                    while (SIZE <= totalWidth)
                    {
                        SIZE *= 2;
                    }
                }


                Pixel[,] Pix       = new Pixel[totalHeight, totalWidth];
                Complex[,] BigData = new Complex[SIZE, SIZE];


                Complex[] Data = new Complex[SIZE];
                if (bytesperpixel == 1) // If an image is in grayscale
                {
                    for (int j = 0; j < (int)bmpih.BiHeight; j++)
                    {
                        for (int i = 0; i < (int)bmpih.BiWidth; i++)
                        {
                            //
                            Pixel Pic = new Pixel(fsBuffer[j * (int)bmpih.BiWidth + i]);
                            Pix[j, i] = Pic;
                        }
                    }
                }
                else // Otherwise if image is RGB
                {
                    for (int j = 0; j < (int)bmpih.BiHeight; j++)
                    {
                        for (int i = 0; i < (int)bmpih.BiWidth; i++)
                        {
                            //if(i == 0 && j == 0)
                            //{

                            //Pix[j, i] = if0;
                            //Pix[j, i+1] = if1;
                            // Complex data = new Complex()
                            //}
                            Pixel Pic = new Pixel(fsBuffer[j * (int)bmpih.BiWidth + i], fsBuffer[j * (int)bmpih.BiWidth + i + 1], fsBuffer[j * (int)bmpih.BiWidth + i + 2]);
                            Pix[j, i] = Pic;
                            double sum = Math.Sqrt(Math.Pow(Pix[j, i].Red, 2) + Math.Pow(Pix[j, i].Green, 2) + Math.Pow(Pix[j, i].Blue, 2));

                            //Pixel Buffer = new Pixel(fsBuffer[j * (int)bmpih.BiWidth + i + 3], fsBuffer[j * (int)bmpih.BiWidth + i + 4], fsBuffer[j * (int)bmpih.BiWidth + i + 5]);
                            //if (i < SIZE && j < SIZE)
                            //{

                            //double sumNext = Buffer.Red + Buffer.Green + Buffer.Blue;
                            //Complex data = new Complex(sum, sumNext);
                            Complex single = new Complex(sum);
                            Complex bit    = new Complex(fsBuffer[j * (int)bmpih.BiWidth + i]);
                            //Data[indeks] = data;
                            BigData[j, i] = bit;
                            // Console.WriteLine(BigData[j, i].real + " " + BigData[j, i].imag);
                            //}

                            //indeks++;


                            //Console.WriteLine("Pix["+ j + ", " + i + "].Red " + Pix[j,i].Red + " " + "Pix[" + j + ", " + i + "].Green " + Pix[j,i].Green + " " + "Pix[" + j + ", " + i + "].Blue " + Pix[j,i].Blue + ", suma: " + sum);
                            //Complex complexPixel = new Complex(1, Pix[j-1,i-1], Pix[j,i]);
                        }
                    }
                }


                for (int j = 0; j < SIZE; j++)
                {
                    for (int i = 0; i < SIZE; i++)
                    {
                        if (j >= totalHeight)
                        {
                            BigData[j, i] = new Complex(0);
                        }
                        if (i >= totalWidth)
                        {
                            BigData[j, i] = new Complex(0);
                        }
                    }
                }


                Complex[,] Fft = new Complex[SIZE, SIZE];
                int[,] toInt2D = new int[SIZE, SIZE];
                uint[] toInt = new uint[SIZE * SIZE];
                for (int j = 0; j < SIZE; j++) // Transformacja wierszy
                {
                    Complex[] tempRow = new Complex[SIZE];
                    for (int i = 0; i < SIZE; i++)
                    {
                        tempRow[i] = BigData[j, i];
                    }
                    Complex[] tempFFT = Fourier.FFT(tempRow);

                    for (int k = 0; k < SIZE; k++)
                    {
                        Fft[j, k] = tempFFT[k];
                        //Console.WriteLine(Fft[j, k].real + " " + Fft[j, k].imag);
                    }
                }

                for (int j = 0; j < SIZE; j++) // Transformacja kolumn
                {
                    Complex[] tempColumn = new Complex[SIZE];
                    for (int i = 0; i < SIZE; i++)
                    {
                        tempColumn[i] = Fft[i, j];
                    }
                    Complex[] tempFFT = Fourier.FFT(tempColumn);
                    for (int k = 0; k < SIZE; k++)
                    {
                        Fft[j, k] = tempFFT[k];
                        //toInt2D[k,j] = (int)Math.Abs(255*Fft[k, j].Phase);
                        //Console.WriteLine(Fft[j, k].real + " " + Fft[j, k].imag);
                        //Console.WriteLine("Gauss polar form: " + toInt[k]);
                    }
                }


                //Wynik do tablicy int[,]

                toInt2D = Fourier.MagnitudePlot(Fft);

                byte[] pixelValues = new byte[2 * totalHeight * totalWidth];
                int    index       = 0;
                for (int j = 0; j < totalHeight; j++)
                {
                    for (int i = 0; i < totalWidth; i++)
                    {
                        pixelValues[index]     = (byte)(((UInt16)(toInt2D[j, i]) & 0xFF00) >> 8);
                        pixelValues[index + 1] = (byte)(((UInt16)(toInt2D[j, i]) & 0x00FF));
                        index += 2;
                        //toInt[ind] = (uint)toInt2D[j, i];
                        //Color pixelColor = imageFinal.GetPixel(j, i);

                        //Color newColor = Color.FromArgb(toInt2D[j, i]);
                        //imageFinal.SetPixel(j, i, (Color)toInt2D[j,i]);

                        //Console.WriteLine(toInt2D[j, i]);
                    }
                }

                byte[] newPixelVal = new byte[totalHeight * totalWidth * 6];
                newPixelVal = Convert16BitGrayScaleToRgb48(pixelValues, totalWidth, totalHeight);
                Bitmap    img       = new Bitmap(totalWidth, totalHeight, System.Drawing.Imaging.PixelFormat.Format48bppRgb);
                Rectangle dimension = new Rectangle(0, 0, img.Width, img.Height);
                System.Drawing.Imaging.BitmapData picData = img.LockBits(dimension, System.Drawing.Imaging.ImageLockMode.ReadWrite, img.PixelFormat);
                IntPtr pixelStartAddress = picData.Scan0;
                System.Runtime.InteropServices.Marshal.Copy(newPixelVal, 0, pixelStartAddress, newPixelVal.Length);
                img.UnlockBits(picData);

                img.Save(@"F:\pablito\downloads\bmp_manip\finall.bmp");


                toInt2D = Fourier.PhasePlot(Fft);


                index = 0;
                for (int j = 0; j < totalHeight; j++)
                {
                    for (int i = 0; i < totalWidth; i++)
                    {
                        pixelValues[index]     = (byte)(((UInt16)(toInt2D[j, i]) & 0xFF00) >> 8);
                        pixelValues[index + 1] = (byte)(((UInt16)(toInt2D[j, i]) & 0x00FF));
                        index += 2;
                        //toInt[ind] = (uint)toInt2D[j, i];
                        //Color pixelColor = imageFinal.GetPixel(j, i);

                        //Color newColor = Color.FromArgb(toInt2D[j, i]);
                        //imageFinal.SetPixel(j, i, (Color)toInt2D[j,i]);

                        //Console.WriteLine(toInt2D[j, i]);
                    }
                }

                newPixelVal = Convert16BitGrayScaleToRgb48(pixelValues, totalWidth, totalHeight);
                Bitmap    imag       = new Bitmap(totalWidth, totalHeight, System.Drawing.Imaging.PixelFormat.Format48bppRgb);
                Rectangle dimension1 = new Rectangle(0, 0, imag.Width, img.Height);
                System.Drawing.Imaging.BitmapData imgData = imag.LockBits(dimension1, System.Drawing.Imaging.ImageLockMode.ReadWrite, imag.PixelFormat);
                IntPtr pixelStartAddress1 = imgData.Scan0;
                System.Runtime.InteropServices.Marshal.Copy(newPixelVal, 0, pixelStartAddress1, newPixelVal.Length);
                imag.UnlockBits(picData);

                imag.Save(@"F:\pablito\downloads\bmp_manip\finall2.bmp");
            }
        }
Esempio n. 58
0
        private Bitmap CreateBmpByGrays(Apicturegrayinformation[] ApicturegrayinformationArray, int index, int PictureWidth, int PictureHeight, PictureOpticflowDataResultStruct[] PictureOpticflowDataResultArray)
        {
            Bitmap bit = new Bitmap(PictureWidth, PictureHeight, System.Drawing.Imaging.PixelFormat.Format8bppIndexed);

            //可读写的方式锁定全部容器
            System.Drawing.Imaging.BitmapData data2 = bit.LockBits(new Rectangle(0, 0, bit.Width, bit.Height), System.Drawing.Imaging.ImageLockMode.ReadWrite, bit.PixelFormat);
            //得到首地址
            IntPtr ptr2 = data2.Scan0;
            //计算24位图像的字节数
            int bytes = PictureWidth * PictureHeight;

            //定义位图数组
            byte[] grayValues = new byte[bytes];
            //复制被锁定的图像到该数组
            System.Runtime.InteropServices.Marshal.Copy(ptr2, grayValues, 0, bytes);
            float tmp;

            for (int i = 0; i < bytes; i++)
            {
                if (biaodingDsp == true)     // 显示模板数据
                {
                    tmp = (byte)ApicturegrayinformationArray[i].OrigingrayValue;
                }
                else
                {
                    tmp = 0;
                }

                if (graydeltaAdd == true)     // 灰度差叠加
                {
                    if (forwardAdd == true)   // 正向叠加
                    {
                        tmp += PictureOpticflowDataResultArray[index].OpticflowResultFOfPixelArray[i].Greyvalue * FactorOfGreygrad;
                    }
                    else
                    {
                        tmp -= PictureOpticflowDataResultArray[index].OpticflowResultFOfPixelArray[i].Greyvalue * FactorOfGreygrad;
                    }
                }
                if (tmp > 255)
                {
                    grayValues[i] = 255;
                }
                if (tmp < 0)
                {
                    grayValues[i] = 0;
                }
                if ((tmp >= 0) & (tmp <= 255))
                {
                    grayValues[i] = (byte)tmp;
                }
            }     //送回数组
            System.Runtime.InteropServices.Marshal.Copy(grayValues, 0, ptr2, bytes);

            //解锁
            bit.UnlockBits(data2);

            ColorPalette tempPalette;

            using (Bitmap tempBmp = new Bitmap(1, 1, PixelFormat.Format8bppIndexed))
            {
                tempPalette = tempBmp.Palette;
            }
            for (int i = 0; i < 256; i++)
            {
                tempPalette.Entries[i] = Color.FromArgb(i, i, i);
            }

            bit.Palette = tempPalette;

            return(bit);
        }
        private void onCamMonitoring()
        {
            if (Data.Instance.Robot_work_info[strRobotID].robot_status_info.cam2 == null)
            {
                return;
            }

            CamInformation cam = Data.Instance.Robot_work_info[strRobotID].robot_status_info.cam2;

            byte[] bytecam = Convert.FromBase64String(cam.msg.data);
            int    height  = cam.msg.height;
            int    width   = cam.msg.width;

            nSourceMapWidth  = width;
            nSourceMapHeight = height;

            sourceMapValues = new byte[width * height * 3];

            for (var y = 0; y < width * height * 3; y++)
            {
                sourceMapValues[y] = bytecam[y];
            }

            string startPath = Application.StartupPath;
            string path      = string.Empty;

            path = startPath + @"\mapinfo.bmp";

            try
            {
                Bitmap bmSource2 = new Bitmap(width, height, PixelFormat.Format24bppRgb);

                Rectangle rect2 = new Rectangle(0, 0, bmSource2.Width, bmSource2.Height);
                System.Drawing.Imaging.BitmapData bmpData2 =
                    bmSource2.LockBits(rect2, System.Drawing.Imaging.ImageLockMode.ReadWrite,
                                       bmSource2.PixelFormat);

                IntPtr ptr = bmpData2.Scan0;

                {
                    System.Runtime.InteropServices.Marshal.Copy(sourceMapValues, 0, ptr, width * height * 3);
                }

                bmSource2.UnlockBits(bmpData2);

                System.Drawing.Rectangle cropArea = new System.Drawing.Rectangle(0, 0, width, height);
                Bitmap bmpTemp = bmSource2.Clone(cropArea, bmSource2.PixelFormat);

                pictureBox1.Image = bmpTemp;

                bmSource2.Dispose();
                bmSource2 = null;
                bmSource2 = (Bitmap)(bmpTemp.Clone());

                // bmSource2.Save(path, ImageFormat.Bmp);
            }
            catch (Exception ex)
            {
                Console.Out.WriteLine("onCamMonitoring err :={0}", ex.Message.ToString());
            }
        }
Esempio n. 60
0
        /// <summary>
        /// 灰度图转伪彩色图像函数(通过查表的方法)
        /// </summary>
        /// <param name="src"></param>
        /// <param name="type">转换类型(1.使用铁红  2.使用彩虹)</param>
        /// <returns></returns>
        private static Bitmap PGrayToPseudoColor2(Bitmap src, int type)
        {
            try
            {
                if (type == 1)
                {
                    Bitmap    a    = new Bitmap(src);
                    Rectangle rect = new Rectangle(0, 0, a.Width, a.Height);
                    System.Drawing.Imaging.BitmapData bmpData = a.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                    int stride = bmpData.Stride;
                    unsafe
                    {
                        byte *pIn = (byte *)bmpData.Scan0.ToPointer();
                        int   temp;
                        byte  R, G, B;

                        for (int y = 0; y < a.Height; y++)
                        {
                            for (int x = 0; x < a.Width; x++)
                            {
                                temp = pIn[0] / 2;

                                R = ironTable[temp, 0];
                                G = ironTable[temp, 1];
                                B = ironTable[temp, 2];

                                pIn[0] = B;
                                pIn[1] = G;
                                pIn[2] = R;

                                pIn += 3;
                            }
                            pIn += stride - a.Width * 3;
                        }
                    }
                    a.UnlockBits(bmpData);
                    return(a);
                }
                else if (type == 2)
                {
                    Bitmap    a    = new Bitmap(src);
                    Rectangle rect = new Rectangle(0, 0, a.Width, a.Height);
                    System.Drawing.Imaging.BitmapData bmpData = a.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                    int stride = bmpData.Stride;
                    unsafe
                    {
                        byte *pIn = (byte *)bmpData.Scan0.ToPointer();
                        int   temp;
                        byte  R, G, B;

                        for (int y = 0; y < a.Height; y++)
                        {
                            for (int x = 0; x < a.Width; x++)
                            {
                                temp = pIn[0] / 2;

                                R = rainTable[temp, 0];
                                G = rainTable[temp, 1];
                                B = rainTable[temp, 2];

                                pIn[0] = B;
                                pIn[1] = G;
                                pIn[2] = R;

                                pIn += 3;
                            }
                            pIn += stride - a.Width * 3;
                        }
                    }
                    a.UnlockBits(bmpData);
                    return(a);
                }
                else
                {
                    throw new Exception("type 参数不合法!");
                }
            }
            catch (Exception e)
            {
                return(null);
            }
        }