Beispiel #1
0
        /// <summary>
        ///
        /// </summary>
        public void UpdateRectangle(IColorMap aColorMap)
        {
            iFillRectangle = new System.Drawing.RectangleF(
                (iLowerLeft.X * iScale.X),
                (iLowerLeft.Y * iScale.Y),
                (iWidth * iScale.X),
                iHeight * iScale.Y);

            if (aColorMap.GetColors().GetLength(0) < iId)
            {
                iId = 0;
            }

            iBrush = new System.Drawing.Drawing2D.LinearGradientBrush(
                iFillRectangle,
                aColorMap.GetColor(iId), Color.Black,
                System.Drawing.Drawing2D.LinearGradientMode.Vertical);
            iGrayBrush = new System.Drawing.Drawing2D.LinearGradientBrush(
                iFillRectangle,
                Color.Gray, Color.Black,
                System.Drawing.Drawing2D.LinearGradientMode.Vertical);


            iBorderRectangle = new System.Drawing.Rectangle(
                (int)Math.Ceiling(iLowerLeft.X * iScale.X),
                (int)Math.Ceiling(iLowerLeft.Y * iScale.Y),
                (int)Math.Ceiling(iWidth * iScale.X),
                (int)Math.Ceiling(iHeight * iScale.Y));
        }
Beispiel #2
0
        // NOTE: This expects colors in SVGs to be specified with hex triplets to be recognized
        static void ApplyColorMap(XmlDocument xmlDocument, IColorMap colorMap)
        {
            foreach (var attr in xmlDocument
                     .SelectNodes("//*")
                     .OfType <XmlElement>()
                     .SelectMany(x => x.Attributes.Cast <XmlAttribute>()))
            {
                var attrValue = attr.Value;
                foreach (var match in _hexColorMatchRegex.Matches(attrValue).Cast <Match>().Reverse())
                {
                    var matchGroup   = match.Groups["color"];
                    var origHexColor = matchGroup.Value;
                    if (origHexColor.Length == 3)
                    {
                        origHexColor = string.Format("{0}{0}{1}{1}{2}{2}", origHexColor[0], origHexColor[1], origHexColor[2]);
                    }

                    var origColor = Color.FromRgb(Convert.ToInt32(origHexColor, 16));
                    var newColor  = colorMap.Map(origColor);
                    if (origColor != newColor)
                    {
                        var newHexColor = string.Format(
                            "{0:x2}{1:x2}{2:x2}",
                            (int)Math.Round(newColor.R * 255.0f),
                            (int)Math.Round(newColor.G * 255.0f),
                            (int)Math.Round(newColor.B * 255.0f));
                        attrValue = attrValue.Remove(matchGroup.Index, matchGroup.Length).Insert(matchGroup.Index, newHexColor);
                    }
                }

                attr.Value = attrValue;
            }
        }
Beispiel #3
0
        public void Initialize(double[] data, int width, int height, IColorTable colorTable, IColorMap colorMap)
        {
            // set members
            _width   = width;
            _height  = height;
            _rawData = data;

            // set default for this
            _invalidPixelValueColor = Color.White;

            // allocate image buffer
            _data = new int[width * height];

            // set color table now, we need it during raw buffer creation
            // TODO: throw if null, initialize?
            _colorTable = colorTable;

            // create color map
            if (colorMap != null)
            {
                _colorMap = colorMap;
            }
            else
            {
                _colorMap = ColorMapFactory.Create(ColorMapTypes.Gray);
                _colorMap.Initialize();
                _colorMap.Bias     = 0.5;
                _colorMap.Contrast = 1;
            }

            // create raw image buffer.
            // separating this will  add more granularity saving time if we want to rebuild
            // since we dont want to recalc extremes again...etc
            CreateRawImageBuffer();
        }
Beispiel #4
0
 public ColorMapper(IColorMap colormap, double zmin, double zmax, Color factor)
 {
     m_colormap = colormap;
     m_zmin     = zmin;
     m_zmax     = zmax;
     m_factor   = factor;
 }
 public CustomAlphaColorMapKey(IColorMap colorMap, byte alpha, bool thresholding)
     : this()
 {
     _colorMap     = colorMap;
     _alpha        = alpha;
     _thresholding = thresholding;
 }
Beispiel #6
0
 public ColorbarImageGenerator(IColorMap map, float min, float max, ITickProvider provider, ITickRenderer renderer)
 {
     _mapper   = new ColorMapper(map, min, max);
     _min      = min;
     _max      = max;
     _provider = provider;
     _renderer = renderer;
 }
Beispiel #7
0
 public void InstallColorMap(string name)
 {
     if (_colorMapName != name)
     {
         _colorMapName = name;
         _colorMap     = null;
     }
 }
Beispiel #8
0
 public void InstallColorMap(IColorMap colorMap)
 {
     if (_colorMap != colorMap)
     {
         _colorMap     = colorMap;
         _colorMapName = null;
     }
 }
Beispiel #9
0
        void IColorMapInstaller.InstallColorMap(IColorMap colorMap)
        {
            if (_colorMap == colorMap)
            {
                return;
            }

            _colorMap = colorMap;
        }
Beispiel #10
0
        public void ResetBiasContrast()
        {
            IColorMap cm = CurrentImage.ColorMap;

            cm.Bias               = 0.5;
            cm.Contrast           = 1;
            CurrentImage.ColorMap = cm;
            RaiseImageChanged();
        }
Beispiel #11
0
        static public IColorMap FromFile(string path)
        {
            IColorMap cm = null;
            XmlReader r  = null;

            try
            {
                r = XmlReader.Create(path);
                r.ReadToFollowing("ColorMap");
                double bias     = double.Parse(r["Bias"]);
                double contrast = double.Parse(r["Contrast"]);
                string type     = r["Type"];
                switch (type)
                {
                case "RGBFile":
                    r.ReadToDescendant("RGB");
                    StringReader sr = new StringReader(r.ReadString());
                    cm = new FileColorMap(sr);
                    sr.Close();
                    break;

                case "Advanced":
                    // skip LIP tag
                    r.ReadToDescendant("LIP");
                    r.ReadToDescendant("Red");
                    string red = r.ReadString();
                    r.ReadToNextSibling("Green");
                    string green = r.ReadString();
                    r.ReadToNextSibling("Blue");
                    string blue = r.ReadString();
                    cm = new CustomLIColorMap(red, green, blue);
                    break;

                default:
                    cm = Create((ColorMapTypes)Enum.Parse(typeof(ColorMapTypes), r["Type"], true), null);
                    break;
                }
                if (cm != null)
                {
                    cm.Initialize();
                    cm.Bias     = bias;
                    cm.Contrast = contrast;
                }
            }
            finally
            {
                if (r != null)
                {
                    r.Close();
                }
            }
            return(cm);
        }
Beispiel #12
0
        private static int[] ConstructFinalLut(IComposedLut outputLut, IColorMap colorMap, bool invert)
        {
            CodeClock clock = new CodeClock();

            clock.Start();

            colorMap.MinInputValue = outputLut.MinOutputValue;
            colorMap.MaxInputValue = outputLut.MaxOutputValue;

            int[] outputLutData = outputLut.Data;
            int[] colorMapData  = colorMap.Data;

            if (_finalLutBuffer == null || _finalLutBuffer.Length != outputLutData.Length)
            {
                _finalLutBuffer = new int[outputLutData.Length];
            }

            int numberOfEntries = _finalLutBuffer.Length;

            fixed(int *pOutputLutData = outputLutData)
            {
                fixed(int *pColorMapData = colorMapData)
                {
                    fixed(int *pFinalLutData = _finalLutBuffer)
                    {
                        int *pFinalLut = pFinalLutData;

                        if (!invert)
                        {
                            int firstColorMappedPixelValue = colorMap.FirstMappedPixelValue;
                            for (int i = 0; i < numberOfEntries; ++i)
                            {
                                *(pFinalLut++) = pColorMapData[*(pOutputLutData + i) - firstColorMappedPixelValue];
                            }
                        }
                        else
                        {
                            int lastColorMappedPixelValue = colorMap.FirstMappedPixelValue + colorMap.Data.Length - 1;
                            for (int i = 0; i < numberOfEntries; ++i)
                            {
                                *(pFinalLut++) = pColorMapData[lastColorMappedPixelValue - *(pOutputLutData + i)];
                            }
                        }
                    }
                }
            }

            clock.Stop();
            PerformanceReportBroker.PublishReport("ImageRenderer", "ConstructFinalLut", clock.Seconds);

            return(_finalLutBuffer);
        }
Beispiel #13
0
        static void DoCreateImage(IDensityMatrix matrix)
        {
            Logger.PrintInfo("matrix = [" + matrix.Width + "x" + matrix.Height + " " + matrix.Maximum + "]");
            IColorMap cm = GetColorMap(out string _);

            using (var img = new MagicCanvas(Options.Width, Options.Height))
            {
                Logger.PrintInfo("building image");
                PaintImageData(matrix, cm, img);

                SaveCanvas(img);
            }
        }
Beispiel #14
0
        static void CreateColorMapTest()
        {
            IColorMap cmap = GetColorMap(out string name);

            using (var img = new MagicCanvas(Options.Width, Options.Height))
            {
                for (int x = 0; x < Options.Width; x++)
                {
                    ColorD c = cmap.GetColor(x, Options.Width);
                    img.DrawLine(c, x, 0, x, Options.Height - 1);
                }
                img.SavePng("ColorMapTest-" + name + ".png");
            }
        }
Beispiel #15
0
 public ForegroundTextTransformation(
     IColorMap colorMap,
     Action <Exception> exceptionHandler,
     int startOffset,
     int endOffset,
     int foreground,
     int background,
     int fontStyle) : base(startOffset, endOffset)
 {
     _colorMap         = colorMap;
     _exceptionHandler = exceptionHandler;
     _foreground       = foreground;
     _background       = background;
     _fontStyle        = fontStyle;
 }
Beispiel #16
0
        /// <summary>
        /// Initializes a new instance of the ToastTileCreator class.
        /// </summary>
        /// <param name="map">
        /// Color map.
        /// </param>
        /// <param name="serializer">
        /// Tile serializer.
        /// </param>
        public ToastTileCreator(IColorMap map, IImageTileSerializer serializer)
        {
            if (map == null)
            {
                throw new ArgumentNullException("map");
            }

            if (serializer == null)
            {
                throw new ArgumentNullException("serializer");
            }

            this.ColorMap       = map;
            this.TileSerializer = serializer;
        }
        private static void SetFusionDisplayParameters(IPresentationImage image, IColorMap colorMap, float opacity, bool thresholding)
        {
            if (image is IColorMapProvider)
            {
                var colorMapProvider = (IColorMapProvider)image;
                colorMapProvider.ColorMapManager.InstallColorMap(colorMap);
            }

            if (image is ILayerOpacityProvider)
            {
                var layerOpacityProvider = (ILayerOpacityProvider)image;
                layerOpacityProvider.LayerOpacityManager.Thresholding = thresholding;
                layerOpacityProvider.LayerOpacityManager.Opacity      = opacity;
            }
        }
        /// <summary>
        /// Initializes a new instance of the MercatorTileCreator class.
        /// </summary>
        /// <param name="map">
        /// Color map.
        /// </param>
        /// <param name="serializer">
        /// Tile serializer.
        /// </param>
        public MercatorTileCreator(IColorMap map, IImageTileSerializer serializer)
        {
            if (map == null)
            {
                throw new ArgumentNullException("map");
            }

            if (serializer == null)
            {
                throw new ArgumentNullException("serializer");
            }

            this.ColorMap = map;
            this.TileSerializer = serializer;
        }
Beispiel #19
0
        public void LoadColorMap(string file)
        {
            _modelState.ColorMap.Param = "";
            IColorMap cm = ColorMapFactory.FromFile(file);

            if (cm != null)
            {
                _modelState.ColorMap.Type = cm.Type;
                if (CurrentImage != null)
                {
                    CurrentImage.ColorMap = cm;
                    RaiseImageChanged();
                }
            }
        }
Beispiel #20
0
        public static IColorMap ProcessFilters(IColorMap map, IEnumerable<IFilter> filters)
        {
            IColorMap currentMap = map;
            foreach (var filter in filters)
            {
                if (filter == null)
                    throw new ArgumentNullException(nameof(filter));

                var newmap = filter.CreateResultMap(currentMap);
                filter.ProcessMap(currentMap, newmap);
                if (newmap != currentMap && currentMap != map) currentMap.Dispose();
                currentMap = newmap;
            }
            return currentMap;
        }
Beispiel #21
0
        /// <summary>
        /// Initializes a new instance of the MaskedTileCreator class.
        /// </summary>
        /// <param name="map">
        /// Color map.
        /// </param>
        /// <param name="serializer">
        /// Tile serializer.
        /// </param>
        /// <param name="lookAtOutsideSurface">
        /// True if the projection is from outside the sphere, False if it's from inside.
        /// </param>
        public MaskedTileCreator(IColorMap map, IImageTileSerializer serializer, bool lookAtOutsideSurface)
        {
            if (map == null)
            {
                throw new ArgumentNullException("map");
            }

            if (serializer == null)
            {
                throw new ArgumentNullException("serializer");
            }

            this.ColorMap = map;
            this.TileSerializer = serializer;
            this.LookAtOutsideSurface = lookAtOutsideSurface;
        }
Beispiel #22
0
        /// <summary>
        /// Initializes a new instance of the MaskedTileCreator class.
        /// </summary>
        /// <param name="map">
        /// Color map.
        /// </param>
        /// <param name="serializer">
        /// Tile serializer.
        /// </param>
        /// <param name="lookAtOutsideSurface">
        /// True if the projection is from outside the sphere, False if it's from inside.
        /// </param>
        public MaskedTileCreator(IColorMap map, IImageTileSerializer serializer, bool lookAtOutsideSurface)
        {
            if (map == null)
            {
                throw new ArgumentNullException("map");
            }

            if (serializer == null)
            {
                throw new ArgumentNullException("serializer");
            }

            this.ColorMap             = map;
            this.TileSerializer       = serializer;
            this.LookAtOutsideSurface = lookAtOutsideSurface;
        }
        /// <summary>
        /// Creates a DEM tile creator instance for the specified projection type.
        /// </summary>
        /// <param name="map">
        /// Color map used.
        /// </param>
        /// <param name="projectionType">
        /// Projection type desired.
        /// </param>
        /// <param name="path">
        /// Location where the tiles should be serialized.
        /// </param>
        /// <returns>
        /// ITileCreator instance.
        /// </returns>
        public static ITileCreator CreateImageTileCreator(IColorMap map, ProjectionTypes projectionType, string path)
        {
            if (map == null)
            {
                throw new ArgumentNullException("map");
            }

            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentNullException("path");
            }

            IImageTileSerializer serializer = new ImageTileSerializer(TileHelper.GetDefaultImageTilePathTemplate(path), ImageFormat.Png);

            return(CreateImageTileCreator(map, projectionType, serializer));
        }
Beispiel #24
0
        /// <summary>
        /// Draws the rectangle and its children
        /// </summary>
        /// <param name="aGraphics">the graphics container</param>
        public void Draw(Graphics aGraphics, IColorMap aColorMap, List <int> aSelectedIds, IndexVisibilityHandler aVisibility)
        {
            iVisibility = aVisibility;
            if (iHeight * iScale.Y <= 1)
            {
                return;
            }

            this.DrawChild(aGraphics, aColorMap, aSelectedIds, aVisibility);

            //foreach (TreeRectangle rectangle in iChildRectangles)
            //{
            //    rectangle.DrawChild(aGraphics, aColorMap);
            //}

            //
        }
Beispiel #25
0
        /// <summary>
        /// Initializes a new instance of the ShapeTileCreator class.
        /// </summary>
        /// <param name="serializer">Tile serializer to be used.</param>
        /// <param name="colorMap">Color map.</param>
        /// <param name="type">Desired projection type.</param>
        /// <param name="maximumLevel">Maximum level of the image pyramid.</param>
        public ShapeTileCreator(IImageTileSerializer serializer, IColorMap colorMap, ProjectionTypes type, int maximumLevel)
        {
            if (serializer == null)
            {
                throw new ArgumentNullException("serializer");
            }

            if (colorMap == null)
            {
                throw new ArgumentNullException("colorMap");
            }

            this.tileSerializer = serializer;
            this.colorMap = colorMap;
            this.ProjectionType = type;
            this.maximumLevel = maximumLevel;
        }
Beispiel #26
0
        /// <summary>
        /// Initializes a new instance of the ShapeTileCreator class.
        /// </summary>
        /// <param name="serializer">Tile serializer to be used.</param>
        /// <param name="colorMap">Color map.</param>
        /// <param name="type">Desired projection type.</param>
        /// <param name="maximumLevel">Maximum level of the image pyramid.</param>
        public ShapeTileCreator(IImageTileSerializer serializer, IColorMap colorMap, ProjectionTypes type, int maximumLevel)
        {
            if (serializer == null)
            {
                throw new ArgumentNullException("serializer");
            }

            if (colorMap == null)
            {
                throw new ArgumentNullException("colorMap");
            }

            this.tileSerializer = serializer;
            this.colorMap       = colorMap;
            this.ProjectionType = type;
            this.maximumLevel   = maximumLevel;
        }
Beispiel #27
0
 public ImageProcessor(IColorMap raw, IEnumerable <IFilter> filters)
 {
     this.raw = raw;
     stages   = filters.Select(f =>
     {
         IIIFilterAutoAdjuster adjuster = null;
         if (!(f is IAutoAdjustableFilter) || !((IAutoAdjustableFilter)f).IsAdjusted)
         {
             adjuster = AutoAdjustersFactory.GetNewAutoAdjuster(f);
         }
         var stage = new Stage
         {
             Filter       = f,
             AutoAdjuster = adjuster
         };
         return(stage);
     }).ToList();
 }
Beispiel #28
0
 public void SetColormapParams(ColorMapTypes colorMapType, string param)
 {
     if (_modelState.ColorMap.Type != colorMapType || _modelState.ColorMap.Param != param)
     {
         _modelState.ColorMap.Type  = colorMapType;
         _modelState.ColorMap.Param = param;
         IColorMap cm = ColorMapFactory.Create(colorMapType, param);
         if (cm != null)
         {
             cm.Initialize();
             if (CurrentImage != null)
             {
                 CurrentImage.ColorMap = cm;
                 RaiseImageChanged();
             }
         }
     }
 }
Beispiel #29
0
        static public IImage FromFile(string nicFile)
        {
            IImage       ii  = null;
            StreamReader sr  = null;
            XmlReader    r   = null;
            ImageTypes   it  = ImageTypes.Indexed;
            Color        nan = Color.Empty;

            try
            {
                sr = new StreamReader(nicFile);
                r  = XmlReader.Create(sr.BaseStream);
                r.ReadToFollowing("ImageConfig");
                it             = (ImageTypes)Enum.Parse(typeof(ImageTypes), r["Type"]);
                nan            = Color.FromArgb(int.Parse(r["NaNColor"]));
                r.Close(); r   = null;
                sr.Close(); sr = null;
                IColorTable ct = ColorTableFactory.FromFile(nicFile);
                IColorMap   cm = ColorMapFactory.FromFile(nicFile);
                ii = ImageFactory.Create(it);
                if (ii != null)
                {
                    ii.ColorTable             = ct;
                    ii.ColorMap               = cm;
                    ii.InvalidPixelValueColor = nan;
                }
            }
            finally
            {
                if (r != null)
                {
                    r.Close();
                }
                if (sr != null)
                {
                    sr.Close();
                }
            }

            return(ii);
        }
            public void Unload()
            {
                if (_realColorMap == null)
                {
                    return;
                }

                lock (_syncLock)
                {
                    if (_realColorMap == null)
                    {
                        return;
                    }
                    _realColorMap = null;

                    Diagnostics.OnLargeObjectReleased(_largeObjectData.BytesHeldCount);
                    _largeObjectData.BytesHeldCount   = 0;
                    _largeObjectData.LargeObjectCount = 0;
                    MemoryManager.Remove(this);
                }
            }
        /// <summary>
        /// Creates an image tile creator instance for the specified projection type.
        /// </summary>
        /// <param name="map">
        /// Color map used.
        /// </param>
        /// <param name="projectionType">
        /// Projection type desired.
        /// </param>
        /// <param name="serializer">
        /// Tile serializer instance.
        /// </param>
        /// <returns>
        /// ITileCreator instance.
        /// </returns>
        public static ITileCreator CreateImageTileCreator(IColorMap map, ProjectionTypes projectionType, IImageTileSerializer serializer)
        {
            if (map == null)
            {
                throw new ArgumentNullException("map");
            }

            if (serializer == null)
            {
                throw new ArgumentNullException("serializer");
            }

            switch (projectionType)
            {
            case ProjectionTypes.Mercator:
                return(new MercatorTileCreator(map, serializer));

            default:
                return(new ToastTileCreator(map, serializer));
            }
        }
Beispiel #32
0
        public static IColorMap ProcessFilters(IColorMap map, IEnumerable <IFilter> filters)
        {
            IColorMap currentMap = map;

            foreach (var filter in filters)
            {
                if (filter == null)
                {
                    throw new ArgumentNullException(nameof(filter));
                }

                var newmap = filter.CreateResultMap(currentMap);
                filter.ProcessMap(currentMap, newmap);
                if (newmap != currentMap && currentMap != map)
                {
                    currentMap.Dispose();
                }
                currentMap = newmap;
            }
            return(currentMap);
        }
Beispiel #33
0
        private void ResetImage()
        {
            // need to maintain color map used with image if we have one
            IColorMap cm = null;

            if (CurrentImage != null)
            {
                cm           = CurrentImage.ColorMap;
                CurrentImage = null;
            }

            // create new image now
            CreateImage();

            // restore colormap
            if (cm != null)
            {
                CurrentImage.ColorMap = cm;
            }

            // notify observers
            RaiseImageChanged();
        }
Beispiel #34
0
        public IColorMap Invoke()
        {
            IColorMap image = raw;
            IColorMap newimage;

            foreach (List <Stage> stagesGroup in stages.Split(s => s.AutoAdjuster != null, LinqExtensions.SplitPlace.Last))
            {
                var last = stagesGroup.Last();
                if (last.AutoAdjuster != null)
                {
                    if (stagesGroup.Count > 1)
                    {
                        newimage = FiltersPipeline.ProcessFilters(image, stagesGroup.Take(stagesGroup.Count - 1).Select(s => s.Filter));
                        image.Dispose();
                        image = newimage;
                    }
                    IColorMap imagetoadjust = image;
                    last.AutoAdjuster.AutoAdjust(last.Filter, imagetoadjust);
                    if (image != imagetoadjust)
                    {
                        imagetoadjust.Dispose();
                    }
                    last.AutoAdjuster = null;

                    newimage = FiltersPipeline.ProcessFilters(image, last.Filter);
                    image.Dispose();
                    image = newimage;
                }
                else
                {
                    newimage = FiltersPipeline.ProcessFilters(image, stagesGroup.Select(s => s.Filter));
                    image.Dispose();
                    image = newimage;
                }
            }
            return(image);
        }
		/// <summary>
		/// Installs a colour map.
		/// </summary>
		public void InstallColorMap(IColorMap colorMap)
		{
			this.ColorMapManager.InstallColorMap(colorMap);
		}
		void IColorMapInstaller.InstallColorMap(IColorMap colorMap)
		{
			if (_colorMap == colorMap)
				return;

			_colorMap = colorMap;
		}
Beispiel #37
0
		/// <summary>
		/// Converts indexed pixel data to ARGB using the specified colour map.
		/// </summary>
		/// <param name="bitsAllocated">Number of bits allocated in <paramref name="srcPixelData"/>.</param>
		/// <param name="isSigned">Indicates whether <paramref name="srcPixelData"/> is signed.</param>
		/// <param name="srcPixelData">The input pixel data to be converted.</param>
		/// <param name="argbPixelData">The converted output pixel data in ARGB format.</param>
		/// <param name="map">The colour map to be used.</param>
		/// <remarks>
		/// Internally, this method is used to convert PALETTE COLOR images to ARGB.
		/// </remarks>
		public static void ToArgb(
			int bitsAllocated,
			bool isSigned, 
			byte[] srcPixelData, 
			byte[] argbPixelData, 
			IColorMap map)
		{
			int sizeInPixels = argbPixelData.Length/4;
			int firstPixelMapped = map.MinInputValue;

			fixed (byte* pSrcPixelData = srcPixelData)
			{
				fixed (byte* pArgbPixelData = argbPixelData)
				{
					fixed (int* pColorMap = map.Data)
					{
						int dst = 0;

						if (bitsAllocated == 8)
						{
							if (isSigned)
							{
								// 8-bit signed
								for (int i = 0; i < sizeInPixels; i++)
								{
									int value = pColorMap[((sbyte*)pSrcPixelData)[i] - firstPixelMapped];
									pArgbPixelData[dst] = Color.FromArgb(value).B;
									pArgbPixelData[dst + 1] = Color.FromArgb(value).G;
									pArgbPixelData[dst + 2] = Color.FromArgb(value).R;
									pArgbPixelData[dst + 3] = Color.FromArgb(value).A;

									dst += 4;
								}
							}
							else
							{
								// 8-bit unsigned
								for (int i = 0; i < sizeInPixels; i++)
								{
									int value = pColorMap[pSrcPixelData[i] - firstPixelMapped];
									pArgbPixelData[dst] = Color.FromArgb(value).B;
									pArgbPixelData[dst + 1] = Color.FromArgb(value).G;
									pArgbPixelData[dst + 2] = Color.FromArgb(value).R;
									pArgbPixelData[dst + 3] = Color.FromArgb(value).A;

									dst += 4;
								}
							}
						}
						else
						{
							if (isSigned)
							{
								// 16-bit signed
								for (int i = 0; i < sizeInPixels; i++)
								{
									int value = pColorMap[((short*)pSrcPixelData)[i] - firstPixelMapped];
									pArgbPixelData[dst] = Color.FromArgb(value).B;
									pArgbPixelData[dst + 1] = Color.FromArgb(value).G;
									pArgbPixelData[dst + 2] = Color.FromArgb(value).R;
									pArgbPixelData[dst + 3] = Color.FromArgb(value).A;

									dst += 4;
								}
							}
							else
							{
								// 16-bit unsinged
								for (int i = 0; i < sizeInPixels; i++)
								{
									int value = pColorMap[((ushort*)pSrcPixelData)[i] - firstPixelMapped];
									pArgbPixelData[dst] = Color.FromArgb(value).B;
									pArgbPixelData[dst + 1] = Color.FromArgb(value).G;
									pArgbPixelData[dst + 2] = Color.FromArgb(value).R;
									pArgbPixelData[dst + 3] = Color.FromArgb(value).A;

									dst += 4;
								}
							}
						}
					}
				}
			}
		}
Beispiel #38
0
		public AlphaColorMap(IColorMap baseColorMap)
			: this(baseColorMap, 255, false) {}
Beispiel #39
0
 public IColorMap ProcessFilters(IColorMap map) => ProcessFilters(map, _filters);
		void IColorMapInstaller.InstallColorMap(IColorMap colorMap)
		{
			_placeholderColorMapManager.InstallColorMap(colorMap);
			InstallColorMap();
		}
Beispiel #41
0
 public VectorMap(IColorMap m, Vector3[] rgb)
 {
     _width = m.Width;
     _height = m.Height;
     Rgb = rgb;
 }
		private static IList<double> DiffFusionOperatorResults(IColorMap colorMap, bool thresholding, string testName)
		{
			var outputPath = new DirectoryInfo(Path.Combine(typeof (FusionColorCompositingTest).FullName, testName));
			if (outputPath.Exists)
				outputPath.Delete(true);
			outputPath.Create();

			// this kind of test requires that the base and overlay slices be unsigned and precisely coincident
			using (var data = new FusionTestDataContainer(
				() => TestDataFunction.GradientX.CreateSops(false, Modality.CT, new Vector3D(1.0f, 1.0f, 15.0f), Vector3D.xUnit, Vector3D.yUnit, Vector3D.zUnit),
				() => TestDataFunction.GradientY.CreateSops(false, Modality.PT, new Vector3D(1.0f, 1.0f, 15.0f), Vector3D.xUnit, Vector3D.yUnit, Vector3D.zUnit)))
			{
				using (var log = File.CreateText(Path.Combine(outputPath.FullName, "data.csv")))
				{
					log.WriteLine("{0}, {1}, {2}, {3}", "n", "opacity", "alpha", "diff");
					using (var baseDisplaySet = data.CreateBaseDisplaySet())
					{
						using (var overlayDisplaySet = data.CreateOverlayDisplaySet())
						{
							using (var fusionDisplaySet = data.CreateFusionDisplaySet())
							{
								var list = new List<double>();

								var imageIndex = fusionDisplaySet.PresentationImages.Count/2;
								var fusionImage = fusionDisplaySet.PresentationImages[imageIndex];

								for (int n = 0; n <= 10; n++)
								{
									var opacity = n/10f;

									SetFusionDisplayParameters(fusionImage, colorMap, opacity, thresholding);
									using (IPresentationImage referenceImage =
										Fuse(baseDisplaySet.PresentationImages[imageIndex], overlayDisplaySet.PresentationImages[imageIndex], colorMap, opacity, thresholding))
									{
										using (var referenceBmp = DrawToBitmap(referenceImage))
										{
											referenceBmp.Save(Path.Combine(outputPath.FullName, string.Format("reference{0}.png", n)));
										}

										using (var fusionBmp = DrawToBitmap(fusionImage))
										{
											fusionBmp.Save(Path.Combine(outputPath.FullName, string.Format("test{0}.png", n)));
										}

										// because the fusion display set is generated from real base images and *reformatted* overlay images,
										// there will necessarily be higher differences at the edges of the useful image area

										Bitmap diff;
										double result = ImageDiff.Compare(ImageDiffAlgorithm.Euclidian, referenceImage, fusionImage, new Rectangle(18, 18, 98, 98), out diff);
										diff.Save(Path.Combine(outputPath.FullName, string.Format("diff{0}.png", n)));
										diff.Dispose();
										log.WriteLine("{0}, {1:f2}, {2}, {3:f6}", n, opacity, (int) (255*opacity), result);
										list.Add(result);
									}
								}

								return list;
							}
						}
					}
				}
			}
		}
		private static void SetFusionDisplayParameters(IPresentationImage image, IColorMap colorMap, float opacity, bool thresholding)
		{
			if (image is IColorMapProvider)
			{
				var colorMapProvider = (IColorMapProvider) image;
				colorMapProvider.ColorMapManager.InstallColorMap(colorMap);
			}

			if (image is ILayerOpacityProvider)
			{
				var layerOpacityProvider = (ILayerOpacityProvider) image;
				layerOpacityProvider.LayerOpacityManager.Thresholding = thresholding;
				layerOpacityProvider.LayerOpacityManager.Opacity = opacity;
			}
		}
		/// <summary>
		/// Installs a color map.
		/// </summary>
		public void InstallColorMap(IColorMap colorMap)
		{
			_colorMapInstaller.InstallColorMap(colorMap);
		}
			public void InstallColorMap(string name)
			{
				if (_colorMapName != name)
				{
					_colorMapName = name;
					_colorMap = null;
				}
			}
        /// <summary>
        /// Creates an image tile creator instance for the specified projection type.
        /// </summary>
        /// <param name="map">
        /// Color map used.
        /// </param>
        /// <param name="projectionType">
        /// Projection type desired.
        /// </param>
        /// <param name="serializer">
        /// Tile serializer instance.
        /// </param>
        /// <returns>
        /// ITileCreator instance.
        /// </returns>
        public static ITileCreator CreateImageTileCreator(IColorMap map, ProjectionTypes projectionType, IImageTileSerializer serializer)
        {
            if (map == null)
            {
                throw new ArgumentNullException("map");
            }

            if (serializer == null)
            {
                throw new ArgumentNullException("serializer");
            }

            switch (projectionType)
            {
                case ProjectionTypes.Mercator:
                    return new MercatorTileCreator(map, serializer);

                default:
                    return new ToastTileCreator(map, serializer);
            }
        }
        /// <summary>
        /// Creates a DEM tile creator instance for the specified projection type.
        /// </summary>
        /// <param name="map">
        /// Color map used.
        /// </param>
        /// <param name="projectionType">
        /// Projection type desired.
        /// </param>
        /// <param name="path">
        /// Location where the tiles should be serialized.
        /// </param>
        /// <returns>
        /// ITileCreator instance.
        /// </returns>
        public static ITileCreator CreateImageTileCreator(IColorMap map, ProjectionTypes projectionType, string path)
        {
            if (map == null)
            {
                throw new ArgumentNullException("map");
            }

            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentNullException("path");
            }

            IImageTileSerializer serializer = new ImageTileSerializer(TileHelper.GetDefaultImageTilePathTemplate(path), ImageFormat.Png);
            return CreateImageTileCreator(map, projectionType, serializer);
        }
Beispiel #48
0
		public AlphaColorMap(IColorMap baseColorMap, byte alpha, bool thresholding)
		{
			_baseColorMap = baseColorMap;
			_alpha = alpha;
			_thresholding = thresholding;
		}
			public void InstallColorMap(IColorMap colorMap)
			{
				if (_colorMap != colorMap)
				{
					_colorMap = colorMap;
					_colorMapName = null;
				}
			}
		/// <summary>
		/// Reference implementation of the image fusion operator.
		/// </summary>
		private static IPresentationImage Fuse(IPresentationImage baseImage, IPresentationImage overlayImage, IColorMap colorMap, float opacity, bool thresholding)
		{
			Platform.CheckTrue(baseImage is IImageSopProvider, "baseImage must be a IImageSopProvider.");
			Platform.CheckTrue(overlayImage is IImageSopProvider, "overlayImage must be a IImageSopProvider.");
			Platform.CheckTrue(baseImage is IImageGraphicProvider, "baseImage must be a IImageGraphicProvider.");
			Platform.CheckTrue(overlayImage is IImageGraphicProvider, "overlayImage must be a IImageGraphicProvider.");

			var baseImageSopProvider = (IImageSopProvider) baseImage;
			var baseImageGraphicProvider = (IImageGraphicProvider) baseImage;
			var overlayImageSopProvider = (IImageSopProvider) overlayImage;
			var overlayImageGraphicProvider = (IImageGraphicProvider) overlayImage;
			var rows = baseImageSopProvider.Frame.Rows;
			var cols = baseImageSopProvider.Frame.Columns;
			var pixelData = new byte[3*rows*cols];

			colorMap.MinInputValue = ushort.MinValue;
			colorMap.MaxInputValue = ushort.MaxValue;

			// this here is the magic
			baseImageGraphicProvider.ImageGraphic.PixelData.ForEachPixel(
				(n, x, y, i) =>
					{
						// and this is why the base and overlay slices must be unsigned precisely coincident
						var patientLocation = baseImageSopProvider.Frame.ImagePlaneHelper.ConvertToPatient(new PointF(x, y));
						var overlayCoordinate = overlayImageSopProvider.Frame.ImagePlaneHelper.ConvertToImagePlane(patientLocation);
						var baseValue = (ushort) baseImageGraphicProvider.ImageGraphic.PixelData.GetPixel(i);
						var overlayValue = overlayImageGraphicProvider.ImageGraphic.PixelData.GetPixel((int) overlayCoordinate.X, (int) overlayCoordinate.Y);

						// the fusion operator: output = underlyingGrey*(1-alpha) + overlayingColour*(alpha) (see DICOM 2009 PS 3.4 N.2.4.3)
						var compositeColor = ToRgbVectorFromGrey(baseValue)*(1 - opacity) + ToRgbVector(colorMap[overlayValue])*opacity;
						pixelData[3*n] = (byte) compositeColor.X;
						pixelData[3*n + 1] = (byte) compositeColor.Y;
						pixelData[3*n + 2] = (byte) compositeColor.Z;
					});

			var dicomFile = new DicomFile();
			var dataset = dicomFile.DataSet;
			dataset[DicomTags.PatientId].SetStringValue(baseImageSopProvider.ImageSop.PatientId);
			dataset[DicomTags.PatientsName].SetStringValue(baseImageSopProvider.ImageSop.PatientsName);
			dataset[DicomTags.StudyId].SetStringValue(baseImageSopProvider.ImageSop.StudyId);
			dataset[DicomTags.StudyInstanceUid].SetStringValue(baseImageSopProvider.ImageSop.StudyInstanceUid);
			dataset[DicomTags.SeriesDescription].SetStringValue(baseImageSopProvider.ImageSop.SeriesDescription);
			dataset[DicomTags.SeriesNumber].SetInt32(0, 9001);
			dataset[DicomTags.SeriesInstanceUid].SetStringValue(DicomUid.GenerateUid().UID);
			dataset[DicomTags.SopInstanceUid].SetStringValue(DicomUid.GenerateUid().UID);
			dataset[DicomTags.SopClassUid].SetStringValue(ModalityConverter.ToSopClassUid(Modality.SC));
			dataset[DicomTags.Modality].SetStringValue("SC");
			dataset[DicomTags.FrameOfReferenceUid].SetStringValue(baseImageSopProvider.Frame.FrameOfReferenceUid);
			dataset[DicomTags.ImageOrientationPatient].SetStringValue(baseImageSopProvider.Frame.ImageOrientationPatient.ToString());
			dataset[DicomTags.ImagePositionPatient].SetStringValue(baseImageSopProvider.Frame.ImagePositionPatient.ToString());
			dataset[DicomTags.PixelSpacing].SetStringValue(baseImageSopProvider.Frame.PixelSpacing.ToString());
			dataset[DicomTags.PhotometricInterpretation].SetStringValue("RGB");
			dataset[DicomTags.SamplesPerPixel].SetInt32(0, 3);
			dataset[DicomTags.BitsStored].SetInt32(0, 8);
			dataset[DicomTags.BitsAllocated].SetInt32(0, 8);
			dataset[DicomTags.HighBit].SetInt32(0, 7);
			dataset[DicomTags.PixelRepresentation].SetInt32(0, 0);
			dataset[DicomTags.Rows].SetInt32(0, rows);
			dataset[DicomTags.Columns].SetInt32(0, cols);
			dataset[DicomTags.PixelData].Values = pixelData;
			dicomFile.MediaStorageSopClassUid = dataset[DicomTags.SopClassUid];
			dicomFile.MediaStorageSopInstanceUid = dataset[DicomTags.SopInstanceUid];

			using (var sopDataSource = new XSopDataSource(dicomFile))
			{
				return PresentationImageFactory.Create(new ImageSop(sopDataSource))[0];
			}
		}
Beispiel #51
0
		private static int[] ConstructFinalLut(IComposedLut outputLut, IColorMap colorMap, bool invert)
		{
			CodeClock clock = new CodeClock();
			clock.Start();

			colorMap.MinInputValue = outputLut.MinOutputValue;
			colorMap.MaxInputValue = outputLut.MaxOutputValue;

			int[] outputLutData = outputLut.Data;
			int[] colorMapData = colorMap.Data;

			if (_finalLutBuffer == null || _finalLutBuffer.Length != outputLutData.Length)
				_finalLutBuffer = new int[outputLutData.Length];

			int numberOfEntries = _finalLutBuffer.Length;

			fixed (int* pOutputLutData = outputLutData)
			{
				fixed (int* pColorMapData = colorMapData)
				{
					fixed (int* pFinalLutData = _finalLutBuffer)
					{
						int* pFinalLut = pFinalLutData;

						if (!invert)
						{
							int firstColorMappedPixelValue = colorMap.FirstMappedPixelValue;
							for (int i = 0; i < numberOfEntries; ++i)
								*(pFinalLut++) = pColorMapData[*(pOutputLutData + i) - firstColorMappedPixelValue];
						}
						else
						{
							int lastColorMappedPixelValue = colorMap.FirstMappedPixelValue + colorMap.Data.Length - 1;
							for (int i = 0; i < numberOfEntries; ++i)
								*(pFinalLut++) = pColorMapData[lastColorMappedPixelValue - *(pOutputLutData + i)];
						}
					}
				}
			}

			clock.Stop();
			PerformanceReportBroker.PublishReport("ImageRenderer", "ConstructFinalLut", clock.Seconds);

			return _finalLutBuffer;
		}
Beispiel #52
0
 public static IColorMap ProcessFilters(IColorMap map, IFilter filter)
 {
     return ProcessFilters(map, new[] { filter });
 }