public static Bitmap ScaleUpBitmap(Bitmap originalImage, int wantedWidth, int wantedHeight) { Bitmap output = Bitmap.CreateBitmap(wantedWidth, wantedHeight, Bitmap.Config.Argb8888); Canvas canvas = new Canvas(output); Matrix m = new Matrix(); m.SetScale((float)wantedWidth / originalImage.Width, (float)wantedHeight / originalImage.Height); canvas.DrawBitmap(originalImage, m, new Paint()); canvas.Dispose (); originalImage.Dispose (); return output; }
public override void Draw(ACanvas canvas) { int width = Bounds.Width(); int height = Bounds.Height(); if (width <= 0 || height <= 0) { if (_normalBitmap != null) { _normalBitmap.Dispose(); _normalBitmap = null; } return; } if (_normalBitmap == null || _normalBitmap.Height != height || _normalBitmap.Width != width) { // If the user changes the orientation of the screen, make sure to destroy reference before // reassigning a new bitmap reference. if (_normalBitmap != null) { _normalBitmap.Dispose(); _normalBitmap = null; } _normalBitmap = CreateBitmap(false, width, height); } Android.Graphics.Bitmap bitmap = _normalBitmap; using (var paint = new Paint()) { canvas.DrawBitmap(bitmap, 0, 0, paint); } }
private byte[] CropImage(byte[] screenshotBytes, int top) { Android.Graphics.Bitmap bitmap = Android.Graphics.BitmapFactory.DecodeByteArray( screenshotBytes, 0, screenshotBytes.Length); // int viewStartY = (int)(top * 2.8f); // int viewHeight = (int)(bitmap.Height - (top * 2.8f)); //// var navBarXY = 20; // int viewHeightMinusNavBar = viewHeight - 20; int height = bitmap.Height - 120; height = height - 120; Android.Graphics.Bitmap crop = Android.Graphics.Bitmap.CreateBitmap(bitmap, 0, 120, bitmap.Width, height); //Android.Graphics.Bitmap crop = Android.Graphics.Bitmap.CreateBitmap(bitmap, // 0, 120, // bitmap.Width, bitmap.Height-140 // ); bitmap.Dispose(); using MemoryStream stream = new MemoryStream(); crop.Compress(Android.Graphics.Bitmap.CompressFormat.Jpeg, 100, stream); return(stream.ToArray()); }
public static String BitmapToBase64String(Bitmap originalImage) { MemoryStream ms = new MemoryStream(); originalImage.Compress(Bitmap.CompressFormat.Png, 100, ms); byte[] imageData = ms.ToArray(); originalImage.Dispose(); return Base64.EncodeToString(imageData, Base64Flags.NoWrap); }
public override void Dispose() { if (ABitmap != null) { ABitmap.Dispose(); ABitmap = null; } }
private Android.Graphics.Bitmap rotateMyBitmap(Android.Graphics.Bitmap bmp) { //*****旋转一下 Android.Graphics.Matrix matrix = new Android.Graphics.Matrix(); matrix.PostRotate(270); Android.Graphics.Bitmap nbmp2 = Android.Graphics.Bitmap.CreateBitmap(bmp, 0, 0, bmp.Width, bmp.Height, matrix, true); bmp.Dispose(); return(nbmp2); }
private static void DisposeBitmap(Bitmap bitmap) { if (bitmap != null) { if (!bitmap.IsRecycled) { bitmap.Recycle(); } bitmap.Dispose(); } }
private MemoryStream RenderToBitmapStreamPrivate(IViewport viewport, IEnumerable <ILayer> layers) { Bitmap target = Bitmap.CreateBitmap((int)viewport.Width, (int)viewport.Height, Bitmap.Config.Argb8888); var canvas = new Canvas(target); Render(canvas, viewport, layers, ShowDebugInfoInMap); var stream = new MemoryStream(); target.Compress(Bitmap.CompressFormat.Png, 100, stream); target.Dispose(); canvas.Dispose(); return(stream); }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.POIDetail); _nameEditText = FindViewById <EditText>(Resource.Id.nameEditText); _descrEditText = FindViewById <EditText>(Resource.Id.descEditText); _addrEditText = FindViewById <EditText>(Resource.Id.addeditText); _latEditText = FindViewById <EditText>(Resource.Id.latEditText); _longEditText = FindViewById <EditText>(Resource.Id.longEditText); _poiImageView = FindViewById <ImageView>(Resource.Id.poiImageView); _photoImageButton = FindViewById <ImageButton>(Resource.Id.newPictureButton); _locMgr = GetSystemService(Context.LocationService) as LocationManager; _locationImageButton = FindViewById <ImageButton>(Resource.Id.locationImageButton); _locationImageButton.Click += GetLocationClicked; _mapImageButton = FindViewById <ImageButton>(Resource.Id.mapImageButton); _mapImageButton.Click += MapImageClicked; _photoImageButton.Click += NewPhotoClicked; if (Intent.HasExtra("poiId")) { int poiId = Intent.GetIntExtra("poiId", -1); _poi = POIData.Service.GetPOI(poiId); UpdateUI(); } else { _poi = new PointOfInterest(); } if (Intent.HasExtra("poiId")) { int poiId = Intent.GetIntExtra("poiId", -1); _poi = POIData.Service.GetPOI(poiId); Android.Graphics.Bitmap poiImage = POIData.GetImageFile(_poi.Id.Value); _poiImageView.SetImageBitmap(poiImage); if (poiImage != null) { poiImage.Dispose(); } } else { _poi = new PointOfInterest(); } }
public bool ReadFile(String fileName, Mat mat, CvEnum.ImreadModes loadType) { try { int rotation = 0; Android.Media.ExifInterface exif = new Android.Media.ExifInterface(fileName); int orientation = exif.GetAttributeInt(Android.Media.ExifInterface.TagOrientation, int.MinValue); switch (orientation) { case (int)Android.Media.Orientation.Rotate270: rotation = 270; break; case (int)Android.Media.Orientation.Rotate180: rotation = 180; break; case (int)Android.Media.Orientation.Rotate90: rotation = 90; break; } using (Android.Graphics.Bitmap bmp = Android.Graphics.BitmapFactory.DecodeFile(fileName)) { if (rotation == 0) { bmp.ToMat(mat); } else { Android.Graphics.Matrix matrix = new Android.Graphics.Matrix(); matrix.PostRotate(rotation); using (Android.Graphics.Bitmap rotated = Android.Graphics.Bitmap.CreateBitmap(bmp, 0, 0, bmp.Width, bmp.Height, matrix, true)) { //manually disposed sooner such that memory is released. bmp.Dispose(); rotated.ToMat(mat); } } } return(true); } catch (Exception e) { Debug.WriteLine(e); //throw; return(false); } }
private void FreeBitmap() { if (bitmap == null) { return; } // free and recycle the bitmap data if (bitmap.Handle != IntPtr.Zero && !bitmap.IsRecycled) { bitmap.Recycle(); } bitmap.Dispose(); bitmap = null; }
protected override void OnCreate (Bundle bundle) { base.OnCreate (bundle); // Set our view from the "main" layout resource SetContentView (Resource.Layout.Main); Utils.Util.SetDisplayMetrics (Resources.DisplayMetrics); // Get our button from the layout resource, // and attach an event to it Button button = FindViewById<Button> (Resource.Id.btn_draw); ImageView iv = FindViewById<ImageView> (Resource.Id.imageView_output); button.Click += delegate { int width = Utils.Util.DetectScreenSize().Width; int height = Utils.Util.DetectScreenSize().Height; if(b != null) { iv.SetImageBitmap(null); } b = DrawImages.GetImage(width,height); iv.SetImageBitmap (b); b.Dispose(); }; }
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data) { if (requestCode == CAPTURE_PHOTO) { if (resultCode == Result.Ok) { // display saved image Android.Graphics.Bitmap poiImage = POIData.GetImageFile(_poi.Id.Value); _poiImageView.SetImageBitmap(poiImage); if (poiImage != null) { poiImage.Dispose(); } } else // let the user know the photo was cancelled { Toast toast = Toast.MakeText(this, "No picture captured.", ToastLength.Short); toast.Show(); } } else { base.OnActivityResult(requestCode, resultCode, data); } }
/// <summary> /// Read an image file, covert the data and save it to the native pointer /// </summary> /// <typeparam name="T">The type of the data to covert the image pixel values to. e.g. "float" or "byte"</typeparam> /// <param name="fileName">The name of the image file</param> /// <param name="dest">The native pointer where the image pixels values will be saved to.</param> /// <param name="inputHeight">The height of the image, must match the height requirement for the tensor</param> /// <param name="inputWidth">The width of the image, must match the width requirement for the tensor</param> /// <param name="inputMean">The mean value, it will be subtracted from the input image pixel values</param> /// <param name="scale">The scale, after mean is subtracted, the scale will be used to multiply the pixel values</param> /// <param name="flipUpSideDown">If true, the image needs to be flipped up side down</param> /// <param name="swapBR">If true, will flip the Blue channel with the Red. e.g. If false, the tensor's color channel order will be RGB. If true, the tensor's color channle order will be BGR </param> public static void ReadImageFileToTensor <T>( String fileName, IntPtr dest, int inputHeight = -1, int inputWidth = -1, float inputMean = 0.0f, float scale = 1.0f, bool flipUpSideDown = false, bool swapBR = false) where T : struct { if (!File.Exists(fileName)) { throw new FileNotFoundException(String.Format("File {0} do not exist.", fileName)); } Android.Graphics.Bitmap bmp = BitmapFactory.DecodeFile(fileName); if (inputHeight > 0 || inputWidth > 0) { Bitmap resized = Bitmap.CreateScaledBitmap(bmp, inputWidth, inputHeight, false); bmp.Dispose(); bmp = resized; } if (flipUpSideDown) { Matrix matrix = new Matrix(); matrix.PostScale(1, -1, bmp.Width / 2, bmp.Height / 2); Bitmap flipped = Bitmap.CreateBitmap(bmp, 0, 0, bmp.Width, bmp.Height, matrix, true); bmp.Dispose(); bmp = flipped; } int[] intValues = new int[bmp.Width * bmp.Height]; float[] floatValues = new float[bmp.Width * bmp.Height * 3]; bmp.GetPixels(intValues, 0, bmp.Width, 0, 0, bmp.Width, bmp.Height); if (swapBR) { for (int i = 0; i < intValues.Length; ++i) { int val = intValues[i]; floatValues[i * 3 + 0] = ((val & 0xFF) - inputMean) * scale; floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 2] = (((val >> 16) & 0xFF) - inputMean) * scale; } } else { for (int i = 0; i < intValues.Length; ++i) { int val = intValues[i]; floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 2] = ((val & 0xFF) - inputMean) * scale; } } if (typeof(T) == typeof(float)) { Marshal.Copy(floatValues, 0, dest, floatValues.Length); } else if (typeof(T) == typeof(byte)) { //copy float to bytes byte[] byteValues = new byte[floatValues.Length]; for (int i = 0; i < floatValues.Length; i++) { byteValues[i] = (byte)floatValues[i]; } Marshal.Copy(byteValues, 0, dest, byteValues.Length); } else { throw new NotImplementedException(String.Format("Destination data type {0} is not supported.", typeof(T).ToString())); } }
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data) { base.OnActivityResult(requestCode, resultCode, data); try { if (resultCode == Result.Ok) { if (requestCode == 1) { try { Android.Net.Uri selectImage = data.Data; imageUrl1 = getRealPathFromURI(data.Data); imageurlId1 = data.Data.LastPathSegment; datetimedetalle = System.IO.File.GetLastAccessTimeUtc(imageUrl1); string fechahora = datetimedetalle.Day.ToString() + datetimedetalle.Month.ToString() + datetimedetalle.Year.ToString().Substring(2, 2) + "-" + datetimedetalle.Hour.ToString() + datetimedetalle.Minute.ToString(); GC.Collect(); if (System.IO.File.Exists(imageUrl1)) { Android.Graphics.Bitmap bitmap = Utils.ChangeSizeBitmap(BitmapFactory.DecodeFile(imageUrl1), 1600, 1200); using (MemoryStream stream = new MemoryStream()) { bitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Jpeg, 100, stream); bitmapDetalle = stream.ToArray(); stream.Flush(); stream.Close(); } bitmap.Dispose(); if (bitmapDetalle == null) { Toast.MakeText(ApplicationContext, "No se cargó la fotografía correctamente, favor de seleccionarla de nuevo", ToastLength.Long).Show(); return; } else { lblFotoDetalle.Text = ODTDet.Folio + " - Detalle - " + fechahora + ".jpg"; } } } catch (Exception exc) { Toast.MakeText(ApplicationContext, "No se cargó la fotografía correctamente, favor de seleccionarla de nuevo", ToastLength.Long).Show(); return; } } else if (requestCode == 2) { try { Android.Net.Uri selectImage = data.Data; imageUrl2 = getRealPathFromURI(data.Data); imageurlId2 = data.Data.LastPathSegment; datetimemediana = System.IO.File.GetLastAccessTimeUtc(imageUrl2); string fechahora = datetimemediana.Day.ToString() + datetimemediana.Month.ToString() + datetimemediana.Year.ToString().Substring(2, 2) + "-" + datetimemediana.Hour.ToString() + datetimemediana.Minute.ToString(); GC.Collect(); if (System.IO.File.Exists(imageUrl2)) { Android.Graphics.Bitmap bitmap = Utils.ChangeSizeBitmap(BitmapFactory.DecodeFile(imageUrl2), 1600, 1200); using (MemoryStream stream = new MemoryStream()) { bitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Jpeg, 100, stream); bitmapMediana = stream.ToArray(); stream.Flush(); stream.Close(); } bitmap.Dispose(); if (bitmapMediana == null) { Toast.MakeText(ApplicationContext, "No se cargó la fotografía correctamente, favor de seleccionarla de nuevo", ToastLength.Long).Show(); return; } else { lblFotoMediana.Text = ODTDet.Folio + " - Mediana - " + fechahora + ".jpg"; } } } catch (Exception exc) { Toast.MakeText(ApplicationContext, "No se cargó la fotografía correctamente, favor de seleccionarla de nuevo", ToastLength.Long).Show(); return; } } else if (requestCode == 3) { try { Android.Net.Uri selectImage = data.Data; imageUrl3 = getRealPathFromURI(data.Data); imageurlId3 = data.Data.LastPathSegment; datetimelarga = System.IO.File.GetLastAccessTimeUtc(imageUrl3); string fechahora = datetimelarga.Day.ToString() + datetimelarga.Month.ToString() + datetimelarga.Year.ToString().Substring(2, 2) + "-" + datetimelarga.Hour.ToString() + datetimelarga.Minute.ToString(); GC.Collect(); if (System.IO.File.Exists(imageUrl3)) { Android.Graphics.Bitmap bitmap = Utils.ChangeSizeBitmap(BitmapFactory.DecodeFile(imageUrl3), 1600, 1200); using (MemoryStream stream = new MemoryStream()) { bitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Jpeg, 100, stream); bitmapLarga = stream.ToArray(); stream.Flush(); stream.Close(); } bitmap.Dispose(); if (bitmapLarga == null) { Toast.MakeText(ApplicationContext, "No se cargó la fotografía correctamente, favor de seleccionarla de nuevo", ToastLength.Long).Show(); return; } else { lblFotoLarga.Text = ODTDet.Folio + " - Larga - " + fechahora + ".jpg"; } } } catch (Exception exc) { Toast.MakeText(ApplicationContext, "No se cargó la fotografía correctamente, favor de seleccionarla de nuevo", ToastLength.Long).Show(); return; } } else if (requestCode == 4) //extSdCard { try{ if (App._file.Exists()) { if (Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Kitkat) { Intent mediaScanIntent = new Intent( Intent.ActionMediaScannerScanFile); var contentUri = Android.Net.Uri.FromFile(App._file); mediaScanIntent.SetData(contentUri); this.SendBroadcast(mediaScanIntent); } else { //SendBroadcast(new Intent(Intent.ActionMediaMounted, MediaStore.Images.Thumbnails.ExternalContentUri)); SendBroadcast(new Intent(Intent.ActionMediaMounted, Android.Net.Uri.Parse("file://" + Android.OS.Environment.ExternalStorageDirectory))); } } //GC.Collect (); }catch (Exception ex) { var toast = Toast.MakeText(ApplicationContext, ex.Message, ToastLength.Long); toast.Show(); } } } }catch (Exception ex) { var toast = Toast.MakeText(ApplicationContext, ex.Message, ToastLength.Long); toast.Show(); } }
static Drawable GetResized(Bitmap b, Android.Content.Res.Resources res) { double width = (double)b.Width; double height = (double)b.Height; if (width <= MaxWidth && height <= MaxHeight) return new BitmapDrawable(res, b); if (width > height) { height = height / width * MaxWidth; width = MaxWidth; } else if (height > width) { width = width / height * MaxHeight; height = MaxHeight; } else { width = MaxWidth; height = MaxHeight; } var resized = Bitmap.CreateScaledBitmap(b, (int)width, (int)height, false); b.Dispose(); return new BitmapDrawable(res, resized); }
private void DismissBitmap(Bitmap bitmap) { if (bitmap != null) { bitmap.Recycle(); bitmap.Dispose(); GC.Collect(); } }
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data) { base.OnActivityResult(requestCode, resultCode, data); if (resultCode == Result.Ok) { if (requestCode == 2) { try { Android.Net.Uri selectImage = data.Data; bitmapDetalle = null; imageurl = getRealPathFromURI(data.Data); imageurlId = data.Data.LastPathSegment; datetime = System.IO.File.GetLastAccessTimeUtc(imageurl); string fechahora = datetime.Day.ToString() + datetime.Month.ToString() + datetime.Year.ToString().Substring(2, 2) + "-" + datetime.Hour.ToString() + datetime.Minute.ToString(); GC.Collect(); if (File.Exists(imageurl)) { Android.Graphics.Bitmap bitmap = Utils.ChangeSizeBitmap(BitmapFactory.DecodeFile(imageurl), 1600, 1200); using (MemoryStream stream = new MemoryStream()) { bitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Jpeg, 100, stream); bitmapDetalle = stream.ToArray(); stream.Flush(); stream.Close(); } bitmap.Dispose(); if (bitmapDetalle == null) { Toast.MakeText(ApplicationContext, "No se cargó la fotografía correctamente, favor de seleccionarla de nuevo", ToastLength.Long).Show(); return; } else { lblInfoFoto.Text = ODTDet.Folio + " - Evidencia - " + fechahora + ".jpg"; } } } catch (Exception exc) { Toast.MakeText(ApplicationContext, "No se cargó la fotografía correctamente, favor de seleccionarla de nuevo", ToastLength.Long).Show(); return; } } else if (requestCode == 4) { if (App._file.Exists()) { Intent mediaScannerIntent = new Intent(Intent.ActionMediaScannerScanFile); Android.Net.Uri contentUri = Android.Net.Uri.FromFile(App._file); mediaScannerIntent.SetData(contentUri); this.SendBroadcast(mediaScannerIntent); GC.Collect(); } } } }
/// <summary> /// Read an image file, covert the data and save it to the native pointer /// </summary> /// <typeparam name="T">The type of the data to covert the image pixel values to. e.g. "float" or "byte"</typeparam> /// <param name="fileName">The name of the image file</param> /// <param name="dest">The native pointer where the image pixels values will be saved to.</param> /// <param name="inputHeight">The height of the image, must match the height requirement for the tensor</param> /// <param name="inputWidth">The width of the image, must match the width requirement for the tensor</param> /// <param name="inputMean">The mean value, it will be substracted from the input image pixel values</param> /// <param name="scale">The scale, after mean is substracted, the scale will be used to multiply the pixel values</param> /// <param name="flipUpSideDown">If true, the image needs to be flipped up side down</param> /// <param name="swapBR">If true, will flip the Blue channel with the Red. e.g. If false, the tensor's color channel order will be RGB. If true, the tensor's color channle order will be BGR </param> public static void ReadImageFileToTensor <T>( String fileName, IntPtr dest, int inputHeight = -1, int inputWidth = -1, float inputMean = 0.0f, float scale = 1.0f, bool flipUpSideDown = false, bool swapBR = false) where T : struct { if (!File.Exists(fileName)) { throw new FileNotFoundException(String.Format("File {0} do not exist.", fileName)); } #if __ANDROID__ Android.Graphics.Bitmap bmp = BitmapFactory.DecodeFile(fileName); if (inputHeight > 0 || inputWidth > 0) { Bitmap resized = Bitmap.CreateScaledBitmap(bmp, inputWidth, inputHeight, false); bmp.Dispose(); bmp = resized; } if (flipUpSideDown) { Matrix matrix = new Matrix(); matrix.PostScale(1, -1, bmp.Width / 2, bmp.Height / 2); Bitmap flipped = Bitmap.CreateBitmap(bmp, 0, 0, bmp.Width, bmp.Height, matrix, true); bmp.Dispose(); bmp = flipped; } int[] intValues = new int[bmp.Width * bmp.Height]; float[] floatValues = new float[bmp.Width * bmp.Height * 3]; bmp.GetPixels(intValues, 0, bmp.Width, 0, 0, bmp.Width, bmp.Height); if (swapBR) { for (int i = 0; i < intValues.Length; ++i) { int val = intValues[i]; floatValues[i * 3 + 0] = ((val & 0xFF) - inputMean) * scale; floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 2] = (((val >> 16) & 0xFF) - inputMean) * scale; } } else { for (int i = 0; i < intValues.Length; ++i) { int val = intValues[i]; floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 2] = ((val & 0xFF) - inputMean) * scale; } } if (typeof(T) == typeof(float)) { Marshal.Copy(floatValues, 0, dest, floatValues.Length); } else if (typeof(T) == typeof(byte)) { //copy float to bytes byte[] byteValues = new byte[floatValues.Length]; for (int i = 0; i < floatValues.Length; i++) { byteValues[i] = (byte)floatValues[i]; } Marshal.Copy(byteValues, 0, dest, byteValues.Length); } else { throw new NotImplementedException(String.Format("Destination data type {0} is not supported.", typeof(T).ToString())); } #elif __IOS__ if (flipUpSideDown) { throw new NotImplementedException("Flip Up Side Down is Not implemented"); } UIImage image = new UIImage(fileName); if (inputHeight > 0 || inputWidth > 0) { UIImage resized = image.Scale(new CGSize(inputWidth, inputHeight)); image.Dispose(); image = resized; } int[] intValues = new int[(int)(image.Size.Width * image.Size.Height)]; float[] floatValues = new float[(int)(image.Size.Width * image.Size.Height * 3)]; System.Runtime.InteropServices.GCHandle handle = System.Runtime.InteropServices.GCHandle.Alloc(intValues, System.Runtime.InteropServices.GCHandleType.Pinned); using (CGImage cgimage = image.CGImage) using (CGColorSpace cspace = CGColorSpace.CreateDeviceRGB()) using (CGBitmapContext context = new CGBitmapContext( handle.AddrOfPinnedObject(), (nint)image.Size.Width, (nint)image.Size.Height, 8, (nint)image.Size.Width * 4, cspace, CGImageAlphaInfo.PremultipliedLast )) { context.DrawImage(new CGRect(new CGPoint(), image.Size), cgimage); } handle.Free(); if (swapBR) { for (int i = 0; i < intValues.Length; ++i) { int val = intValues[i]; floatValues[i * 3 + 0] = ((val & 0xFF) - inputMean) * scale; floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 2] = (((val >> 16) & 0xFF) - inputMean) * scale; } } else { for (int i = 0; i < intValues.Length; ++i) { int val = intValues[i]; floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 2] = ((val & 0xFF) - inputMean) * scale; } } if (typeof(T) == typeof(float)) { Marshal.Copy(floatValues, 0, dest, floatValues.Length); } else if (typeof(T) == typeof(byte)) { //copy float to bytes byte[] byteValues = new byte[floatValues.Length]; for (int i = 0; i < floatValues.Length; i++) { byteValues[i] = (byte)floatValues[i]; } Marshal.Copy(byteValues, 0, dest, byteValues.Length); } else { throw new NotImplementedException(String.Format("Destination data type {0} is not supported.", typeof(T).ToString())); } //System.Runtime.InteropServices.Marshal.Copy(floatValues, 0, dest, floatValues.Length); #elif __UNIFIED__ if (flipUpSideDown) { throw new NotImplementedException("Flip Up Side Down is Not implemented"); } //if (swapBR) // throw new NotImplementedException("swapBR is Not implemented"); NSImage image = new NSImage(fileName); if (inputHeight > 0 || inputWidth > 0) { NSImage resized = new NSImage(new CGSize(inputWidth, inputHeight)); resized.LockFocus(); image.DrawInRect(new CGRect(0, 0, inputWidth, inputHeight), CGRect.Empty, NSCompositingOperation.SourceOver, 1.0f); resized.UnlockFocus(); image.Dispose(); image = resized; } int[] intValues = new int[(int)(image.Size.Width * image.Size.Height)]; float[] floatValues = new float[(int)(image.Size.Width * image.Size.Height * 3)]; System.Runtime.InteropServices.GCHandle handle = System.Runtime.InteropServices.GCHandle.Alloc(intValues, System.Runtime.InteropServices.GCHandleType.Pinned); using (CGImage cgimage = image.CGImage) using (CGColorSpace cspace = CGColorSpace.CreateDeviceRGB()) using (CGBitmapContext context = new CGBitmapContext( handle.AddrOfPinnedObject(), (nint)image.Size.Width, (nint)image.Size.Height, 8, (nint)image.Size.Width * 4, cspace, CGImageAlphaInfo.PremultipliedLast )) { context.DrawImage(new CGRect(new CGPoint(), image.Size), cgimage); } handle.Free(); if (swapBR) { for (int i = 0; i < intValues.Length; ++i) { int val = intValues[i]; floatValues[i * 3 + 0] = ((val & 0xFF) - inputMean) * scale; floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 2] = (((val >> 16) & 0xFF) - inputMean) * scale; } } else { for (int i = 0; i < intValues.Length; ++i) { int val = intValues[i]; floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 2] = ((val & 0xFF) - inputMean) * scale; } } if (typeof(T) == typeof(float)) { Marshal.Copy(floatValues, 0, dest, floatValues.Length); } else if (typeof(T) == typeof(byte)) { //copy float to bytes byte[] byteValues = new byte[floatValues.Length]; for (int i = 0; i < floatValues.Length; i++) { byteValues[i] = (byte)floatValues[i]; } Marshal.Copy(byteValues, 0, dest, byteValues.Length); } else { throw new NotImplementedException(String.Format("Destination data type {0} is not supported.", typeof(T).ToString())); } //System.Runtime.InteropServices.Marshal.Copy(floatValues, 0, dest, floatValues.Length); #elif UNITY_EDITOR || UNITY_IOS || UNITY_ANDROID || UNITY_STANDALONE Texture2D texture = ReadTexture2DFromFile(fileName); ReadTensorFromTexture2D <T>(texture, dest, inputHeight, inputWidth, inputMean, scale, flipUpSideDown, false); #else //if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows)) { //Read the file using Bitmap class System.Drawing.Bitmap bmp = new Bitmap(fileName); if (inputHeight > 0 || inputWidth > 0) { //resize bmp System.Drawing.Bitmap newBmp = new Bitmap(bmp, inputWidth, inputHeight); bmp.Dispose(); bmp = newBmp; //bmp.Save("tmp.png"); } if (flipUpSideDown) { bmp.RotateFlip(RotateFlipType.RotateNoneFlipY); } int bmpWidth = bmp.Width; int bmpHeight = bmp.Height; System.Drawing.Imaging.BitmapData bd = new System.Drawing.Imaging.BitmapData(); bmp.LockBits( new Rectangle(0, 0, bmpWidth, bmpHeight), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format24bppRgb, bd); int stride = bd.Stride; byte[] byteValues = new byte[bmpHeight * stride]; Marshal.Copy(bd.Scan0, byteValues, 0, byteValues.Length); bmp.UnlockBits(bd); if (typeof(T) == typeof(float)) { int imageSize = bmpWidth * bmpHeight; float[] floatValues = new float[imageSize * 3]; if (swapBR) { int idx = 0; int rowOffset = 0; for (int i = 0; i < bmpHeight; ++i) { int rowPtr = rowOffset; for (int j = 0; j < bmpWidth; ++j) { float b = ((float)byteValues[rowPtr++] - inputMean) * scale; float g = ((float)byteValues[rowPtr++] - inputMean) * scale; float r = ((float)byteValues[rowPtr++] - inputMean) * scale; floatValues[idx++] = r; floatValues[idx++] = g; floatValues[idx++] = b; } rowOffset += stride; } } else { int idx = 0; int rowOffset = 0; for (int i = 0; i < bmpHeight; ++i) { int rowPtr = rowOffset; for (int j = 0; j < bmpWidth; ++j) { floatValues[idx++] = ((float)byteValues[rowPtr++] - inputMean) * scale; floatValues[idx++] = ((float)byteValues[rowPtr++] - inputMean) * scale; floatValues[idx++] = ((float)byteValues[rowPtr++] - inputMean) * scale; } rowOffset += stride; } } Marshal.Copy(floatValues, 0, dest, floatValues.Length); } else if (typeof(T) == typeof(byte)) { int imageSize = bmp.Width * bmp.Height; if (swapBR) { int idx = 0; for (int i = 0; i < bmpHeight; ++i) { int offset = i * stride; for (int j = 0; j < bmpWidth; ++j) { byte b = (byte)(((float)byteValues[offset++] - inputMean) * scale); byte g = (byte)(((float)byteValues[offset++] - inputMean) * scale); byte r = (byte)(((float)byteValues[offset++] - inputMean) * scale); byteValues[idx++] = r; byteValues[idx++] = g; byteValues[idx++] = b; } } } else { int idx = 0; for (int i = 0; i < bmpHeight; ++i) { int offset = i * stride; for (int j = 0; j < bmpWidth * 3; ++j) { byteValues[idx++] = (byte)(((float)byteValues[offset++] - inputMean) * scale); } } } Marshal.Copy(byteValues, 0, dest, imageSize * 3); } else { throw new NotImplementedException(String.Format("Destination data type {0} is not supported.", typeof(T).ToString())); } } /* * else //Unix * { * //if (flipUpSideDown) * // throw new NotImplementedException("Flip Up Side Down is Not implemented"); * * throw new NotImplementedException("Not implemented"); * }*/ #endif }
public static void ReadImageFileToTensor(String fileName, IntPtr dest, int inputHeight = -1, int inputWidth = -1, float inputMean = 0.0f, float scale = 1.0f) { #if __ANDROID__ Android.Graphics.Bitmap bmp = BitmapFactory.DecodeFile(fileName); if (inputHeight > 0 || inputWidth > 0) { Bitmap resized = Bitmap.CreateScaledBitmap(bmp, inputWidth, inputHeight, false); bmp.Dispose(); bmp = resized; } int[] intValues = new int[bmp.Width * bmp.Height]; float[] floatValues = new float[bmp.Width * bmp.Height * 3]; bmp.GetPixels(intValues, 0, bmp.Width, 0, 0, bmp.Width, bmp.Height); for (int i = 0; i < intValues.Length; ++i) { int val = intValues[i]; floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 2] = ((val & 0xFF) - inputMean) * scale; } System.Runtime.InteropServices.Marshal.Copy(floatValues, 0, dest, floatValues.Length); #elif __IOS__ UIImage image = new UIImage(fileName); if (inputHeight > 0 || inputWidth > 0) { UIImage resized = image.Scale(new CGSize(inputWidth, inputHeight)); image.Dispose(); image = resized; } int[] intValues = new int[(int)(image.Size.Width * image.Size.Height)]; float[] floatValues = new float[(int)(image.Size.Width * image.Size.Height * 3)]; System.Runtime.InteropServices.GCHandle handle = System.Runtime.InteropServices.GCHandle.Alloc(intValues, System.Runtime.InteropServices.GCHandleType.Pinned); using (CGImage cgimage = image.CGImage) using (CGColorSpace cspace = CGColorSpace.CreateDeviceRGB()) using (CGBitmapContext context = new CGBitmapContext( handle.AddrOfPinnedObject(), (nint)image.Size.Width, (nint)image.Size.Height, 8, (nint)image.Size.Width * 4, cspace, CGImageAlphaInfo.PremultipliedLast )) { context.DrawImage(new CGRect(new CGPoint(), image.Size), cgimage); } handle.Free(); for (int i = 0; i < intValues.Length; ++i) { int val = intValues[i]; floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 2] = ((val & 0xFF) - inputMean) * scale; } System.Runtime.InteropServices.Marshal.Copy(floatValues, 0, dest, floatValues.Length); #elif __UNIFIED__ NSImage image = new NSImage(fileName); if (inputHeight > 0 || inputWidth > 0) { NSImage resized = new NSImage(new CGSize(inputWidth, inputHeight)); resized.LockFocus(); image.DrawInRect(new CGRect(0, 0, inputWidth, inputHeight), CGRect.Empty, NSCompositingOperation.SourceOver, 1.0f); resized.UnlockFocus(); image.Dispose(); image = resized; } int[] intValues = new int[(int)(image.Size.Width * image.Size.Height)]; float[] floatValues = new float[(int)(image.Size.Width * image.Size.Height * 3)]; System.Runtime.InteropServices.GCHandle handle = System.Runtime.InteropServices.GCHandle.Alloc(intValues, System.Runtime.InteropServices.GCHandleType.Pinned); using (CGImage cgimage = image.CGImage) using (CGColorSpace cspace = CGColorSpace.CreateDeviceRGB()) using (CGBitmapContext context = new CGBitmapContext( handle.AddrOfPinnedObject(), (nint)image.Size.Width, (nint)image.Size.Height, 8, (nint)image.Size.Width * 4, cspace, CGImageAlphaInfo.PremultipliedLast )) { context.DrawImage(new CGRect(new CGPoint(), image.Size), cgimage); } handle.Free(); for (int i = 0; i < intValues.Length; ++i) { int val = intValues[i]; floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 2] = ((val & 0xFF) - inputMean) * scale; } System.Runtime.InteropServices.Marshal.Copy(floatValues, 0, dest, floatValues.Length); #else if (Emgu.TF.Util.Platform.OperationSystem == OS.Windows) { //Do something for Windows System.Drawing.Bitmap bmp = new Bitmap(fileName); if (inputHeight > 0 || inputWidth > 0) { //resize bmp System.Drawing.Bitmap newBmp = new Bitmap(bmp, inputWidth, inputHeight); bmp.Dispose(); bmp = newBmp; //bmp.Save("tmp.png"); } byte[] byteValues = new byte[bmp.Width * bmp.Height * 3]; System.Drawing.Imaging.BitmapData bd = new System.Drawing.Imaging.BitmapData(); bmp.LockBits( new Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format24bppRgb, bd); System.Runtime.InteropServices.Marshal.Copy(bd.Scan0, byteValues, 0, byteValues.Length); bmp.UnlockBits(bd); float[] floatValues = new float[bmp.Width * bmp.Height * 3]; for (int i = 0; i < byteValues.Length; ++i) { floatValues[i] = ((float)byteValues[i] - inputMean) * scale; } System.Runtime.InteropServices.Marshal.Copy(floatValues, 0, dest, floatValues.Length); } else { throw new Exception("Not implemented"); } #endif }
protected override void OnCreate (Bundle bundle) { base.OnCreate (bundle); intensity_arr = new string[256]; hexcijfers = new string[]{"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"}; int j = 0; int k = 0; for(int i = 0; i < 256;i++) { intensity_arr [i] += hexcijfers [j]; intensity_arr [i] += hexcijfers [k]; k++; if (k == 16) { k = 0; j++; } } // Set our view from the "main" layout resource SetContentView (Resource.Layout.Main); Utils.Util.SetDisplayMetrics (Resources.DisplayMetrics); // Get our button from the layout resource, // and attach an event to it Button button = FindViewById<Button> (Resource.Id.btn_draw); ImageView iv = FindViewById<ImageView> (Resource.Id.imageView_output); SeekBar intensity = FindViewById<SeekBar> (Resource.Id.seekBar1); int width = Utils.Util.DetectScreenSize ().Width; int height = Utils.Util.DetectScreenSize ().Height; intensity.ProgressChanged += (object sender, SeekBar.ProgressChangedEventArgs e) => { if (e.FromUser) { intensiteit = intensity_arr [e.Progress]; if (b != null) { iv.SetImageBitmap (null); } b = DrawImages.GetImage (width, height,intensiteit); iv.SetImageBitmap (b); b.Dispose (); //waarde.Text = string.Format ("The value of the intensity is {0}", intensity_arr[e.Progress]); } }; button.Click += delegate { intensiteit = intensity_arr[intensity.Progress]; if (b != null) { iv.SetImageBitmap (null); } b = DrawImages.GetImage (width, height,intensiteit); iv.SetImageBitmap (b); b.Dispose (); }; }
public static Tensor ReadTensorFromImageFile(String fileName, int inputHeight = -1, int inputWidth = -1, float inputMean = 0.0f, float scale = 1.0f, Status status = null) { #if __ANDROID__ Android.Graphics.Bitmap bmp = BitmapFactory.DecodeFile(fileName); if (inputHeight > 0 || inputWidth > 0) { Bitmap resized = Bitmap.CreateScaledBitmap(bmp, inputWidth, inputHeight, false); bmp.Dispose(); bmp = resized; } int[] intValues = new int[bmp.Width * bmp.Height]; float[] floatValues = new float[bmp.Width * bmp.Height * 3]; bmp.GetPixels(intValues, 0, bmp.Width, 0, 0, bmp.Width, bmp.Height); for (int i = 0; i < intValues.Length; ++i) { int val = intValues[i]; floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 2] = ((val & 0xFF) - inputMean) * scale; } Tensor t = new Tensor(DataType.Float, new int[] { 1, bmp.Height, bmp.Width, 3 }); System.Runtime.InteropServices.Marshal.Copy(floatValues, 0, t.DataPointer, floatValues.Length); return(t); #elif __IOS__ UIImage image = new UIImage(fileName); if (inputHeight > 0 || inputWidth > 0) { UIImage resized = image.Scale(new CGSize(inputWidth, inputHeight)); image.Dispose(); image = resized; } int[] intValues = new int[(int)(image.Size.Width * image.Size.Height)]; float[] floatValues = new float[(int)(image.Size.Width * image.Size.Height * 3)]; System.Runtime.InteropServices.GCHandle handle = System.Runtime.InteropServices.GCHandle.Alloc(intValues, System.Runtime.InteropServices.GCHandleType.Pinned); using (CGImage cgimage = image.CGImage) using (CGColorSpace cspace = CGColorSpace.CreateDeviceRGB()) using (CGBitmapContext context = new CGBitmapContext( handle.AddrOfPinnedObject(), (nint)image.Size.Width, (nint)image.Size.Height, 8, (nint)image.Size.Width * 4, cspace, CGImageAlphaInfo.PremultipliedLast )) { context.DrawImage(new CGRect(new CGPoint(), image.Size), cgimage); } handle.Free(); for (int i = 0; i < intValues.Length; ++i) { int val = intValues[i]; floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 2] = ((val & 0xFF) - inputMean) * scale; } Tensor t = new Tensor(DataType.Float, new int[] { 1, (int)image.Size.Height, (int)image.Size.Width, 3 }); System.Runtime.InteropServices.Marshal.Copy(floatValues, 0, t.DataPointer, floatValues.Length); return(t); #else if (Emgu.TF.Util.Platform.OperationSystem == OS.Windows) { Tensor t = new Tensor(DataType.Float, new int[] { 1, (int)inputHeight, (int)inputWidth, 3 }); NativeImageIO.ReadImageFileToTensor(fileName, t.DataPointer, inputHeight, inputWidth, inputMean, scale); return(t); } else { using (StatusChecker checker = new StatusChecker(status)) { var graph = new Graph(); Operation input = graph.Placeholder(DataType.String); Operation jpegDecoder = graph.DecodeJpeg(input, 3); //dimension 3 Operation floatCaster = graph.Cast(jpegDecoder, DstT: DataType.Float); //cast to float Tensor axis = new Tensor(0); Operation axisOp = graph.Const(axis, axis.Type, opName: "axis"); Operation dimsExpander = graph.ExpandDims(floatCaster, axisOp); //turn it to dimension [1,3] Operation resized; bool resizeRequired = (inputHeight > 0) && (inputWidth > 0); if (resizeRequired) { Tensor size = new Tensor(new int[] { inputHeight, inputWidth }); // new size; Operation sizeOp = graph.Const(size, size.Type, opName: "size"); resized = graph.ResizeBilinear(dimsExpander, sizeOp); //resize image } else { resized = dimsExpander; } Tensor mean = new Tensor(inputMean); Operation meanOp = graph.Const(mean, mean.Type, opName: "mean"); Operation substracted = graph.Sub(resized, meanOp); Tensor scaleTensor = new Tensor(scale); Operation scaleOp = graph.Const(scaleTensor, scaleTensor.Type, opName: "scale"); Operation scaled = graph.Mul(substracted, scaleOp); Session session = new Session(graph); Tensor imageTensor = Tensor.FromString(File.ReadAllBytes(fileName), status); Tensor[] imageResults = session.Run(new Output[] { input }, new Tensor[] { imageTensor }, new Output[] { scaled }); return(imageResults[0]); } } #endif }
public static void ReadImageFileToTensor <T>( String fileName, IntPtr dest, int inputHeight = -1, int inputWidth = -1, float inputMean = 0.0f, float scale = 1.0f, bool flipUpSideDown = false, bool swapBR = false) where T : struct { #if __ANDROID__ if (flipUpSideDown) { throw new NotImplementedException("Flip Up Side Down is Not implemented"); } if (swapBR) { throw new NotImplementedException("swapBR is Not implemented"); } Android.Graphics.Bitmap bmp = BitmapFactory.DecodeFile(fileName); if (inputHeight > 0 || inputWidth > 0) { Bitmap resized = Bitmap.CreateScaledBitmap(bmp, inputWidth, inputHeight, false); bmp.Dispose(); bmp = resized; } int[] intValues = new int[bmp.Width * bmp.Height]; float[] floatValues = new float[bmp.Width * bmp.Height * 3]; bmp.GetPixels(intValues, 0, bmp.Width, 0, 0, bmp.Width, bmp.Height); for (int i = 0; i < intValues.Length; ++i) { int val = intValues[i]; floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 2] = ((val & 0xFF) - inputMean) * scale; } Marshal.Copy(floatValues, 0, dest, floatValues.Length); #elif __IOS__ if (flipUpSideDown) { throw new NotImplementedException("Flip Up Side Down is Not implemented"); } if (swapBR) { throw new NotImplementedException("swapBR is Not implemented"); } UIImage image = new UIImage(fileName); if (inputHeight > 0 || inputWidth > 0) { UIImage resized = image.Scale(new CGSize(inputWidth, inputHeight)); image.Dispose(); image = resized; } int[] intValues = new int[(int)(image.Size.Width * image.Size.Height)]; float[] floatValues = new float[(int)(image.Size.Width * image.Size.Height * 3)]; System.Runtime.InteropServices.GCHandle handle = System.Runtime.InteropServices.GCHandle.Alloc(intValues, System.Runtime.InteropServices.GCHandleType.Pinned); using (CGImage cgimage = image.CGImage) using (CGColorSpace cspace = CGColorSpace.CreateDeviceRGB()) using (CGBitmapContext context = new CGBitmapContext( handle.AddrOfPinnedObject(), (nint)image.Size.Width, (nint)image.Size.Height, 8, (nint)image.Size.Width * 4, cspace, CGImageAlphaInfo.PremultipliedLast )) { context.DrawImage(new CGRect(new CGPoint(), image.Size), cgimage); } handle.Free(); for (int i = 0; i < intValues.Length; ++i) { int val = intValues[i]; floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 2] = ((val & 0xFF) - inputMean) * scale; } System.Runtime.InteropServices.Marshal.Copy(floatValues, 0, dest, floatValues.Length); #elif __UNIFIED__ if (flipUpSideDown) { throw new NotImplementedException("Flip Up Side Down is Not implemented"); } if (swapBR) { throw new NotImplementedException("swapBR is Not implemented"); } NSImage image = new NSImage(fileName); if (inputHeight > 0 || inputWidth > 0) { NSImage resized = new NSImage(new CGSize(inputWidth, inputHeight)); resized.LockFocus(); image.DrawInRect(new CGRect(0, 0, inputWidth, inputHeight), CGRect.Empty, NSCompositingOperation.SourceOver, 1.0f); resized.UnlockFocus(); image.Dispose(); image = resized; } int[] intValues = new int[(int)(image.Size.Width * image.Size.Height)]; float[] floatValues = new float[(int)(image.Size.Width * image.Size.Height * 3)]; System.Runtime.InteropServices.GCHandle handle = System.Runtime.InteropServices.GCHandle.Alloc(intValues, System.Runtime.InteropServices.GCHandleType.Pinned); using (CGImage cgimage = image.CGImage) using (CGColorSpace cspace = CGColorSpace.CreateDeviceRGB()) using (CGBitmapContext context = new CGBitmapContext( handle.AddrOfPinnedObject(), (nint)image.Size.Width, (nint)image.Size.Height, 8, (nint)image.Size.Width * 4, cspace, CGImageAlphaInfo.PremultipliedLast )) { context.DrawImage(new CGRect(new CGPoint(), image.Size), cgimage); } handle.Free(); for (int i = 0; i < intValues.Length; ++i) { int val = intValues[i]; floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 2] = ((val & 0xFF) - inputMean) * scale; } System.Runtime.InteropServices.Marshal.Copy(floatValues, 0, dest, floatValues.Length); #elif UNITY_EDITOR || UNITY_IOS || UNITY_ANDROID || UNITY_STANDALONE Texture2D texture = ReadTexture2DFromFile(fileName); ReadTensorFromTexture2D <T>(texture, dest, inputHeight, inputWidth, inputMean, scale, flipUpSideDown, false); #else if (Emgu.TF.Util.Platform.OperationSystem == OS.Windows) { //Do something for Windows System.Drawing.Bitmap bmp = new Bitmap(fileName); if (inputHeight > 0 || inputWidth > 0) { //resize bmp System.Drawing.Bitmap newBmp = new Bitmap(bmp, inputWidth, inputHeight); bmp.Dispose(); bmp = newBmp; //bmp.Save("tmp.png"); } if (flipUpSideDown) { bmp.RotateFlip(RotateFlipType.RotateNoneFlipY); } byte[] byteValues = new byte[bmp.Width * bmp.Height * 3]; System.Drawing.Imaging.BitmapData bd = new System.Drawing.Imaging.BitmapData(); bmp.LockBits( new Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format24bppRgb, bd); Marshal.Copy(bd.Scan0, byteValues, 0, byteValues.Length); bmp.UnlockBits(bd); if (typeof(T) == typeof(float)) { int imageSize = bmp.Width * bmp.Height; float[] floatValues = new float[imageSize * 3]; if (swapBR) { for (int i = 0; i < imageSize; ++i) { floatValues[i * 3] = (byte)(((float)byteValues[i * 3 + 2] - inputMean) * scale); floatValues[i * 3 + 1] = (byte)(((float)byteValues[i * 3 + 1] - inputMean) * scale); floatValues[i * 3 + 2] = (byte)(((float)byteValues[i * 3 + 0] - inputMean) * scale); } } else { for (int i = 0; i < byteValues.Length; ++i) { floatValues[i] = ((float)byteValues[i] - inputMean) * scale; } } Marshal.Copy(floatValues, 0, dest, floatValues.Length); } else if (typeof(T) == typeof(byte)) { if (swapBR) { int imageSize = bmp.Width * bmp.Height; //byte[] bValues = new byte[imageSize * 3]; for (int i = 0; i < imageSize; ++i) { byte c0 = (byte)(((float)byteValues[i * 3 + 2] - inputMean) * scale); byte c1 = (byte)(((float)byteValues[i * 3 + 1] - inputMean) * scale); byte c2 = (byte)(((float)byteValues[i * 3 + 0] - inputMean) * scale); byteValues[i * 3] = c0; byteValues[i * 3 + 1] = c1; byteValues[i * 3 + 2] = c2; } } else { if (!(inputMean == 0.0f && scale == 1.0f)) { for (int i = 0; i < byteValues.Length; ++i) { byteValues[i] = (byte)(((float)byteValues[i] - inputMean) * scale); } } } Marshal.Copy(byteValues, 0, dest, byteValues.Length); } else { throw new Exception(String.Format("Destination data type {0} is not supported.", typeof(T).ToString())); } } else //Unix { if (flipUpSideDown) { throw new NotImplementedException("Flip Up Side Down is Not implemented"); } throw new Exception("Not implemented"); } #endif }
// This gets called when the drawing surface is ready protected override void OnLoad (EventArgs e) { base.OnLoad (e); try { // Clear the current Context GraphicsContext.MakeCurrent (null); // Create a secondary context using the same information the primary // context was created with backgroundContext = new AndroidGraphicsContext(GraphicsMode, WindowInfo, GraphicsContext, ContextRenderingApi, GraphicsContextFlags.Embedded); }catch { // secondary context not supported backgroundContext = null; } MakeCurrent(); var vertexShader = LoadShader(ShaderType.VertexShader, vertexShaderCode); var fragmentShader = LoadShader(ShaderType.FragmentShader, fragmentShaderCode); program = GL.CreateProgram (); // create empty OpenGL Program GL.AttachShader (program, vertexShader); // add the vertex shader to program GL.AttachShader (program, fragmentShader); // add the fragment shader to program GL.BindAttribLocation (program, ATTRIB_VERTEX, "position"); GL.BindAttribLocation (program, ATTRIB_TEXCOORD, "texcoord"); GL.LinkProgram (program); // create OpenGL program executables uniformTextureLocation = GL.GetUniformLocation (program, "texture"); if (vertexShader != 0) { GL.DetachShader (program, vertexShader); GL.DeleteShader (vertexShader); } if (fragmentShader != 0) { GL.DetachShader (program, fragmentShader); GL.DeleteShader (fragmentShader); } GL.Viewport (0, 0, Width, Height); // Run the render loop Run (); Task.Factory.StartNew (() => { //Thread.Sleep(500); // load the bitmap bitmap = BitmapFactory.DecodeResource (Context.Resources, Resource.Drawable.f_spot); // the device may or may not support a background Context. But rather than // duplicating this code we just create an Action which we can invoke on this // background thread later or queue to be executed on the rendering thread. Action acton = new Action (() => { GL.Enable (EnableCap.Texture2D); GL.GenTextures(1, out textureid); GL.ActiveTexture (TextureUnit.Texture0); GL.BindTexture (TextureTarget.Texture2D, textureid); // setup texture parameters GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear); GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear); GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.ClampToEdge); GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.ClampToEdge); Android.Opengl.GLUtils.TexImage2D ((int)TextureTarget.Texture2D, 0, bitmap, 0); // make sure the texture is pushed to the GPU. GL.Flush(); // make sure we free resources bitmap.Recycle(); bitmap.Dispose(); bitmap = null; }); // take a lock so the main rendering thread does not try to draw anything // there are other ways to do this, but its is probably the simplest lock (lockobject) { if (backgroundContext != null) { // Clear the current context bound to the Display backgroundContext.MakeCurrent (null); // make this context active backgroundContext.MakeCurrent (WindowInfo); // do our processing acton.Invoke (); // clear the current context again so we don't error on the main thread backgroundContext.MakeCurrent (null); } else { // Secondary Context's are not supported on this device // queue the action for execution later. actions.Enqueue (acton); } } }); }