public static Bitmap Binarize(Bitmap bm, double threshhold)
        {
            //Binarize
            int size = bm.Width * bm.Height;
            int[] pixels = new int[size];
            bm.GetPixels( pixels, 0, bm.Width, 0, 0, bm.Width, bm.Height );

            // Calculate overall lightness of image
            int c;
            for (int i = 0; i < size; i++)
            {
                c = pixels[i];
                double whiteDist = Math.Sqrt(Math.Pow(0xff - ((c&0x00FF0000 )>>16),2) + Math.Pow(0xff - ((c & 0x0000FF00 )>>8), 2) + Math.Pow(0xff - (c&0x000000FF), 2));
                double blackDist = Math.Sqrt(Math.Pow(0x00 - ((c&0x00FF0000 )>>16),2) + Math.Pow(0x00 - ((c & 0x0000FF00 )>>8), 2) + Math.Pow(0x00 - (c&0x000000FF), 2));
                double distance = blackDist + whiteDist;

                if (whiteDist / distance > threshhold / 30.0) {
                    pixels [i] = Color.Black;
                } else {
                    pixels [i] = Color.White;
                }
            }

            Bitmap newBitmap = bm.Copy (bm.GetConfig (), true);
            newBitmap.SetPixels (pixels, 0, bm.Width, 0, 0, bm.Width, bm.Height);

            return newBitmap;
        }
        public static bool Reshape(ANDROIDBITMAP bmp, ANDROIDBITMAP.Config fmt, int w, int h)
        {
            if (bmp == null)
            {
                throw new ArgumentNullException(nameof(bmp));
            }
            if (fmt == null)
            {
                throw new Diagnostics.PixelFormatNotSupportedException(fmt, nameof(fmt));
            }
            if (w <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(w));
            }
            if (h <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(h));
            }

            if (bmp.Width == w && bmp.Height == h && bmp.GetConfig() == fmt)
            {
                return(false);
            }

            if (!bmp.IsMutable)
            {
                throw new ArgumentException(nameof(bmp));
            }

            bmp.Reconfigure(w, h, fmt);
            return(true);
        }
Exemple #3
0
 /// <summary>
 /// Convert a Bitmap to and from this Mat
 /// </summary>
 /// <param name="mat">The mat to copy Bitmap into</param>
 /// <param name="bitmap">The bitmap to copy into mat</param>
 public static void SetBitmap(this Mat mat, Android.Graphics.Bitmap bitmap)
 {
     Android.Graphics.Bitmap.Config config = bitmap.GetConfig();
     if (config.Equals(Android.Graphics.Bitmap.Config.Argb8888))
     {
         using (BitmapArgb8888Image bi = new BitmapArgb8888Image(bitmap))
         {
             CvInvoke.CvtColor(bi, mat, ColorConversion.Rgba2Bgra);
         }
     }
     else if (config.Equals(Android.Graphics.Bitmap.Config.Rgb565))
     {
         Size  size   = new Size(bitmap.Width, bitmap.Height);
         int[] values = new int[size.Width * size.Height];
         bitmap.GetPixels(values, 0, size.Width, 0, 0, size.Width, size.Height);
         GCHandle handle = GCHandle.Alloc(values, GCHandleType.Pinned);
         using (Mat bgra = new Mat(size, DepthType.Cv8U, 4, handle.AddrOfPinnedObject(), size.Width * 4))
         {
             bgra.CopyTo(mat);
         }
         handle.Free();
     }
     else
     {
         throw new NotImplementedException(String.Format("Coping from Bitmap of {0} is not implemented", config));
     }
 }
		public static Bitmap ToCropped(Bitmap source, double zoomFactor, double xOffset, double yOffset, double cropWidthRatio, double cropHeightRatio)
		{
			double sourceWidth = source.Width;
			double sourceHeight = source.Height;

			double desiredWidth = sourceWidth;
			double desiredHeight = sourceHeight;

			double desiredRatio = cropWidthRatio / cropHeightRatio;
			double currentRatio = sourceWidth / sourceHeight;

			if (currentRatio > desiredRatio)
				desiredWidth = (cropWidthRatio * sourceHeight / cropHeightRatio);
			else if (currentRatio < desiredRatio)
				desiredHeight = (cropHeightRatio * sourceWidth / cropWidthRatio);

			xOffset = xOffset * desiredWidth;
			yOffset = yOffset * desiredHeight;

			desiredWidth =  desiredWidth / zoomFactor;
			desiredHeight = desiredHeight / zoomFactor;

			float cropX = (float)(((sourceWidth - desiredWidth) / 2) + xOffset);
			float cropY = (float)(((sourceHeight - desiredHeight) / 2) + yOffset);

			if (cropX < 0)
				cropX = 0;

			if (cropY < 0)
				cropY = 0;

			if (cropX + desiredWidth > sourceWidth)
				cropX = (float)(sourceWidth - desiredWidth);

			if (cropY + desiredHeight > sourceHeight)
				cropY = (float)(sourceHeight - desiredHeight);

			Bitmap bitmap = Bitmap.CreateBitmap((int)desiredWidth, (int)desiredHeight, source.GetConfig());

			using (Canvas canvas = new Canvas(bitmap))
			using (Paint paint = new Paint())
			using (BitmapShader shader = new BitmapShader(source, Shader.TileMode.Clamp, Shader.TileMode.Clamp))
			using (Matrix matrix = new Matrix())
			{
				if (cropX != 0 || cropY != 0)
				{
					matrix.SetTranslate(-cropX, -cropY);
					shader.SetLocalMatrix(matrix);
				}

				paint.SetShader(shader);
				paint.AntiAlias = false;

				RectF rectF = new RectF(0, 0, (int)desiredWidth, (int)desiredHeight);
				canvas.DrawRect(rectF, paint);

				return bitmap;				
			}
		}
 public static Bitmap ConvertConfig(Bitmap bitmap, Bitmap.Config config)
 {
     if (bitmap.GetConfig().Equals(config))
         return Bitmap.CreateBitmap(bitmap);
     Bitmap convertedBitmap = Bitmap.CreateBitmap(bitmap.Width, bitmap.Height, config);
     Canvas canvas = new Canvas(convertedBitmap);
     Android.Graphics.Paint paint = new Android.Graphics.Paint();
     paint.Color = Android.Graphics.Color.Black;
     canvas.DrawBitmap(bitmap, 0, 0, paint);
     return convertedBitmap;
 }
		public static Bitmap ToColorSpace(Bitmap source, ColorMatrix colorMatrix)
		{
			int width = source.Width;
			int height = source.Height;

			Bitmap bitmap = Bitmap.CreateBitmap(width, height, source.GetConfig());

			using (Canvas canvas = new Canvas(bitmap))
			using (Paint paint = new Paint())
			{
				paint.SetColorFilter(new ColorMatrixColorFilter(colorMatrix));
				canvas.DrawBitmap(source, 0, 0, paint);

				return bitmap;	
			}
		}
Exemple #7
0
        //#region Conversion with Bitmap
        /// <summary>
        /// The Get property provide a more efficient way to convert Image&lt;Gray, Byte&gt;, Image&lt;Bgr, Byte&gt; and Image&lt;Bgra, Byte&gt; into Bitmap
        /// such that the image data is <b>shared</b> with Bitmap.
        /// If you change the pixel value on the Bitmap, you change the pixel values on the Image object as well!
        /// For other types of image this property has the same effect as ToBitmap()
        /// <b>Take extra caution not to use the Bitmap after the Image object is disposed</b>
        /// The Set property convert the bitmap to this Image type.
        /// </summary>
        public static Image <TColor, TDepth> ToImage <TColor, TDepth>(this Bitmap bitmap)
            where TColor : struct, IColor
            where TDepth : new()
        {
            #region reallocate memory if necessary
            Size size = new Size(bitmap.Width, bitmap.Height);
            Image <TColor, TDepth> image = new Image <TColor, TDepth>(size);

            /*
             * if (image.Ptr == IntPtr.Zero)
             * {
             *  image.AllocateData(size.Height, size.Width, image.NumberOfChannels);
             * }
             * else if (!Size.Equals(size))
             * {
             *  image.DisposeObject();
             *  image.AllocateData(size.Height, size.Width, image.NumberOfChannels);
             * }*/
            #endregion

            Android.Graphics.Bitmap.Config config = bitmap.GetConfig();
            if (config.Equals(Android.Graphics.Bitmap.Config.Argb8888))
            {
                using (BitmapArgb8888Image bi = new BitmapArgb8888Image(bitmap))
                {
                    image.ConvertFrom(bi);
                }
            }
            else if (config.Equals(Android.Graphics.Bitmap.Config.Rgb565))
            {
                int[] values = new int[size.Width * size.Height];
                bitmap.GetPixels(values, 0, size.Width, 0, 0, size.Width, size.Height);
                GCHandle handle = GCHandle.Alloc(values, GCHandleType.Pinned);
                using (Image <Bgra, Byte> bgra = new Image <Bgra, byte>(size.Width, size.Height, size.Width * 4, handle.AddrOfPinnedObject()))
                {
                    image.ConvertFrom(bgra);
                }
                handle.Free();
            }
            else
            {
                throw new NotImplementedException(String.Format("Coping from Bitmap of {0} is not implemented", config));
            }

            return(image);
        }
Exemple #8
0
        /// <summary>
        /// Convert the Mat to Bitmap
        /// </summary>
        /// <param name="mat">The Mat to convert to Bitmap</param>
        /// <param name="bitmap">The bitmap, must be of the same size and has bitmap config type of either Argb888 or Rgb565</param>
        /// <returns>The Bitmap</returns>
        public static void ToBitmap(this Mat mat, Android.Graphics.Bitmap bitmap)
        {
            System.Drawing.Size size = mat.Size;
            if (!(size.Width == bitmap.Width && size.Height == bitmap.Height))
            {
                throw new Exception("Bitmap size doesn't match the Mat size");
            }

            Android.Graphics.Bitmap.Config config = bitmap.GetConfig();
            if (config == Android.Graphics.Bitmap.Config.Argb8888)
            {
                int channels = mat.NumberOfChannels;
                using (BitmapArgb8888Image bi = new BitmapArgb8888Image(bitmap))
                {
                    if (channels == 1)
                    {
                        CvInvoke.CvtColor(mat, bi.Mat, ColorConversion.Gray2Rgba);
                    }
                    else if (channels == 3)
                    {
                        CvInvoke.CvtColor(mat, bi, ColorConversion.Bgr2Rgba);
                    }
                    else if (channels == 4)
                    {
                        CvInvoke.CvtColor(mat, bi, ColorConversion.Bgra2Rgba);
                    }
                    else
                    {
                        using (Image <Rgba, Byte> tmp = mat.ToImage <Rgba, Byte>())
                        {
                            tmp.Copy(bi, null);
                        }
                    }
                }
            }
            else if (config == Android.Graphics.Bitmap.Config.Rgb565)
            {
                using (BitmapRgb565Image bi = new BitmapRgb565Image(bitmap))
                    using (Image <Bgr, Byte> tmp = mat.ToImage <Bgr, Byte>())
                        bi.ConvertFrom(tmp);
            }
            else
            {
                throw new NotImplementedException("Only Bitmap config of Argb888 or Rgb565 is supported.");
            }
        }
 private static Bitmap CreateOverlayedBitmap(Bitmap bitmap, int width, int height)
 {
     int[] originalPixels = new int[bitmap.Width * bitmap.Height];
     bitmap.GetPixels(originalPixels, 0, bitmap.Width, 0, 0, bitmap.Width, bitmap.Height);
     int[] pixels = new int[width * height];
     int xStart = (width - bitmap.Width) / 2;
     int xEnd = (width + bitmap.Width) / 2;
     for (int y = 0; y < height; y++)
     {
         int rowStart = y*width;
         int originalRowStart = y*bitmap.Width;
         for (int ox = 0, x = xStart; x < xEnd; x++, ox++)
         {
             pixels[rowStart + x] = originalPixels[originalRowStart + ox];
         }
     }
     return Bitmap.CreateBitmap(pixels, width, height, bitmap.GetConfig());
 }
        protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            if (resultCode == Result.Ok && requestCode == 1)
            {
                _imageSelected = true;

                Android.Net.Uri selectedImageUri = data.Data;

                _originalBitmap = BitmapFactory.DecodeStream(ContentResolver.OpenInputStream(selectedImageUri));

                //Create a new mutable Bitmap from original
                _canvasBitmap = Bitmap.CreateBitmap(_originalBitmap.Width, _originalBitmap.Height, _originalBitmap.GetConfig());

                //Initialize the canvas assigning the mutable Bitmap to it
                _canvas = new Canvas(_canvasBitmap);

                SetBitmapToImageViewer();
            }
        }
Exemple #11
0
        public static Bitmap Blur(Context context, Bitmap input)
        {
            try {
                var rsScript = RenderScript.Create (context);
                var alloc = Allocation.CreateFromBitmap (rsScript, input);
                var blur = ScriptIntrinsicBlur.Create (rsScript, alloc.Element);
                blur.SetRadius (25);
                blur.SetInput (alloc);

                var result = Bitmap.CreateBitmap (input.Width, input.Height, input.GetConfig ());
                var outAlloc = Allocation.CreateFromBitmap (rsScript, result);
                blur.ForEach (outAlloc);

                outAlloc.CopyTo (result);
                rsScript.Destroy ();
                return result;
            } catch (Exception e) {
                Log.Error ("Blurrer", "Error while trying to blur, fallbacking. " + e.ToString ());
                return Bitmap.CreateBitmap (input);
            }
        }
        public Bitmap Transform(Bitmap source)
        {
            Bitmap result = Bitmap.CreateBitmap(source.Width, source.Height, source.GetConfig());
            Bitmap noise;
            try
            {
                noise = picasso.Load(Resource.Drawable.noise).Get();
            }
            catch (Exception)
            {
                throw new Exception("Failed to apply transformation! Missing resource.");
            }

            BitmapShader shader = new BitmapShader(noise, Shader.TileMode.Repeat, Shader.TileMode.Repeat);

            ColorMatrix colorMatrix = new ColorMatrix();
            colorMatrix.SetSaturation(0);
            ColorMatrixColorFilter filter = new ColorMatrixColorFilter(colorMatrix);

            Paint paint = new Paint(PaintFlags.AntiAlias);
            paint.SetColorFilter(filter);

            Canvas canvas = new Canvas(result);
            canvas.DrawBitmap(source, 0, 0, paint);

            paint.SetColorFilter(null);
            paint.SetShader(shader);
            paint.SetXfermode(new PorterDuffXfermode(PorterDuff.Mode.Multiply));

            canvas.DrawRect(0, 0, canvas.Width, canvas.Height, paint);

            source.Recycle();
            noise.Recycle();

            return result;
        }
		public static Bitmap ToColorSpace(Bitmap source, ColorMatrix colorMatrix)
		{
			var config = source.GetConfig();
            		if (config == null)
                		config = Bitmap.Config.Argb8888;    // This will support transparency
			
			int width = source.Width;
			int height = source.Height;

			Bitmap bitmap = Bitmap.CreateBitmap(width, height, config);

			using (Canvas canvas = new Canvas(bitmap))
			using (Paint paint = new Paint())
			{
				paint.SetColorFilter(new ColorMatrixColorFilter(colorMatrix));
				canvas.DrawBitmap(source, 0, 0, paint);

				return bitmap;	
			}
		}
        private static Bitmap ChangeColor(Bitmap bitmap, Color fromColor, Color targetColor, float tolerance = 20)
        {
            int width = bitmap.Width;
            int height = bitmap.Height;
            int[] pixels = new int[width * height];

            float[] redRange = new float[2]{
                (float)Math.Max(fromColor.R - (tolerance / 2), 0.0),
                (float)Math.Min(fromColor.R + (tolerance / 2), 255.0)};

            float[] greenRange = new float[2]{
                (float)Math.Max(fromColor.G - (tolerance / 2), 0.0),
                (float)Math.Min(fromColor.G + (tolerance / 2), 255.0)};

            float[] blueRange = new float[2]{
                (float)Math.Max(fromColor.B - (tolerance / 2), 0.0),
                (float)Math.Min(fromColor.B + (tolerance / 2), 255.0)};

            bitmap.GetPixels(pixels, 0, width, 0, 0, width, height);

            for (int i = 0; i < pixels.Length; i++)
            {

                if (pixels[i] == fromColor)
                {
                    pixels[i] = new Color(targetColor.R, targetColor.G, targetColor.B, targetColor.A - 1);
                }

                int red = Color.GetRedComponent(pixels[i]);
                int green = Color.GetGreenComponent(pixels[i]);
                int blue = Color.GetBlueComponent(pixels[i]);
                int alpha = Color.GetAlphaComponent(pixels[i]);

                if (((red >= redRange[0]) && (red <= redRange[1])) &&
                    ((green >= greenRange[0]) && (green <= greenRange[1])) &&
                    ((blue >= blueRange[0]) && (blue <= blueRange[1])) &&
                    ((alpha > 0 && alpha < 254)))
                {
                    pixels[i] = new Color(targetColor.R, targetColor.G, targetColor.B, targetColor.A - 1);
                }
            }

            if (bitmap.IsMutable)
            {
                bitmap.SetPixels(pixels, 0, width, 0, 0, width, height);
                return bitmap;
            }
            else
            {
                var mutableBitmap = bitmap.Copy(bitmap.GetConfig(), true);
                mutableBitmap.SetPixels(pixels, 0, width, 0, 0, width, height);
                return mutableBitmap;
            }
        }
		// Source: http://incubator.quasimondo.com/processing/superfast_blur.php
		public static Bitmap ToLegacyBlurred(Bitmap source, Context context, int radius)
		{
			Bitmap img = source.Copy(source.GetConfig(), true);

			int w = img.Width;
			int h = img.Height;
			int wm = w-1;
			int hm = h-1;
			int wh = w*h;
			int div = radius+radius+1;
			int[] r = new int[wh];
			int[] g = new int[wh];
			int[] b = new int[wh];
			int rsum,gsum,bsum,x,y,i,p,p1,p2,yp,yi,yw;
			int[] vmin = new int[Math.Max(w,h)];
			int[] vmax = new int[Math.Max(w,h)];
			int[] pix= new int[w*h];

			img.GetPixels(pix, 0, w, 0,0,w, h);

			int[] dv = new int[256*div];
			for (i=0;i<256*div;i++){
				dv[i]=(i/div);
			}

			yw=yi=0;

			for (y=0;y<h;y++){
				rsum=gsum=bsum=0;
				for(i=-radius;i<=radius;i++){
					p=pix[yi+Math.Min(wm,Math.Max(i,0))];
					rsum+=(p & 0xff0000)>>16;
					gsum+=(p & 0x00ff00)>>8;
					bsum+= p & 0x0000ff;
				}
				for (x=0;x<w;x++){

					r[yi]=dv[rsum];
					g[yi]=dv[gsum];
					b[yi]=dv[bsum];

					if(y==0){
						vmin[x]=Math.Min(x+radius+1,wm);
						vmax[x]=Math.Max(x-radius,0);
					}
					p1=pix[yw+vmin[x]];
					p2=pix[yw+vmax[x]];

					rsum+=((p1 & 0xff0000)-(p2 & 0xff0000))>>16;
					gsum+=((p1 & 0x00ff00)-(p2 & 0x00ff00))>>8;
					bsum+= (p1 & 0x0000ff)-(p2 & 0x0000ff);
					yi++;
				}
				yw+=w;
			}

			for (x=0;x<w;x++){
				rsum=gsum=bsum=0;
				yp=-radius*w;
				for(i=-radius;i<=radius;i++){
					yi=Math.Max(0,yp)+x;
					rsum+=r[yi];
					gsum+=g[yi];
					bsum+=b[yi];
					yp+=w;
				}
				yi=x;
				for (y=0;y<h;y++){
					// Preserve alpha channel: ( 0xff000000 & pix[yi] )
					pix[yi] = (int)((0xff000000 & pix[yi]) | (dv[rsum] << 16) | (dv[gsum] << 8) | dv[bsum]);
					if(x==0){
						vmin[y]=Math.Min(y+radius+1,hm)*w;
						vmax[y]=Math.Max(y-radius,0)*w;
					}
					p1=x+vmin[y];
					p2=x+vmax[y];

					rsum+=r[p1]-r[p2];
					gsum+=g[p1]-g[p2];
					bsum+=b[p1]-b[p2];

					yi+=w;
				}
			}

			img.SetPixels(pix,0, w,0,0,w,h);
			return img;
		}
        public static bool Reshape(ref ANDROIDBITMAP bmp, BitmapInfo info, ANDROIDBITMAP.Config defFmt)
        {
            var bmpCfg = ToAndroidBitmapConfig(info.PixelFormat, bmp != null ? bmp.GetConfig() : defFmt);

            return(Reshape(ref bmp, bmpCfg, info.Width, info.Height));
        }
        public static Bitmap changeBitmapContrastBrightness (Bitmap bmp, float contrast, float brightness)
        {
            ColorMatrix cm = new ColorMatrix (new float[] {
                contrast, 0, 0, 0, brightness,
                0, contrast, 0, 0, brightness,
                0, 0, contrast, 0, brightness,
                0, 0, 0, 1, 0
            });
            cm.SetSaturation (0);

            Bitmap ret = Bitmap.CreateBitmap (bmp.Width, bmp.Height, bmp.GetConfig ());

            Canvas canvas = new Canvas (ret);

            Paint paint = new Paint ();
            paint.SetColorFilter (new ColorMatrixColorFilter (cm));
            canvas.DrawBitmap (bmp, 0, 0, paint);

            return ret;
        }
        private Bitmap CreateBlurredImage(Bitmap inputBitmap)
        {
            try
            {
                var rs = RenderScript.Create(m_Context);
                var theInstrinsic = ScriptIntrinsicBlur.Create(rs, Element.U8_4(rs));

                var outputBitmap = Bitmap.CreateBitmap(inputBitmap.Width, inputBitmap.Height, inputBitmap.GetConfig());

                var tmpIn = Allocation.CreateFromBitmap(rs, inputBitmap);
                var tmpOut = Allocation.CreateFromBitmap(rs, outputBitmap);

                theInstrinsic.SetRadius(m_BlurRadius);
                theInstrinsic.SetInput(tmpIn);
                theInstrinsic.ForEach(tmpOut);

                tmpOut.CopyTo(outputBitmap);
                rs.Destroy();
                return outputBitmap;
            }
            catch (Exception)
            {
            }

            return null;
        }