private static void SaveFromMemory(PixelBuffer[] pixelBuffers, int count, ImageDescription description, Stream imageStream, Bitmap.CompressFormat imageFormat) { var colors = pixelBuffers[0].GetPixels<int>(); using (var bitmap = Bitmap.CreateBitmap(description.Width, description.Height, Bitmap.Config.Argb8888)) { var pixelData = bitmap.LockPixels(); var sizeToCopy = colors.Length * sizeof(int); unsafe { fixed (int* pSrc = colors) { // Copy the memory if (description.Format == PixelFormat.R8G8B8A8_UNorm || description.Format == PixelFormat.R8G8B8A8_UNorm_SRgb) { CopyMemoryBGRA(pixelData, (IntPtr)pSrc, sizeToCopy); } else if (description.Format == PixelFormat.B8G8R8A8_UNorm || description.Format == PixelFormat.B8G8R8A8_UNorm_SRgb) { Utilities.CopyMemory(pixelData, (IntPtr)pSrc, sizeToCopy); } else { throw new NotSupportedException(string.Format("Pixel format [{0}] is not supported", description.Format)); } } } bitmap.UnlockPixels(); bitmap.Compress(imageFormat, 100, imageStream); } }
public static unsafe Image LoadFromMemory(IntPtr pSource, int size, bool makeACopy, GCHandle? handle) { var stream = new BinarySerializationReader(new NativeMemoryStream((byte*)pSource, size)); // Read and check magic code var magicCode = stream.ReadUInt32(); if (magicCode != MagicCode) return null; // Read header var imageDescription = new ImageDescription(); imageDescriptionSerializer.Serialize(ref imageDescription, ArchiveMode.Deserialize, stream); if (makeACopy) { var buffer = Utilities.AllocateMemory(size); Utilities.CopyMemory(buffer, pSource, size); pSource = buffer; makeACopy = false; } var image = new Image(imageDescription, pSource, 0, handle, !makeACopy); var totalSizeInBytes = stream.ReadInt32(); if (totalSizeInBytes != image.TotalSizeInBytes) throw new InvalidOperationException("Image size is different than expected."); // Read image data stream.Serialize(image.DataPointer, image.TotalSizeInBytes); return image; }
private static void SaveFromMemory(PixelBuffer[] pixelBuffers, int count, ImageDescription description, Stream imageStream, ImageFormat imageFormat) { using (var bitmap = new Bitmap(description.Width, description.Height)) { var sourceArea = new Rectangle(0, 0, bitmap.Width, bitmap.Height); // Lock System.Drawing.Bitmap var bitmapData = bitmap.LockBits(sourceArea, ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppPArgb); try { // Copy memory if (description.Format == PixelFormat.R8G8B8A8_UNorm || description.Format == PixelFormat.R8G8B8A8_UNorm_SRgb) CopyMemoryBGRA(bitmapData.Scan0, pixelBuffers[0].DataPointer, pixelBuffers[0].BufferStride); else if (description.Format == PixelFormat.B8G8R8A8_UNorm || description.Format == PixelFormat.B8G8R8A8_UNorm_SRgb) Utilities.CopyMemory(bitmapData.Scan0, pixelBuffers[0].DataPointer, pixelBuffers[0].BufferStride); else throw new NotSupportedException(string.Format("Pixel format [{0}] is not supported", description.Format)); } finally { bitmap.UnlockBits(bitmapData); } // Save bitmap.Save(imageStream, imageFormat); } }
public void Read(BinaryReader reader) { TestName = reader.ReadString(); CurrentVersion = reader.ReadString(); Frame = reader.ReadString(); // Read image header var width = reader.ReadInt32(); var height = reader.ReadInt32(); var format = (PixelFormat)reader.ReadInt32(); var textureSize = reader.ReadInt32(); // Read image data var imageData = new byte[textureSize]; using (var lz4Stream = new LZ4Stream(reader.BaseStream, CompressionMode.Decompress, false, textureSize)) { if (lz4Stream.Read(imageData, 0, textureSize) != textureSize) throw new EndOfStreamException("Unexpected end of stream"); } var pinnedImageData = GCHandle.Alloc(imageData, GCHandleType.Pinned); var description = new ImageDescription { Dimension = TextureDimension.Texture2D, Width = width, Height = height, ArraySize = 1, Depth = 1, Format = format, MipLevels = 1, }; Image = Image.New(description, pinnedImageData.AddrOfPinnedObject(), 0, pinnedImageData, false); }
private static void SaveFromMemory(PixelBuffer[] pixelBuffers, int count, ImageDescription description, Stream imageStream, Bitmap.CompressFormat imageFormat) { var colors = pixelBuffers[0].GetPixels<int>(); using (var bitmap = Bitmap.CreateBitmap(colors, description.Width, description.Height, Bitmap.Config.Argb8888)) { bitmap.Compress(imageFormat, 0, imageStream); } }
public static void SaveFromMemory(PixelBuffer[] pixelBuffers, int count, ImageDescription description, System.IO.Stream imageStream) { var stream = new BinarySerializationWriter(imageStream); // Write magic code stream.Write(MagicCode); // Write image header imageDescriptionSerializer.Serialize(ref description, ArchiveMode.Serialize, stream); // Write total size int totalSize = 0; foreach (var pixelBuffer in pixelBuffers) totalSize += pixelBuffer.BufferStride; stream.Write(totalSize); // Write buffers contiguously foreach (var pixelBuffer in pixelBuffers) { stream.Serialize(pixelBuffer.DataPointer, pixelBuffer.BufferStride); } }
/// <summary> /// Determines number of image array entries and pixel size. /// </summary> /// <param name="imageDesc">Description of the image to create.</param> /// <param name="pitchFlags">Pitch flags.</param> /// <param name="bufferCount">Output number of mipmap.</param> /// <param name="pixelSizeInBytes">Output total size to allocate pixel buffers for all images.</param> private static List<int> CalculateImageArray( ImageDescription imageDesc, PitchFlags pitchFlags, out int bufferCount, out int pixelSizeInBytes) { pixelSizeInBytes = 0; bufferCount = 0; var mipmapToZIndex = new List<int>(); for (int j = 0; j < imageDesc.ArraySize; j++) { int w = imageDesc.Width; int h = imageDesc.Height; int d = imageDesc.Depth; for (int i = 0; i < imageDesc.MipLevels; i++) { int rowPitch, slicePitch; int widthPacked; int heightPacked; ComputePitch(imageDesc.Format, w, h, out rowPitch, out slicePitch, out widthPacked, out heightPacked, pitchFlags); // Store the number of z-slicec per miplevels if ( j == 0) mipmapToZIndex.Add(bufferCount); // Keep a trace of indices for the 1st array size, for each mip levels pixelSizeInBytes += d * slicePitch; bufferCount += d; if (h > 1) h >>= 1; if (w > 1) w >>= 1; if (d > 1) d >>= 1; } // For the last mipmaps, store just the number of zbuffers in total if (j == 0) mipmapToZIndex.Add(bufferCount); } return mipmapToZIndex; }
public void SetIcon(ImageDescription icon) { // TODO }
public override object ConvertToBitmap(ImageDescription idesc, double scaleFactor, XD.ImageFormat format) { var image = (GdiImage)idesc.Backend; return(image.ConvertToBitmap(idesc.Size.Width, idesc.Size.Height, scaleFactor, format)); }
internal static MipMapDescription[] CalculateMipMapDescription(ImageDescription metadata, PitchFlags cpFlags, out int nImages, out int pixelSize) { pixelSize = 0; nImages = 0; int w = metadata.Width; int h = metadata.Height; int d = metadata.Depth; var mipmaps = new MipMapDescription[metadata.MipLevels]; for (int level = 0; level < metadata.MipLevels; ++level) { int rowPitch, slicePitch; int widthPacked; int heightPacked; ComputePitch(metadata.Format, w, h, out rowPitch, out slicePitch, out widthPacked, out heightPacked, PitchFlags.None); mipmaps[level] = new MipMapDescription( w, h, d, rowPitch, slicePitch, widthPacked, heightPacked ); pixelSize += d * slicePitch; nImages += d; if (h > 1) h >>= 1; if (w > 1) w >>= 1; if (d > 1) d >>= 1; } return mipmaps; }
/// <summary> /// Saves this instance to a stream. /// </summary> /// <param name="pixelBuffers">The buffers to save.</param> /// <param name="count">The number of buffers to save.</param> /// <param name="description">Global description of the buffer.</param> /// <param name="imageStream">The destination stream.</param> /// <param name="fileType">Specify the output format.</param> /// <remarks>This method support the following format: <c>dds, bmp, jpg, png, gif, tiff, wmp, tga</c>.</remarks> internal static void Save(PixelBuffer[] pixelBuffers, int count, ImageDescription description, Stream imageStream, ImageFileType fileType) { foreach (var loadSaveDelegate in loadSaveDelegates) { if (loadSaveDelegate.FileType == fileType) { loadSaveDelegate.Save(pixelBuffers, count, description, imageStream); return; } } throw new NotSupportedException("This file format is not yet implemented."); }
/// <summary> /// Initializes a new instance of the <see cref="Image" /> class. /// </summary> /// <param name="description">The image description.</param> /// <param name="dataPointer">The pointer to the data buffer.</param> /// <param name="offset">The offset from the beginning of the data buffer.</param> /// <param name="handle">The handle (optionnal).</param> /// <param name="bufferIsDisposable">if set to <c>true</c> [buffer is disposable].</param> /// <exception cref="System.InvalidOperationException">If the format is invalid, or width/height/depth/arraysize is invalid with respect to the dimension.</exception> internal unsafe Image(ImageDescription description, IntPtr dataPointer, int offset, GCHandle? handle, bool bufferIsDisposable, PitchFlags pitchFlags = PitchFlags.None, int rowStride = 0) { Initialize(description, dataPointer, offset, handle, bufferIsDisposable, pitchFlags, rowStride); }
public static void SavePngFromMemory(PixelBuffer[] pixelBuffers, int count, ImageDescription description, Stream imageStream) { SaveFromMemory(pixelBuffers, count, description, imageStream, Bitmap.CompressFormat.Png); }
public void SetImage(ImageDescription image) { item.Image = image.ToNSImage(); }
public Gdk.Pixbuf GetBestFrame(ApplicationContext actx, Gtk.Widget w, ImageDescription idesc, bool forceExactSize) { return(GetBestFrame(actx, Util.GetScaleFactor(w), idesc, forceExactSize)); }
public void SetContent(string label, bool useMnemonic, ImageDescription image, ContentPosition position) { Widget.UseUnderline = useMnemonic; this.image = image; if (label != null && label.Length == 0) { label = null; } Button b = (Button)Frontend; if (label != null && image.Backend == null && b.Type == ButtonType.Normal) { Widget.Label = label; return; } if (b.Type == ButtonType.Disclosure) { Widget.Label = null; Widget.Image = new Gtk.Arrow(Gtk.ArrowType.Down, Gtk.ShadowType.Out); Widget.Image.ShowAll(); return; } Gtk.Widget contentWidget = null; Gtk.Widget imageWidget = null; if (image.Backend != null) { imageWidget = new ImageBox(ApplicationContext, image.WithDefaultSize(Gtk.IconSize.Button)); } if (label != null && imageWidget == null) { contentWidget = new Gtk.Label(label) { UseUnderline = useMnemonic }; } else if (label == null && imageWidget != null) { contentWidget = imageWidget; } else if (label != null && imageWidget != null) { Gtk.Box box = position == ContentPosition.Left || position == ContentPosition.Right ? (Gtk.Box) new Gtk.HBox(false, 3) : (Gtk.Box) new Gtk.VBox(false, 3); var lab = new Gtk.Label(label) { UseUnderline = useMnemonic }; if (position == ContentPosition.Left || position == ContentPosition.Top) { box.PackStart(imageWidget, false, false, 0); box.PackStart(lab, false, false, 0); } else { box.PackStart(lab, false, false, 0); box.PackStart(imageWidget, false, false, 0); } contentWidget = box; } if (b.Type == ButtonType.DropDown) { if (contentWidget != null) { Gtk.HBox box = new Gtk.HBox(false, 3); box.PackStart(contentWidget, true, true, 3); box.PackStart(new Gtk.VSeparator(), true, true, 0); box.PackStart(new Gtk.Arrow(Gtk.ArrowType.Down, Gtk.ShadowType.Out), false, false, 0); contentWidget = box; } else { contentWidget = new Gtk.Arrow(Gtk.ArrowType.Down, Gtk.ShadowType.Out); } } if (contentWidget != null) { contentWidget.ShowAll(); Widget.Label = null; Widget.Image = contentWidget; } else { Widget.Label = null; } }
public void Draw(ApplicationContext actx, SWM.DrawingContext dc, double scaleFactor, double x, double y, ImageDescription idesc) { if (drawCallback != null) { DrawingContext c = new DrawingContext(dc, scaleFactor); actx.InvokeUserCode(delegate { drawCallback(c, new Rectangle(x, y, idesc.Size.Width, idesc.Size.Height), idesc, actx.Toolkit); }); } else { if (idesc.Alpha < 1) { dc.PushOpacity(idesc.Alpha); } var f = GetBestFrame(actx, scaleFactor, idesc.Size.Width, idesc.Size.Height, false); var bmpImage = f as BitmapSource; // When an image is a single bitmap that doesn't have the same intrinsic size as the drawing size, dc.DrawImage makes a very poor job of down/up scaling it. // Thus we handle this manually by using a TransformedBitmap to handle the conversion in a better way when it's needed. var scaledWidth = idesc.Size.Width * scaleFactor; var scaledHeight = idesc.Size.Height * scaleFactor; if (bmpImage != null && (Math.Abs(bmpImage.PixelHeight - scaledHeight) > 0.001 || Math.Abs(bmpImage.PixelWidth - scaledWidth) > 0.001)) { f = new TransformedBitmap(bmpImage, new ScaleTransform(scaledWidth / bmpImage.PixelWidth, scaledHeight / bmpImage.PixelHeight)); } dc.DrawImage(f, new Rect(x, y, idesc.Size.Width, idesc.Size.Height)); if (idesc.Alpha < 1) { dc.Pop(); } } }
public override object ConvertToBitmap(ImageDescription idesc, double scaleFactor, Xwt.Drawing.ImageFormat format) { var wpfImage = (WpfImage)idesc.Backend; return(new WpfImage(wpfImage.GetBestFrame(ApplicationContext, scaleFactor, idesc, true))); }
private static void SaveFromMemory(PixelBuffer[] pixelBuffers, int count, ImageDescription description, Stream imageStream, ImageFormat imageFormat) { #if (SILICONSTUDIO_XENKO_UI_WINFORMS || SILICONSTUDIO_XENKO_UI_WPF) using (var bitmap = new Bitmap(description.Width, description.Height)) { var sourceArea = new Rectangle(0, 0, bitmap.Width, bitmap.Height); // Lock System.Drawing.Bitmap var bitmapData = bitmap.LockBits(sourceArea, ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppPArgb); try { // Copy memory if (description.Format == PixelFormat.R8G8B8A8_UNorm || description.Format == PixelFormat.R8G8B8A8_UNorm_SRgb) CopyMemoryBGRA(bitmapData.Scan0, pixelBuffers[0].DataPointer, pixelBuffers[0].BufferStride); else if (description.Format == PixelFormat.B8G8R8A8_UNorm || description.Format == PixelFormat.B8G8R8A8_UNorm_SRgb) Utilities.CopyMemory(bitmapData.Scan0, pixelBuffers[0].DataPointer, pixelBuffers[0].BufferStride); else { // TODO Ideally we will want to support grayscale images, but the SpriteBatch can only render RGBA for now // so convert the grayscale image as an RGBA and save it CopyMemoryRRR1(bitmapData.Scan0, pixelBuffers[0].DataPointer, pixelBuffers[0].BufferStride); } } finally { bitmap.UnlockBits(bitmapData); } // Save bitmap.Save(imageStream, imageFormat); } #else // FIXME: Manu: Currently SDL can only save to BMP or PNG. #endif }
public override object ConvertToBitmap(ImageDescription idesc, double scaleFactor, ImageFormat format) { double width = idesc.Size.Width; double height = idesc.Size.Height; int pixelWidth = (int)(width * scaleFactor); int pixelHeight = (int)(height * scaleFactor); if (idesc.Backend is CustomImage) { var flags = CGBitmapFlags.ByteOrderDefault; int bytesPerRow; switch (format) { case ImageFormat.ARGB32: bytesPerRow = pixelWidth * 4; flags |= CGBitmapFlags.PremultipliedFirst; break; case ImageFormat.RGB24: bytesPerRow = pixelWidth * 3; flags |= CGBitmapFlags.None; break; default: throw new NotImplementedException("ImageFormat: " + format.ToString()); } var bmp = new CGBitmapContext(IntPtr.Zero, pixelWidth, pixelHeight, 8, bytesPerRow, Util.DeviceRGBColorSpace, flags); bmp.TranslateCTM(0, pixelHeight); bmp.ScaleCTM((float)scaleFactor, (float)-scaleFactor); var ctx = new CGContextBackend { Context = bmp, Size = new CGSize((nfloat)width, (nfloat)height), InverseViewTransform = bmp.GetCTM().Invert(), ScaleFactor = scaleFactor }; var ci = (CustomImage)idesc.Backend; ci.DrawInContext(ctx, idesc); var img = new NSImage(((CGBitmapContext)bmp).ToImage(), new CGSize(pixelWidth, pixelHeight)); var imageData = img.AsTiff(); var imageRep = (NSBitmapImageRep)NSBitmapImageRep.ImageRepFromData(imageData); var im = new NSImage(); im.AddRepresentation(imageRep); im.Size = new CGSize((nfloat)width, (nfloat)height); bmp.Dispose(); return(im); } else { NSImage img = (NSImage)idesc.Backend; NSBitmapImageRep bitmap = img.Representations().OfType <NSBitmapImageRep> ().FirstOrDefault(); if (bitmap == null) { var imageData = img.AsTiff(); var imageRep = (NSBitmapImageRep)NSBitmapImageRep.ImageRepFromData(imageData); var im = new NSImage(); im.AddRepresentation(imageRep); im.Size = new CGSize((nfloat)width, (nfloat)height); return(im); } return(idesc.Backend); } }
public ImageBox(ApplicationContext actx, ImageDescription img) : this(actx) { Image = img; }
public void trainNestedAlgorithm(ContextualMemoryNestedAlgorithm nestedAlgorithm) { BlackAndWhiteConverter blackAndWhiteConverter = new BlackAndWhiteConverter(1); //BlackAndWhiteConverter blackAndWhiteConverter = new BlackAndWhiteConverter(63); List <String> fileList = new List <string>(benchmark.getTrainingFilesPathList()); List <ContextualMemoryNestedAlgorithmLayer> layers = nestedAlgorithm.getLayers(); for (int layerIndex = 0; layerIndex < layers.Count; layerIndex++) { ContextualMemoryNestedAlgorithmLayer layer = layers[layerIndex]; layer.initialize(); Console.WriteLine("Layer: " + (layerIndex + 1) + "/" + layers.Count); EdgeDetectionAlgorithm algorithm = layer.algorithm; DateTime trainingStart = DateTime.Now; float totalLoss = 0; int totalNumberOfFiles = numberOfTrainingSetPasses * fileList.Count; int totalIndex = 0; for (int pass = 0; pass < numberOfTrainingSetPasses; pass++) { ListUtils.Shuffle(fileList); int index = 1; float totalPassLoss = 0; DateTime trainingPassStart = DateTime.Now; foreach (string trainingFileName in fileList) { DateTime start = DateTime.Now; Console.WriteLine("Pass: "******"/" + numberOfTrainingSetPasses + ", " + index + "/" + fileList.Count + " Training file: " + Path.GetFileName(trainingFileName)); ImageDescription inputImage = ImageFileHandler.loadFromPath(trainingFileName); int layerResizeFactor = layer.resizeFactor; ImageDescription computedImage = null; if (layerIndex > 0) { List <ImageDescription> computedImages = nestedAlgorithm.computeImageForLayers(inputImage, layerIndex); computedImage = computedImages[layerIndex - 1]; } ImageDescription inputImageGroundTruth = ImageFileHandler.loadFromPath(benchmark.getTrainingFileGroundTruth(trainingFileName)); inputImageGroundTruth = blackAndWhiteConverter.filter(inputImageGroundTruth); ImageDescription newInputImage = null; ImageDescription newInputImageGroundTruth = null; ResizeFilter resizeGrayscale = new ResizeFilter(inputImage.sizeX / layerResizeFactor, inputImage.sizeY / layerResizeFactor, ImageDescriptionUtil.grayscaleChannel); ResizeFilter resizeColor = new ResizeFilter(inputImage.sizeX / layerResizeFactor, inputImage.sizeY / layerResizeFactor, ImageDescriptionUtil.colorChannels); if (layerResizeFactor == 1) { newInputImage = inputImage; newInputImageGroundTruth = inputImageGroundTruth; } else { newInputImage = resizeColor.filter(inputImage); newInputImageGroundTruth = resizeGrayscale.filter(inputImageGroundTruth); } if (layerIndex > 0) { ImageDescription resizedComputed = resizeGrayscale.filter(computedImage); newInputImage.setColorChannel(ColorChannelEnum.Layer, resizedComputed.gray); } float loss = algorithm.train(newInputImage, newInputImageGroundTruth); totalLoss += loss; totalPassLoss += loss; index++; totalIndex++; double timeElapsed = (DateTime.Now - start).TotalSeconds; double timeElapsedSoFar = (DateTime.Now - trainingStart).TotalSeconds; double estimatedTime = (timeElapsedSoFar / totalIndex) * (totalNumberOfFiles - totalIndex); Console.WriteLine("Loss: " + loss.ToString("0.00") + " Time: " + timeElapsed.ToString("0.00") + "s Time elapsed: " + timeElapsedSoFar.ToString("0.00") + "s ETA: " + estimatedTime.ToString("0.00") + "s"); } double tariningPassTimeElapsed = (DateTime.Now - trainingPassStart).TotalSeconds; Console.WriteLine("Pass took " + tariningPassTimeElapsed.ToString("0.00") + " sec. Pass loss: " + totalPassLoss.ToString("0.00") + " Avg loss: " + (totalPassLoss / (fileList.Count)).ToString("0.00")); } double totalTimeElapsed = (DateTime.Now - trainingStart).TotalSeconds; Console.WriteLine("Training took " + totalTimeElapsed.ToString("0.00") + " sec. Total loss: " + totalLoss.ToString("0.00") + " Avg loss: " + (totalLoss / (totalNumberOfFiles)).ToString("0.00")); } Console.WriteLine("Training blender"); DateTime blenderTrainingStart = DateTime.Now; float blenderTotalLoss = 0; int blenderTotalNumberOfFiles = /* numberOfTrainingSetPasses * */ fileList.Count; int blenderTotalIndex = 0; ImageBlender blender = nestedAlgorithm.getImageBlender(); //for (int pass = 0; pass < numberOfTrainingSetPasses; pass++) { ListUtils.Shuffle(fileList); int index = 1; float totalPassLoss = 0; DateTime trainingPassStart = DateTime.Now; foreach (string trainingFileName in fileList) { DateTime start = DateTime.Now; //Console.Write("Pass: "******"/" + numberOfTrainingSetPasses + ", "); Console.WriteLine(index + "/" + fileList.Count + " Training file: " + Path.GetFileName(trainingFileName)); ImageDescription inputImage = ImageFileHandler.loadFromPath(trainingFileName); List <ImageDescription> computedImages = nestedAlgorithm.computeImageForLayers(inputImage, layers.Count); ImageDescription inputImageGroundTruth = ImageFileHandler.loadFromPath(benchmark.getTrainingFileGroundTruth(trainingFileName)); inputImageGroundTruth = blackAndWhiteConverter.filter(inputImageGroundTruth); float blenderLoss = blender.train(computedImages, inputImageGroundTruth); blenderTotalLoss += blenderLoss; totalPassLoss += blenderLoss; index++; blenderTotalIndex++; double timeElapsed = (DateTime.Now - start).TotalSeconds; double timeElapsedSoFar = (DateTime.Now - blenderTrainingStart).TotalSeconds; double estimatedTime = (timeElapsedSoFar / blenderTotalIndex) * (blenderTotalNumberOfFiles - blenderTotalIndex); Console.WriteLine("Loss: " + blenderLoss.ToString("0.00") + " Time: " + timeElapsed.ToString("0.00") + "s Time elapsed: " + timeElapsedSoFar.ToString("0.00") + "s ETA: " + estimatedTime.ToString("0.00") + "s"); } //double tariningPassTimeElapsed = (DateTime.Now - trainingPassStart).TotalSeconds; //Console.WriteLine("Pass took " + tariningPassTimeElapsed.ToString("0.00") + " sec. Pass loss: " + totalPassLoss.ToString("0.00") //+ " Avg loss: " + (totalPassLoss / (fileList.Count)).ToString("0.00")); } double blenderTotalTimeElapsed = (DateTime.Now - blenderTrainingStart).TotalSeconds; Console.WriteLine("Training took " + blenderTotalTimeElapsed.ToString("0.00") + " sec. Total loss: " + blenderTotalLoss.ToString("0.00") + " Avg loss: " + (blenderTotalLoss / (blenderTotalNumberOfFiles)).ToString("0.00")); }
public void SetIcon(ImageDescription image) { throw new NotImplementedException(); }
public void test(EdgeDetectionAlgorithm algorithm) { DateTime testingStart = DateTime.Now; List <String> fileList = benchmark.getTestFilesPathList(); int index = 1; string outputDirectory = null; foreach (string testFileName in fileList) { DateTime start = DateTime.Now; outputDirectory = Path.GetDirectoryName(benchmark.getTestFileOutputPathWithoutExtension(testFileName)); if (!Directory.Exists(outputDirectory)) { Directory.CreateDirectory(outputDirectory); } Console.WriteLine(index + "/" + fileList.Count + " Testing file: " + Path.GetFileName(testFileName)); ImageDescription inputImage = ImageFileHandler.loadFromPath(testFileName); ImageDescription outputImage = algorithm.test(inputImage); ImageFileHandler.saveToPath(outputImage, benchmark.getTestFileOutputPathWithoutExtension(testFileName), outputFileExtension); double timeElapsed = (DateTime.Now - start).TotalSeconds; double timeElapsedSoFar = (DateTime.Now - testingStart).TotalSeconds; double estimatedTime = (timeElapsedSoFar / index) * (fileList.Count - index); Console.WriteLine(timeElapsed.ToString("0.00") + "s Time elapsed: " + timeElapsedSoFar.ToString("0.00") + "s ETA: " + estimatedTime.ToString("0.00") + "s"); index++; } double totalTimeElapsed = (DateTime.Now - testingStart).TotalSeconds; Console.WriteLine("Testing took " + totalTimeElapsed.ToString("0.00") + " sec."); if (testOnTrainingFiles) { Console.WriteLine("Testing on training files"); testingStart = DateTime.Now; index = 0; // we have the outputDirectory from test, else, relative to the exe outputDirectory = Path.Combine(outputDirectory, trainingFilesTestOutput); if (!Directory.Exists(outputDirectory)) { Directory.CreateDirectory(outputDirectory); } fileList = new List <string>(benchmark.getTrainingFilesPathList()); foreach (string trainingFileName in fileList) { DateTime start = DateTime.Now; string outputPath = Path.Combine(outputDirectory, Path.GetFileNameWithoutExtension(trainingFileName)); Console.WriteLine(index + "/" + fileList.Count + " Testing file: " + Path.GetFileName(trainingFileName)); ImageDescription inputImage = ImageFileHandler.loadFromPath(trainingFileName); ImageDescription outputImage = algorithm.test(inputImage); ImageFileHandler.saveToPath(outputImage, outputPath, outputFileExtension); index++; double timeElapsed = (DateTime.Now - start).TotalSeconds; Console.WriteLine(timeElapsed.ToString("0.00") + " seconds"); } totalTimeElapsed = (DateTime.Now - testingStart).TotalSeconds; Console.WriteLine("Testing on training files took " + totalTimeElapsed.ToString("0.00") + " sec."); } }
/// <summary> /// Creates a new instance of <see cref="Image"/> from an image description. /// </summary> /// <param name="description">The image description.</param> /// <param name="dataPointer">Pointer to an existing buffer.</param> /// <returns>A new image.</returns> public static Image New(ImageDescription description, IntPtr dataPointer) { return new Image(description, dataPointer, 0, null, false); }
public void testNestedAlgorithm(ContextualMemoryNestedAlgorithm nestedAlgorithm) { DateTime testingStart = DateTime.Now; List <String> fileList = benchmark.getTestFilesPathList(); int index = 1; string outputDirectory = null; foreach (string testFileName in fileList) { DateTime start = DateTime.Now; outputDirectory = Path.GetDirectoryName(benchmark.getTestFileOutputPathWithoutExtension(testFileName)); if (!Directory.Exists(outputDirectory)) { Directory.CreateDirectory(outputDirectory); } Console.WriteLine(index + "/" + fileList.Count + " Testing file: " + Path.GetFileName(testFileName)); ImageDescription inputImage = ImageFileHandler.loadFromPath(testFileName); List <ContextualMemoryNestedAlgorithmLayer> layers = nestedAlgorithm.getLayers(); List <ImageDescription> computedImages = nestedAlgorithm.computeImageForLayers(inputImage, layers.Count); for (int i = 0; i < layers.Count; i++) { if (layers[i].outputResults) { ImageFileHandler.saveToPath(computedImages[i], benchmark.getTestFileOutputPathWithoutExtension(testFileName) + "_layer" + i, outputFileExtension); } } ImageDescription outputImage = nestedAlgorithm.getImageBlender().blendImages(computedImages); ImageFileHandler.saveToPath(outputImage, benchmark.getTestFileOutputPathWithoutExtension(testFileName), outputFileExtension); double timeElapsed = (DateTime.Now - start).TotalSeconds; double timeElapsedSoFar = (DateTime.Now - testingStart).TotalSeconds; double estimatedTime = (timeElapsedSoFar / index) * (fileList.Count - index); Console.WriteLine(timeElapsed.ToString("0.00") + "s Time elapsed: " + timeElapsedSoFar.ToString("0.00") + "s ETA: " + estimatedTime.ToString("0.00") + "s"); index++; } double totalTimeElapsed = (DateTime.Now - testingStart).TotalSeconds; Console.WriteLine("Testing took " + totalTimeElapsed.ToString("0.00") + " sec."); if (testOnTrainingFiles) { Console.WriteLine("Testing on training files"); testingStart = DateTime.Now; index = 0; // we have the outputDirectory from test, else, relative to the exe outputDirectory = Path.Combine(outputDirectory, trainingFilesTestOutput); if (!Directory.Exists(outputDirectory)) { Directory.CreateDirectory(outputDirectory); } fileList = new List <string>(benchmark.getTrainingFilesPathList()); foreach (string trainingFileName in fileList) { DateTime start = DateTime.Now; string outputPath = Path.Combine(outputDirectory, Path.GetFileNameWithoutExtension(trainingFileName)); Console.WriteLine((index + 1) + "/" + fileList.Count + " Testing file: " + Path.GetFileName(trainingFileName)); ImageDescription inputImage = ImageFileHandler.loadFromPath(trainingFileName); List <ContextualMemoryNestedAlgorithmLayer> layers = nestedAlgorithm.getLayers(); List <ImageDescription> computedImages = nestedAlgorithm.computeImageForLayers(inputImage, layers.Count); for (int i = 0; i < layers.Count; i++) { if (layers[i].outputResults) { ImageFileHandler.saveToPath(computedImages[i], outputPath + "_layer" + i, outputFileExtension); } } ImageDescription outputImage = nestedAlgorithm.getImageBlender().blendImages(computedImages); ImageFileHandler.saveToPath(outputImage, outputPath, outputFileExtension); index++; double timeElapsed = (DateTime.Now - start).TotalSeconds; Console.WriteLine(timeElapsed.ToString("0.00") + " seconds"); } totalTimeElapsed = (DateTime.Now - testingStart).TotalSeconds; Console.WriteLine("Testing on training files took " + totalTimeElapsed.ToString("0.00") + " sec."); } }
internal void InitializeFrom(Image image) { // TODO: Invalidate original image? pixelBuffers = image.pixelBuffers; dataBoxArray = image.dataBoxArray; mipMapToZIndex = image.mipMapToZIndex; zBufferCountPerArraySlice = image.zBufferCountPerArraySlice; mipmapDescriptions = image.mipmapDescriptions; pixelBufferArray = image.pixelBufferArray; totalSizeInBytes = image.totalSizeInBytes; buffer = image.buffer; bufferIsDisposable = image.bufferIsDisposable; handle = image.handle; Description = image.Description; }
public void validate() { DateTime validateStart = DateTime.Now; List <String> fileList = benchmark.getTestFilesPathList(); float totalCrossEntropy = 0; foreach (string testFilePath in fileList) { DateTime start = DateTime.Now; string outputFilePath = Path.ChangeExtension(benchmark.getTestFileOutputPathWithoutExtension(testFilePath), outputFileExtension); string groundTruthPath = benchmark.getTestingFileGroundTruth(testFilePath); ImageDescription outputImage = ImageFileHandler.loadFromPath(outputFilePath); ImageDescription groundTruthImage = ImageFileHandler.loadFromPath(groundTruthPath); byte[,] outputGray = outputImage.getColorChannel(ColorChannelEnum.Gray); byte[,] groundTruthGray = groundTruthImage.getColorChannel(ColorChannelEnum.Gray); // might be a bug in GDI if (outputGray == null) { outputImage.computeGrayscale(); outputGray = outputImage.getColorChannel(ColorChannelEnum.Gray); } if (groundTruthGray == null) { groundTruthImage.computeGrayscale(); groundTruthGray = groundTruthImage.getColorChannel(ColorChannelEnum.Gray); } float crossEntropy = 0; for (int i = 0; i < outputGray.GetLength(0); i++) { for (int j = 0; j < outputGray.GetLength(1); j++) { byte output = outputGray[i, j]; byte groundTruth = groundTruthGray[i, j]; float groundTruthProbability; float outputProbability; if (groundTruth != 0) { groundTruthProbability = 1.0f; } else { groundTruthProbability = 0; } //groundTruthProbability = groundTruth / 255.0f; if (output == 0) { outputProbability = 1 / 255.0f; } else { if (output == 255) { outputProbability = 254 / 255.0f; } else { outputProbability = output / 255.0f; } } float loss = LogisticHelper.computeEntropyLoss(outputProbability, groundTruthProbability); crossEntropy += loss; } } totalCrossEntropy += crossEntropy; Console.WriteLine(testFilePath); Console.WriteLine("Cross entropy: " + crossEntropy.ToString("0.00")); } Console.WriteLine("Total cross entropy: " + totalCrossEntropy.ToString("0.00")); double totalTimeElapsed = (DateTime.Now - validateStart).TotalSeconds; Console.WriteLine("Validation took " + totalTimeElapsed.ToString("0.00") + " sec."); }
// Simple DDS loader ported from http://msdn.microsoft.com/en-us/library/windows/apps/jj651550.aspx static void CreateTextureFromDDS( SharpDX.Direct3D11.Device d3dDevice, ImageDescription imageDesc, //SharpDX.Toolkit.Graphics.DDS.Header header, //DDS_HEADER* header, IntPtr bitData, //_In_reads_bytes_(bitSize) const byte* bitData, int bitSize, out SharpDX.Direct3D11.Resource texture, //_Out_opt_ ID3D11Resource** texture, out ShaderResourceView textureView //_Out_opt_ ID3D11ShaderResourceView** textureView, ) { int width = imageDesc.Width; int height = imageDesc.Height; int depth = imageDesc.Depth; int arraySize = imageDesc.ArraySize; Format format = imageDesc.Format; bool isCubeMap = imageDesc.Dimension == TextureDimension.TextureCube; int mipCount = imageDesc.MipLevels;// MipMapCount; if (0 == mipCount) { mipCount = 1; } // Create the texture DataBox[] initData = new DataBox[mipCount * arraySize]; //std::unique_ptr<D3D11_SUBRESOURCE_DATA> initData(new D3D11_SUBRESOURCE_DATA[mipCount * arraySize]); int maxsize = 1; if (isCubeMap) { maxsize = SharpDX.Direct3D11.Resource.MaximumTextureCubeSize; } else { maxsize = (imageDesc.Dimension == TextureDimension.Texture3D) ? SharpDX.Direct3D11.Resource.MaximumTexture3DSize : SharpDX.Direct3D11.Resource.MaximumTexture2DSize; } int skipMip = 0; int twidth = 0; int theight = 0; int tdepth = 0; FillInitData(width, height, depth, mipCount, arraySize, format, maxsize, bitSize, bitData, out twidth, out theight, out tdepth, out skipMip, initData); CreateD3DResources(d3dDevice, imageDesc.Dimension, twidth, theight, tdepth, mipCount - skipMip, arraySize, format, isCubeMap, initData, out texture, out textureView); }
public void SetContent(string label, bool useMnemonic, ImageDescription image, ContentPosition position) { Widget.UseUnderline = useMnemonic; this.image = image; if (label != null && label.Length == 0) { label = null; } Button b = (Button)Frontend; if (label != null && image.Backend == null && b.Type == ButtonType.Normal) { Widget.Label = label; return; } if (b.Type == ButtonType.Disclosure) { Widget.Label = null; Widget.Image = new Gtk.Arrow(Gtk.ArrowType.Down, Gtk.ShadowType.Out); Widget.Image.ShowAll(); return; } Gtk.Widget contentWidget = null; Gtk.Widget imageWidget = null; if (image.Backend != null) { imageWidget = new ImageBox(ApplicationContext, image.WithDefaultSize(Gtk.IconSize.Button)); } Gtk.Label labelWidget = null; if (label != null && imageWidget == null) { contentWidget = labelWidget = new Gtk.Label(label); } else if (label == null && imageWidget != null) { contentWidget = imageWidget; } else if (label != null && imageWidget != null) { Gtk.Box box = position == ContentPosition.Left || position == ContentPosition.Right ? (Gtk.Box) new Gtk.HBox(false, 3) : (Gtk.Box) new Gtk.VBox(false, 3); labelWidget = new Gtk.Label(label) { UseUnderline = useMnemonic }; if (position == ContentPosition.Left || position == ContentPosition.Top) { box.PackStart(imageWidget, false, false, 0); box.PackStart(labelWidget, false, false, 0); } else { box.PackStart(labelWidget, false, false, 0); box.PackStart(imageWidget, false, false, 0); } contentWidget = box; } var expandButtonContent = false; if (b.Type == ButtonType.DropDown) { if (contentWidget != null) { Gtk.HBox box = new Gtk.HBox(false, 3); box.PackStart(contentWidget, true, true, 3); box.PackStart(new Gtk.Arrow(Gtk.ArrowType.Down, Gtk.ShadowType.Out), false, false, 0); contentWidget = box; expandButtonContent = true; } else { contentWidget = new Gtk.Arrow(Gtk.ArrowType.Down, Gtk.ShadowType.Out); } } if (contentWidget != null) { contentWidget.ShowAll(); Widget.Label = null; Widget.Image = contentWidget; if (expandButtonContent) { var alignment = Widget.Child as Gtk.Alignment; if (alignment != null) { var box = alignment.Child as Gtk.Box; if (box != null) { alignment.Xscale = 1; box.SetChildPacking(box.Children [0], true, true, 0, Gtk.PackType.Start); if (labelWidget != null) { labelWidget.Xalign = 0; } } } } if (labelWidget != null) { labelWidget.UseUnderline = useMnemonic; if (customFont != null) { labelWidget.ModifyFont(customFont); } } } else { Widget.Label = null; } }
public void SetIcon(ImageDescription icon) { Window.IconList = ((GtkImage)icon.Backend).Frames.Select(f => f.Pixbuf).ToArray(); }
/// <summary> /// Determines metadata for image /// </summary> /// <param name="flags">The flags.</param> /// <param name="decoder">The decoder.</param> /// <param name="frame">The frame.</param> /// <param name="pixelFormat">The pixel format.</param> /// <returns></returns> /// <exception cref="System.InvalidOperationException">If pixel format is not supported.</exception> private static ImageDescription? DecodeMetadata(WICFlags flags, BitmapDecoder decoder, BitmapFrameDecode frame, out Guid pixelFormat) { var size = frame.Size; var metadata = new ImageDescription { Dimension = TextureDimension.Texture2D, Width = size.Width, Height = size.Height, Depth = 1, MipLevels = 1, ArraySize = (flags & WICFlags.AllFrames) != 0 ? decoder.FrameCount : 1, Format = DetermineFormat(frame.PixelFormat, flags, out pixelFormat) }; if (metadata.Format == DXGI.Format.Unknown) return null; return metadata; }
/// <summary> /// Liefert den Hashcode dieser Instanz. /// </summary> /// <returns>Der Hashcode dieser Instanz.</returns> public override int GetHashCode() { return(Articles.GetHashCode() ^ ArticleUrl.GetHashCode() ^ Author.GetHashCode() ^ ImageDescription.GetHashCode() ^ Image.GetHashCode() ^ Language.GetHashCode() ^ Published.GetHashCode() ^ SkipDays.GetHashCode() ^ SkipHours.GetHashCode() ^ TextInput.GetHashCode() ^ TimeToLive.GetHashCode() ^ Title.GetHashCode() ^ Updated.GetHashCode() ^ Version.GetHashCode() ^ WebMaster.GetHashCode()); }
//------------------------------------------------------------------------------------- // Decodes an image array, resizing/format converting as needed //------------------------------------------------------------------------------------- private static Image DecodeMultiframe(WICFlags flags, ImageDescription metadata, BitmapDecoder decoder) { var image = Image.New(metadata); Guid sourceGuid; if (!ToWIC(metadata.Format, out sourceGuid)) return null; for (int index = 0; index < metadata.ArraySize; ++index) { var pixelBuffer = image.PixelBuffer[index, 0]; using (var frame = decoder.GetFrame(index)) { var pfGuid = frame.PixelFormat; var size = frame.Size; if (pfGuid == sourceGuid) { if (size.Width == metadata.Width && size.Height == metadata.Height) { // This frame does not need resized or format converted, just copy... frame.CopyPixels(pixelBuffer.RowStride, pixelBuffer.DataPointer, pixelBuffer.BufferStride); } else { // This frame needs resizing, but not format converted using (var scaler = new BitmapScaler(Factory)) { scaler.Initialize(frame, metadata.Width, metadata.Height, GetWICInterp(flags)); scaler.CopyPixels(pixelBuffer.RowStride, pixelBuffer.DataPointer, pixelBuffer.BufferStride); } } } else { // This frame required format conversion using (var converter = new FormatConverter(Factory)) { converter.Initialize(frame, pfGuid, GetWICDither(flags), null, 0, BitmapPaletteType.Custom); if (size.Width == metadata.Width && size.Height == metadata.Height) { converter.CopyPixels(pixelBuffer.RowStride, pixelBuffer.DataPointer, pixelBuffer.BufferStride); } else { // This frame needs resizing, but not format converted using (var scaler = new BitmapScaler(Factory)) { scaler.Initialize(frame, metadata.Width, metadata.Height, GetWICInterp(flags)); scaler.CopyPixels(pixelBuffer.RowStride, pixelBuffer.DataPointer, pixelBuffer.BufferStride); } } } } } } return image; }
public static void SaveJpgFromMemory(PixelBuffer[] pixelBuffers, int count, ImageDescription description, Stream imageStream) { SaveFromMemory(pixelBuffers, count, description, imageStream, ImageFormat.Jpeg); }
public static void SaveWmpToWICMemory(PixelBuffer[] pixelBuffers, int count, ImageDescription description, Stream imageStream) { SaveToWICMemory(pixelBuffers, 1, WICFlags.None, ImageFileType.Wmp, imageStream); }
public float train(List <ImageDescription> inputImages, ImageDescription inputImageGroundTruth) { return(0); }
public void Draw(ApplicationContext actx, Cairo.Context ctx, double scaleFactor, double x, double y, ImageDescription idesc) { if (stockId != null) { ImageFrame frame = null; if (frames != null) { frame = frames.FirstOrDefault(f => f.Width == (int)idesc.Size.Width && f.Height == (int)idesc.Size.Height && f.Scale == scaleFactor); } if (frame == null) { frame = new ImageFrame(ImageHandler.CreateBitmap(stockId, idesc.Size.Width, idesc.Size.Height, scaleFactor), (int)idesc.Size.Width, (int)idesc.Size.Height, false); frame.Scale = scaleFactor; AddFrame(frame); } DrawPixbuf(ctx, frame.Pixbuf, x, y, idesc); } else if (drawCallback != null) { CairoContextBackend c = new CairoContextBackend(scaleFactor) { Context = ctx }; if (actx != null) { actx.InvokeUserCode(delegate { drawCallback(c, new Rectangle(x, y, idesc.Size.Width, idesc.Size.Height), idesc, actx.Toolkit); }); } else { drawCallback(c, new Rectangle(x, y, idesc.Size.Width, idesc.Size.Height), idesc, Toolkit.CurrentEngine); } } else { DrawPixbuf(ctx, GetBestFrame(actx, scaleFactor, idesc.Size.Width, idesc.Size.Height, false), x, y, idesc); } }
//------------------------------------------------------------------------------------- // Decodes a single frame //------------------------------------------------------------------------------------- private static Image DecodeSingleFrame(WICFlags flags, ImageDescription metadata, Guid convertGUID, BitmapFrameDecode frame) { var image = Image.New(metadata); var pixelBuffer = image.PixelBuffer[0]; if (convertGUID == Guid.Empty) { frame.CopyPixels(pixelBuffer.RowStride, pixelBuffer.DataPointer, pixelBuffer.BufferStride); } else { using (var converter = new FormatConverter(Factory)) { converter.Initialize(frame, convertGUID, GetWICDither(flags), null, 0, BitmapPaletteType.Custom); converter.CopyPixels(pixelBuffer.RowStride, pixelBuffer.DataPointer, pixelBuffer.BufferStride); } } return image; }
//// GET api/<controller> //public IEnumerable<string> Get(string filter, int toId = 0) //{ // return _repository.TestGetAll().Where(s => s.ToUpper().Contains(filter.ToUpper())).Skip(toId).ToList(); //} //// GET api/<controller>/5 //public string Get(int id) //{ // return "value"; //} // POST api/<controller> public void Post(ImageDescription value) { _repository.AddImageDescription(value.ImageId, value.Description); }
public static void SaveTiffToWICMemory(PixelBuffer[] pixelBuffers, int count, ImageDescription description, Stream imageStream) { SaveToWICMemory(pixelBuffers, count, WICFlags.AllFrames, ImageFileType.Tiff, imageStream); }
public override void DrawImage(object backend, ImageDescription img, double x, double y) { }
public static void SavePngFromMemory(PixelBuffer[] pixelBuffers, int count, ImageDescription description, Stream imageStream) { WICHelper.SavePngToWICMemory(pixelBuffers, count, description, imageStream); }
public override void DrawImage(object backend, ImageDescription img, Rectangle srcRect, Rectangle destRect) { }
public static void SaveWmpFromMemory(PixelBuffer[] pixelBuffers, int count, ImageDescription description, Stream imageStream) { throw new NotImplementedException(); }
public override object Create(ImageDescription img) { return(new ImagePattern(ApplicationContext, img)); }
/// <summary> /// Allocates PixelBuffers /// </summary> /// <param name="buffer"></param> /// <param name="pixelSize"></param> /// <param name="imageDesc"></param> /// <param name="pitchFlags"></param> /// <param name="output"></param> private static unsafe void SetupImageArray(IntPtr buffer, int pixelSize, int rowStride, ImageDescription imageDesc, PitchFlags pitchFlags, PixelBuffer[] output) { int index = 0; var pixels = (byte*)buffer; for (uint item = 0; item < imageDesc.ArraySize; ++item) { int w = imageDesc.Width; int h = imageDesc.Height; int d = imageDesc.Depth; for (uint level = 0; level < imageDesc.MipLevels; ++level) { int rowPitch, slicePitch; int widthPacked; int heightPacked; ComputePitch(imageDesc.Format, w, h, out rowPitch, out slicePitch, out widthPacked, out heightPacked, pitchFlags); if (rowStride > 0) { // Check that stride is ok if (rowStride < rowPitch) throw new InvalidOperationException(string.Format("Invalid stride [{0}]. Value can't be lower than actual stride [{1}]", rowStride, rowPitch)); if (widthPacked != w || heightPacked != h) throw new InvalidOperationException("Custom strides is not supported with packed PixelFormats"); // Override row pitch rowPitch = rowStride; // Recalculate slice pitch slicePitch = rowStride * h; } for (uint zSlice = 0; zSlice < d; ++zSlice) { // We use the same memory organization that Direct3D 11 needs for D3D11_SUBRESOURCE_DATA // with all slices of a given miplevel being continuous in memory output[index] = new PixelBuffer(w, h, imageDesc.Format, rowPitch, slicePitch, (IntPtr)pixels); ++index; pixels += slicePitch; } if (h > 1) h >>= 1; if (w > 1) w >>= 1; if (d > 1) d >>= 1; } } }
public ImagePattern(ApplicationContext actx, ImageDescription im) { this.actx = actx; this.image = im; }
/// <summary> /// Creates a new instance of <see cref="Image"/> from an image description. /// </summary> /// <param name="description">The image description.</param> /// <returns>A new image.</returns> public static Image New(ImageDescription description) { return New(description, IntPtr.Zero); }
private static void DeserializeTexture(ContentManager contentManager, Texture texture, ref ImageDescription imageDescription, ref ContentStorageHeader storageHeader) { using (var content = new ContentStreamingService()) { // Get content storage container var storage = content.GetStorage(ref storageHeader); if (storage == null) { throw new ContentStreamingException("Missing content storage."); } storage.LockChunks(); // Cache data var fileProvider = contentManager.FileProvider; var format = imageDescription.Format; bool isBlockCompressed = (format >= PixelFormat.BC1_Typeless && format <= PixelFormat.BC5_SNorm) || (format >= PixelFormat.BC6H_Typeless && format <= PixelFormat.BC7_UNorm_SRgb); var dataBoxes = new DataBox[imageDescription.MipLevels * imageDescription.ArraySize]; int dataBoxIndex = 0; // Get data boxes data for (int arrayIndex = 0; arrayIndex < imageDescription.ArraySize; arrayIndex++) { for (int mipIndex = 0; mipIndex < imageDescription.MipLevels; mipIndex++) { int mipWidth = imageDescription.Width >> mipIndex; int mipHeight = imageDescription.Height >> mipIndex; if (isBlockCompressed && ((mipWidth % 4) != 0 || (mipHeight % 4) != 0)) { mipWidth = unchecked ((int)(((uint)(mipWidth + 3)) & ~3U)); mipHeight = unchecked ((int)(((uint)(mipHeight + 3)) & ~3U)); } int rowPitch, slicePitch; int widthPacked; int heightPacked; Image.ComputePitch(format, mipWidth, mipHeight, out rowPitch, out slicePitch, out widthPacked, out heightPacked); var chunk = storage.GetChunk(mipIndex); if (chunk == null || chunk.Size != slicePitch * imageDescription.ArraySize) { throw new ContentStreamingException("Data chunk is missing or has invalid size.", storage); } var data = chunk.GetData(fileProvider); if (!chunk.IsLoaded) { throw new ContentStreamingException("Data chunk is not loaded.", storage); } dataBoxes[dataBoxIndex].DataPointer = data + slicePitch * arrayIndex; dataBoxes[dataBoxIndex].RowPitch = rowPitch; dataBoxes[dataBoxIndex].SlicePitch = slicePitch; dataBoxIndex++; } } // Initialize texture texture.InitializeFrom(imageDescription, new TextureViewDescription(), dataBoxes); storage.UnlockChunks(); } }
/// <summary> /// Initializes a new instance of the <see cref="Image" /> class. /// </summary> /// <param name="description">The image description.</param> /// <param name="dataPointer">The pointer to the data buffer.</param> /// <param name="offset">The offset from the beginning of the data buffer.</param> /// <param name="handle">The handle (optionnal).</param> /// <param name="bufferIsDisposable">if set to <c>true</c> [buffer is disposable].</param> /// <exception cref="System.InvalidOperationException">If the format is invalid, or width/height/depth/arraysize is invalid with respect to the dimension.</exception> public static Image New(ImageDescription description, IntPtr dataPointer, int offset, GCHandle? handle, bool bufferIsDisposable) { return new Image(description, dataPointer, offset, handle, bufferIsDisposable); }
internal static void Serialize(ArchiveMode mode, SerializationStream stream, Texture texture, bool allowContentStreaming) { if (mode == ArchiveMode.Deserialize) { var services = stream.Context.Tags.Get(ServiceRegistry.ServiceRegistryKey); var graphicsDeviceService = services.GetSafeServiceAs <IGraphicsDeviceService>(); var texturesStreamingProvider = services.GetService <ITexturesStreamingProvider>(); var isStreamable = stream.ReadBoolean(); if (!isStreamable) { texturesStreamingProvider?.UnregisterTexture(texture); // TODO: Error handling? using (var textureData = Image.Load(stream.NativeStream)) { if (texture.GraphicsDevice != null) { texture.OnDestroyed(); //Allows fast reloading todo review maybe? } texture.AttachToGraphicsDevice(graphicsDeviceService.GraphicsDevice); texture.InitializeFrom(textureData.Description, new TextureViewDescription(), textureData.ToDataBox()); // Setup reload callback (reload from asset manager) var contentSerializerContext = stream.Context.Get(ContentSerializerContext.ContentSerializerContextProperty); if (contentSerializerContext != null) { var assetManager = contentSerializerContext.ContentManager; var url = contentSerializerContext.Url; texture.Reload = (graphicsResource) => { var textureDataReloaded = assetManager.Load <Image>(url); ((Texture)graphicsResource).Recreate(textureDataReloaded.ToDataBox()); assetManager.Unload(textureDataReloaded); }; } } } else { if (texture.GraphicsDevice != null) { texture.OnDestroyed(); } texture.AttachToGraphicsDevice(graphicsDeviceService.GraphicsDevice); texture.Reload = null; // Read image header var imageDescription = new ImageDescription(); ImageHelper.ImageDescriptionSerializer.Serialize(ref imageDescription, ArchiveMode.Deserialize, stream); // Read content storage header ContentStorageHeader storageHeader; ContentStorageHeader.Read(stream, out storageHeader); // Check if streaming service is available if (texturesStreamingProvider != null) { if (allowContentStreaming) { // Register texture for streaming texturesStreamingProvider.RegisterTexture(texture, ref imageDescription, ref storageHeader); // Note: here we don't load texture data and don't allocate GPU memory } else { // Request texture loading (should be fully loaded) texturesStreamingProvider.FullyLoadTexture(texture, ref imageDescription, ref storageHeader); } // Load initial texture (with limited number of mipmaps) using (var textureData = Image.Load(stream.NativeStream)) { if (texture.GraphicsDevice != null) { texture.OnDestroyed(); //Allows fast reloading todo review maybe? } texture.InitializeFrom(textureData.Description, new TextureViewDescription(), textureData.ToDataBox()); } } else { // Load initial texture and discard it (we are going to load the full chunk texture right after) using (var textureData = Image.Load(stream.NativeStream)) { } // Deserialize whole texture without streaming feature var contentSerializerContext = stream.Context.Get(ContentSerializerContext.ContentSerializerContextProperty); DeserializeTexture(contentSerializerContext.ContentManager, texture, ref imageDescription, ref storageHeader); } } } else { var textureData = texture.GetSerializationData(); if (textureData == null) { throw new InvalidOperationException("Trying to serialize a Texture without CPU info."); } textureData.Write(stream); } }
internal unsafe void Initialize(ImageDescription description, IntPtr dataPointer, int offset, GCHandle? handle, bool bufferIsDisposable, PitchFlags pitchFlags = PitchFlags.None, int rowStride = 0) { if (!description.Format.IsValid() || description.Format.IsVideo()) throw new InvalidOperationException("Unsupported DXGI Format"); if (rowStride > 0 && description.MipLevels != 1) throw new InvalidOperationException("Cannot specify custom stride with mipmaps"); this.handle = handle; switch (description.Dimension) { case TextureDimension.Texture1D: if (description.Width <= 0 || description.Height != 1 || description.Depth != 1 || description.ArraySize == 0) throw new InvalidOperationException("Invalid Width/Height/Depth/ArraySize for Image 1D"); // Check that miplevels are fine description.MipLevels = CalculateMipLevels(description.Width, 1, description.MipLevels); break; case TextureDimension.Texture2D: case TextureDimension.TextureCube: if (description.Width <= 0 || description.Height <= 0 || description.Depth != 1 || description.ArraySize == 0) throw new InvalidOperationException("Invalid Width/Height/Depth/ArraySize for Image 2D"); if (description.Dimension == TextureDimension.TextureCube) { if ((description.ArraySize % 6) != 0) throw new InvalidOperationException("TextureCube must have an arraysize = 6"); } // Check that miplevels are fine description.MipLevels = CalculateMipLevels(description.Width, description.Height, description.MipLevels); break; case TextureDimension.Texture3D: if (description.Width <= 0 || description.Height <= 0 || description.Depth <= 0 || description.ArraySize != 1) throw new InvalidOperationException("Invalid Width/Height/Depth/ArraySize for Image 3D"); // Check that miplevels are fine description.MipLevels = CalculateMipLevels(description.Width, description.Height, description.Depth, description.MipLevels); break; } // Calculate mipmaps int pixelBufferCount; this.mipMapToZIndex = CalculateImageArray(description, pitchFlags, rowStride, out pixelBufferCount, out totalSizeInBytes); this.mipmapDescriptions = CalculateMipMapDescription(description, pitchFlags); zBufferCountPerArraySlice = this.mipMapToZIndex[this.mipMapToZIndex.Count - 1]; // Allocate all pixel buffers pixelBuffers = new PixelBuffer[pixelBufferCount]; pixelBufferArray = new PixelBufferArray(this); // Setup all pointers // only release buffer that is not pinned and is asked to be disposed. this.bufferIsDisposable = !handle.HasValue && bufferIsDisposable; this.buffer = dataPointer; if (dataPointer == IntPtr.Zero) { buffer = Utilities.AllocateMemory(totalSizeInBytes); offset = 0; this.bufferIsDisposable = true; } SetupImageArray((IntPtr)((byte*)buffer + offset), totalSizeInBytes, rowStride, description, pitchFlags, pixelBuffers); Description = description; // PreCompute databoxes dataBoxArray = ComputeDataBox(); }
public void SetContent(string label, bool useMnemonic, ImageDescription image, ContentPosition position) { SetContent(label, useMnemonic, image, position, false); }
internal static MipMapDescription[] CalculateMipMapDescription(ImageDescription metadata, PitchFlags cpFlags = PitchFlags.None) { int nImages; int pixelSize; return CalculateMipMapDescription(metadata, cpFlags, out nImages, out pixelSize); }
void SetContent(string label, bool useMnemonic, ImageDescription image, ContentPosition position, bool forceCustomLabel) { Widget.UseUnderline = useMnemonic; this.image = image; contentPosition = position; formattedText = null; if (label != null && label.Length == 0) { label = null; } Button b = (Button)Frontend; if (label != null && image.Backend == null && b.Type == ButtonType.Normal && !forceCustomLabel) { Widget.Label = label; return; } if (b.Type == ButtonType.Disclosure) { Widget.Label = null; Widget.Image = new Gtk.Arrow(Gtk.ArrowType.Down, Gtk.ShadowType.Out); Widget.Image.ShowAll(); return; } Gtk.Widget contentWidget = null; Gtk.Widget imageWidget = null; if (image.Backend != null) { imageWidget = new ImageBox(ApplicationContext, image.WithDefaultSize(Gtk.IconSize.Button)); } if (labelWidget != null) { labelWidget.Realized -= HandleStyleUpdate; labelWidget.StyleSet -= HandleStyleUpdate; labelWidget = null; } if (label != null && imageWidget == null) { contentWidget = labelWidget = new Gtk.Label(label); } else if (label == null && imageWidget != null) { contentWidget = imageWidget; } else if (label != null && imageWidget != null) { Gtk.Box box = position == ContentPosition.Left || position == ContentPosition.Right ? (Gtk.Box) new Gtk.HBox(false, 3) : (Gtk.Box) new Gtk.VBox(false, 3); labelWidget = new Gtk.Label(label) { UseUnderline = useMnemonic }; if (position == ContentPosition.Left || position == ContentPosition.Top) { box.PackStart(imageWidget, false, false, 0); box.PackStart(labelWidget, false, false, 0); } else { box.PackStart(labelWidget, false, false, 0); box.PackStart(imageWidget, false, false, 0); } contentWidget = box; } var expandButtonContent = false; if (b.Type == ButtonType.DropDown) { if (contentWidget != null) { Gtk.HBox box = new Gtk.HBox(false, 3); box.PackStart(contentWidget, true, true, 3); box.PackStart(new Gtk.Arrow(Gtk.ArrowType.Down, Gtk.ShadowType.Out), false, false, 0); contentWidget = box; expandButtonContent = true; } else { contentWidget = new Gtk.Arrow(Gtk.ArrowType.Down, Gtk.ShadowType.Out); } } if (contentWidget != null) { contentWidget.ShowAll(); Widget.Label = null; Widget.Image = contentWidget; var alignment = Widget.Child as Gtk.Alignment; if (alignment != null) { if (expandButtonContent) { var box = alignment.Child as Gtk.Box; if (box != null) { alignment.Xscale = 1; box.SetChildPacking(box.Children [0], true, true, 0, Gtk.PackType.Start); if (labelWidget != null) { labelWidget.Xalign = 0; } } } else if (position == ContentPosition.Left && (contentWidget is Gtk.Box)) { // in case the button is wider than its natural size and has text and an image on the left, // optimize its alignment to make the text more centered. // FIXME: more sophisticated size calculation alignment.Xalign = 0.475f; } } if (labelWidget != null) { labelWidget.UseUnderline = useMnemonic; if (customFont != null) { labelWidget.ModifyFont(customFont); } if (customLabelColor.HasValue) { labelWidget.SetForegroundColor(customLabelColor.Value); labelWidget.SetForegroundColor(Gtk.StateType.Prelight, customLabelColor.Value); } } } else { Widget.Label = null; } }
/// <summary> /// Determines number of image array entries and pixel size. /// </summary> /// <param name="imageDesc">Description of the image to create.</param> /// <param name="pitchFlags">Pitch flags.</param> /// <param name="bufferCount">Output number of mipmap.</param> /// <param name="pixelSizeInBytes">Output total size to allocate pixel buffers for all images.</param> private static List<int> CalculateImageArray( ImageDescription imageDesc, PitchFlags pitchFlags, int rowStride, out int bufferCount, out int pixelSizeInBytes) { pixelSizeInBytes = 0; bufferCount = 0; var mipmapToZIndex = new List<int>(); for (int j = 0; j < imageDesc.ArraySize; j++) { int w = imageDesc.Width; int h = imageDesc.Height; int d = imageDesc.Depth; for (int i = 0; i < imageDesc.MipLevels; i++) { int rowPitch, slicePitch; int widthPacked; int heightPacked; ComputePitch(imageDesc.Format, w, h, out rowPitch, out slicePitch, out widthPacked, out heightPacked, pitchFlags); if (rowStride > 0) { // Check that stride is ok if (rowStride < rowPitch) throw new InvalidOperationException(string.Format("Invalid stride [{0}]. Value can't be lower than actual stride [{1}]", rowStride, rowPitch)); if (widthPacked != w || heightPacked != h) throw new InvalidOperationException("Custom strides is not supported with packed PixelFormats"); // Override row pitch rowPitch = rowStride; // Recalculate slice pitch slicePitch = rowStride * h; } // Store the number of z-slicec per miplevels if ( j == 0) mipmapToZIndex.Add(bufferCount); // Keep a trace of indices for the 1st array size, for each mip levels pixelSizeInBytes += d * slicePitch; bufferCount += d; if (h > 1) h >>= 1; if (w > 1) w >>= 1; if (d > 1) d >>= 1; } // For the last mipmaps, store just the number of zbuffers in total if (j == 0) mipmapToZIndex.Add(bufferCount); } return mipmapToZIndex; }
public void SetImage(ImageDescription image) { image = image.WithDefaultSize(Gtk.IconSize.Menu); statusItem.Pixbuf = ((GtkImage)image.Backend).GetBestFrame(context, Util.GetDefaultScaleFactor(), image.Size.Width, image.Size.Height, true); }
/// <summary> /// Decodes DDS header including optional DX10 extended header /// </summary> /// <param name="headerPtr">Pointer to the DDS header.</param> /// <param name="size">Size of the DDS content.</param> /// <param name="flags">Flags used for decoding the DDS header.</param> /// <param name="description">Output texture description.</param> /// <param name="convFlags">Output conversion flags.</param> /// <exception cref="ArgumentException">If the argument headerPtr is null</exception> /// <exception cref="InvalidOperationException">If the DDS header contains invalid datas.</exception> /// <returns>True if the decoding is successfull, false if this is not a DDS header.</returns> private static unsafe bool DecodeDDSHeader(IntPtr headerPtr, int size, DDSFlags flags, out ImageDescription description, out ConversionFlags convFlags) { description = new ImageDescription(); convFlags = ConversionFlags.None; if (headerPtr == IntPtr.Zero) throw new ArgumentException("Pointer to DDS header cannot be null", "headerPtr"); if (size < (Utilities.SizeOf<DDS.Header>() + sizeof(uint))) return false; // DDS files always start with the same magic number ("DDS ") if (*(uint*)(headerPtr) != DDS.MagicHeader) return false; var header = *(DDS.Header*)((byte*)headerPtr + sizeof(int)); // Verify header to validate DDS file if (header.Size != Utilities.SizeOf<DDS.Header>() || header.PixelFormat.Size != Utilities.SizeOf<DDS.PixelFormat>()) return false; // Setup MipLevels description.MipLevels = header.MipMapCount; if (description.MipLevels == 0) description.MipLevels = 1; // Check for DX10 extension if ((header.PixelFormat.Flags & DDS.PixelFormatFlags.FourCC) != 0 && (new FourCC('D', 'X', '1', '0') == header.PixelFormat.FourCC)) { // Buffer must be big enough for both headers and magic value if (size < (Utilities.SizeOf<DDS.Header>() + sizeof(uint) + Utilities.SizeOf<DDS.HeaderDXT10>())) return false; var headerDX10 = *(DDS.HeaderDXT10*)((byte*)headerPtr + sizeof(int) + Utilities.SizeOf<DDS.Header>()); convFlags |= ConversionFlags.DX10; description.ArraySize = headerDX10.ArraySize; if (description.ArraySize == 0) throw new InvalidOperationException("Unexpected ArraySize == 0 from DDS HeaderDX10 "); description.Format = headerDX10.DXGIFormat; if (!FormatHelper.IsValid(description.Format)) throw new InvalidOperationException("Invalid Format from DDS HeaderDX10 "); switch (headerDX10.ResourceDimension) { case ResourceDimension.Texture1D: // D3DX writes 1D textures with a fixed Height of 1 if ((header.Flags & DDS.HeaderFlags.Height) != 0 && header.Height != 1) throw new InvalidOperationException("Unexpected Height != 1 from DDS HeaderDX10 "); description.Width = header.Width; description.Height = 1; description.Depth = 1; description.Dimension = TextureDimension.Texture1D; break; case ResourceDimension.Texture2D: if ((headerDX10.MiscFlags & ResourceOptionFlags.TextureCube) != 0) { description.ArraySize *= 6; description.Dimension = TextureDimension.TextureCube; } else { description.Dimension = TextureDimension.Texture2D; } description.Width = header.Width; description.Height = header.Height; description.Depth = 1; break; case ResourceDimension.Texture3D: if ((header.Flags & DDS.HeaderFlags.Volume) == 0) throw new InvalidOperationException("Texture3D missing HeaderFlags.Volume from DDS HeaderDX10"); if (description.ArraySize > 1) throw new InvalidOperationException("Unexpected ArraySize > 1 for Texture3D from DDS HeaderDX10"); description.Width = header.Width; description.Height = header.Height; description.Depth = header.Depth; description.Dimension = TextureDimension.Texture3D; break; default: throw new InvalidOperationException(string.Format("Unexpected dimension [{0}] from DDS HeaderDX10", headerDX10.ResourceDimension)); } } else { description.ArraySize = 1; if ((header.Flags & DDS.HeaderFlags.Volume) != 0) { description.Width = header.Width; description.Height = header.Height; description.Depth = header.Depth; description.Dimension = TextureDimension.Texture3D; } else { if ((header.CubemapFlags & DDS.CubemapFlags.CubeMap) != 0) { // We require all six faces to be defined if ((header.CubemapFlags & DDS.CubemapFlags.AllFaces) != DDS.CubemapFlags.AllFaces) throw new InvalidOperationException("Unexpected CubeMap, expecting all faces from DDS Header"); description.ArraySize = 6; description.Dimension = TextureDimension.TextureCube; } else { description.Dimension = TextureDimension.Texture2D; } description.Width = header.Width; description.Height = header.Height; description.Depth = 1; // Note there's no way for a legacy Direct3D 9 DDS to express a '1D' texture } description.Format = GetDXGIFormat(ref header.PixelFormat, flags, out convFlags); if (description.Format == Format.Unknown) throw new InvalidOperationException("Unsupported PixelFormat from DDS Header"); } // Special flag for handling BGR DXGI 1.1 formats if ((flags & DDSFlags.ForceRgb) != 0) { switch ((Format)description.Format) { case Format.B8G8R8A8_UNorm: description.Format = Format.R8G8B8A8_UNorm; convFlags |= ConversionFlags.Swizzle; break; case Format.B8G8R8X8_UNorm: description.Format = Format.R8G8B8A8_UNorm; convFlags |= ConversionFlags.Swizzle | ConversionFlags.NoAlpha; break; case Format.B8G8R8A8_Typeless: description.Format = Format.R8G8B8A8_Typeless; convFlags |= ConversionFlags.Swizzle; break; case Format.B8G8R8A8_UNorm_SRgb: description.Format = Format.R8G8B8A8_UNorm_SRgb; convFlags |= ConversionFlags.Swizzle; break; case Format.B8G8R8X8_Typeless: description.Format = Format.R8G8B8A8_Typeless; convFlags |= ConversionFlags.Swizzle | ConversionFlags.NoAlpha; break; case Format.B8G8R8X8_UNorm_SRgb: description.Format = Format.R8G8B8A8_UNorm_SRgb; convFlags |= ConversionFlags.Swizzle | ConversionFlags.NoAlpha; break; } } // Pass DDSFlags copy memory to the conversion flags if ((flags & DDSFlags.CopyMemory) != 0) convFlags |= ConversionFlags.CopyMemory; // Special flag for handling 16bpp formats if ((flags & DDSFlags.No16Bpp) != 0) { switch ((Format)description.Format) { case Format.B5G6R5_UNorm: case Format.B5G5R5A1_UNorm: case Format.B4G4R4A4_UNorm: description.Format = Format.R8G8B8A8_UNorm; convFlags |= ConversionFlags.Expand; if (description.Format == Format.B5G6R5_UNorm) convFlags |= ConversionFlags.NoAlpha; break; } } return true; }
public void SetIcon(ImageDescription imageBackend) { window.Icon = imageBackend.ToImageSource(); }