Exemple #1
0
        /// <summary>
        /// Filter implementation with rectangle clipping effect.
        /// if a rectangle does not cover a pixel in the processed image,
        /// the pixel keeps its original value;
        /// </summary>
        public IImageAdapter Process(IImageAdapter source, bool[,] clippingMap)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source", "Parameter must be set to a valid instance of the object (null passed in)");
            }

            IImageAdapter result = ProcessFilter(source);


            // filter effect mask to be applied
            if (result != null && clippingMap != null)
            {
                int minWidth  = (int)Math.Min(source.Width, clippingMap.GetLength(0));
                int minHeight = (int)Math.Min(source.Height, clippingMap.GetLength(1));

                for (int j = 0; j < minHeight; j++)
                {
                    for (int i = 0; i < minWidth; i++)
                    {
                        if (clippingMap[i, j] == false)
                        {
                            result[i, j] = source[i, j];
                        }
                    }
                }
            }

            return(result);
        }
Exemple #2
0
        /// <summary>
        /// Filter Implementation
        /// </summary>
        protected override IImageAdapter ProcessFilter(IImageAdapter source)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source", "The value passed in cannot be null");
            }

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

            rgbPixels = new float[3, source.Width, source.Height];
            for (int j = 0; j < source.Height; j++)
            {
                for (int i = 0; i < source.Width; i++)
                {
                    rgbPixels[0, i, j] = (float)source[i, j].Red;
                    rgbPixels[1, i, j] = (float)source[i, j].Green;
                    rgbPixels[2, i, j] = (float)source[i, j].Blue;
                }
            }
            IImageAdapter retVal = new ImageAdapter(source);

            Process(Level, true);
            Normalize(retVal);
            retVal = Interp(retVal);

            return(retVal);
        }
Exemple #3
0
        /// <summary>
        /// Filter Implementation
        /// </summary>
        protected override IImageAdapter ProcessFilter(IImageAdapter source)
        {
            IImageAdapter retVal = null;

            if (source != null)
            {
                int width  = source.Width;
                int height = source.Height;
                retVal = new ImageAdapter(source.Width, source.Height, ColorByte.Empty);
                if (Automatic)
                {
                    _delta[0] = 256f / AutomaticNumberOfColors[0];
                    _delta[1] = 256f / AutomaticNumberOfColors[1];
                    _delta[2] = 256f / AutomaticNumberOfColors[2];
                }


                for (int j = 0; j < height; j++)
                {
                    for (int i = 0; i < width; i++)
                    {
                        retVal[i, j] = ComputeClosestColor(source[i, j]);
                    }
                }
            }

            return(retVal);
        }
Exemple #4
0
        /// <summary>
        /// Build the histogram for this image
        /// </summary>
        /// <param name="imageAdapter">The image to analyze</param>
        /// <returns></returns>
        internal static Hashtable BuildHistogram(IImageAdapter imageAdapter)
        {
            // Initialize the variables
            Hashtable hashChannel = new Hashtable();

            for (int channel = 0; channel < intColor.Length; channel++)
            {
                ArrayList[] list1 = new ArrayList[256];
                for (int index = 0; index < 256; index++)
                {
                    list1[index] = new ArrayList();
                }
                hashChannel.Add(intColor[channel], list1);
            }


            // Build the histogram
            IColor color = null;

            for (int height = 0; height < imageAdapter.Height; height++)
            {
                for (int width = 0; width < imageAdapter.Width; width++)
                {
                    color = (IColor)imageAdapter[width, height].Clone();
                    Point point = new Point(width, height);
                    ((ArrayList[])hashChannel[ALPHA])[color.A].Add(point);
                    ((ArrayList[])hashChannel[RED])[color.R].Add(point);
                    ((ArrayList[])hashChannel[GREEN])[color.G].Add(point);
                    ((ArrayList[])hashChannel[BLUE])[color.B].Add(point);
                }
            }

            return(hashChannel);
        }
Exemple #5
0
        /// <summary>
        /// Filter Implementation
        /// </summary>
        protected override IImageAdapter ProcessFilter(IImageAdapter source)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source", "The IImageAdapter cannot be null");
            }
            if (source.Width == 0 || source.Height == 0)
            {
                throw new ArgumentException("The IImageAdapter is invalid (width and/or height is zero)");
            }

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

            IColor       lcol   = null;
            ImageAdapter retVal = new ImageAdapter(width, height);

            for (int j = 0; j < height; j++)
            {
                for (int i = 0; i < width; i++)
                {
                    lcol = (IColor)source[i, j].Clone();
                    // Do not try to convert an empty color
                    if (lcol.IsEmpty == false)
                    {
                        double gval = lcol.Red * RED + lcol.Green * GREEN + lcol.Blue * BLUE;
                        lcol.Red   = gval;
                        lcol.Green = gval;
                        lcol.Blue  = gval;
                    }
                    retVal[i, j] = lcol;
                }
            }
            return(retVal);
        }
        /// <summary>
        /// Filter Implementation
        /// </summary>
        protected override IImageAdapter ProcessFilter(IImageAdapter source)
        {
            ImageAdapter iret = null;

            iret = new ImageAdapter(source.Width, source.Height);

            // Compute the curve for all channels (except Alpha which remains constant)
            byte[] redLUT   = CreateLUT(RedGamma);
            byte[] greenLUT = CreateLUT(GreenGamma);
            byte[] blueLUT  = CreateLUT(BlueGamma);

            IColor color = null;

            for (int y = 0; y < iret.Height; y++)
            {
                for (int x = 0; x < iret.Width; x++)
                {
                    color      = (IColor)source[x, y].Clone();
                    color.RGB  = 0;         // Keep alpha value
                    color.R    = redLUT[source[x, y].R];
                    color.G    = greenLUT[source[x, y].G];
                    color.B    = blueLUT[source[x, y].B];
                    iret[x, y] = color;
                }
            }
            return(iret);
        }
Exemple #7
0
        /// <summary>
        /// Filter Implementation
        /// </summary>
        protected override IImageAdapter ProcessFilter(IImageAdapter source)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source", "The value passed in cannot be null");
            }
            if (Radius == 0)
            {
                //
                return((IImageAdapter)source.Clone());
            }

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

            ImageAdapter retVal = null;

            if (Expand)
            {
                retVal = new ImageAdapter((int)(width + (Radius + 0.5) * 2), (int)(height + (Radius + 0.5) * 2));
            }
            else
            {
                retVal = new ImageAdapter(width, height);
            }

            InitializeKernel();
            GaussianFilter gaussianFilter = new GaussianFilter();

            gaussianFilter.Kernel = _kernel;

            return(gaussianFilter.Process(source));
        }
Exemple #8
0
        /// <summary>
        /// Filter implementation with rectangle clipping effect.
        /// if a rectangle does not cover a pixel in the processed image,
        /// the pixel keeps its original value;
        /// </summary>
        public IImageAdapter Process(IImageAdapter source, Rectangle[] clippingRectangles)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source", "Parameter must be set to a valid instance of the object (null passed in)");
            }

            IImageAdapter result = ProcessFilter(source);

            if (result != null && clippingRectangles != null && clippingRectangles.Length > 0)
            {
                int width  = source.Width;
                int height = source.Height;
                bool[,] tmap = new bool[width, height];
                Rectangle iadpt = new Rectangle(0, 0, width, height);

                foreach (Rectangle r in clippingRectangles)
                {
                    Rectangle intersect = r;

                    r.Intersect(iadpt);
                    for (int j = intersect.Y; j < intersect.Y + intersect.Height; j++)
                    {
                        for (int i = intersect.X; i < intersect.X + intersect.Width; i++)
                        {
                            tmap[i, j] = true;
                        }
                    }
                }

                result = Process(source, tmap);
            }

            return(result);
        }
Exemple #9
0
        /// <summary>
        /// Filter Implementation
        /// </summary>
        protected override IImageAdapter ProcessFilter(IImageAdapter source)
        {
            LogicalOperationFilter logicalFilter = new LogicalOperationFilter();

            logicalFilter.Not = true;
            return(logicalFilter.Process(source));
        }
Exemple #10
0
        private void tsbBatchImport_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fbd = new FolderBrowserDialog();

            fbd.Description         = "Select the source directory containing image and png file pairs..." + (Settings.Default.BatchScanSubdirectories ? "\r\nSub-directories will be scanned." : string.Empty);
            fbd.SelectedPath        = Settings.Default.LastBatchDirectory == string.Empty ? Settings.Default.LastDirectory : Settings.Default.LastBatchDirectory;
            fbd.ShowNewFolderButton = false;

            if (fbd.ShowDialog() == DialogResult.OK)
            {
                string path        = fbd.SelectedPath;
                int    fileCount   = 0;
                int    importCount = 0;

                if (Directory.Exists(path))
                {
                    string[] types = _imageAdapters.Select(x => x.Extension.ToLower()).ToArray();

                    List <string> files = new List <string>();
                    foreach (string type in types)
                    {
                        string[] subTypes = type.Split(';');
                        foreach (string subType in subTypes)
                        {
                            files.AddRange(Directory.GetFiles(path, subType, (Settings.Default.BatchScanSubdirectories ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly)));
                        }
                    }

                    foreach (string file in files)
                    {
                        if (File.Exists(file))
                        {
                            FileInfo      fi             = new FileInfo(file);
                            IImageAdapter currentAdapter = SelectImageAdapter(file, true);

                            if (currentAdapter != null && currentAdapter.CanSave && File.Exists(fi.FullName + ".png"))
                            {
                                try
                                {
                                    var bmp = (Bitmap)Image.FromFile(fi.FullName + ".png");
                                    currentAdapter.Load(file);
                                    currentAdapter.Bitmap = bmp;
                                    currentAdapter.Save();
                                    importCount++;
                                }
                                catch (Exception) { }
                            }

                            fileCount++;
                        }
                    }

                    MessageBox.Show("Batch import completed successfully. " + importCount + " of " + fileCount + " files succesfully imported.", "Batch Import", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }

            Settings.Default.LastBatchDirectory = fbd.SelectedPath;
            Settings.Default.Save();
        }
Exemple #11
0
 /// <summary>
 /// Get the IImageAdapter DPI settings
 /// </summary>
 /// <param name="imageAdapter"></param>
 /// <returns></returns>
 static public Point GetDpi(IImageAdapter imageAdapter)
 {
     if (imageAdapter == null)
     {
         throw new ArgumentNullException("imageAdapter", "Cannot pass a null value");
     }
     return(GetDpi(imageAdapter.Metadata));
 }
Exemple #12
0
        private void OpenFile(string filename = "")
        {
            var ofd = new OpenFileDialog
            {
                InitialDirectory = Settings.Default.LastDirectory,
                Filter           = Tools.LoadFilters(_imageAdapters)
            };

            var dr = DialogResult.OK;

            if (filename == string.Empty)
            {
                dr = ofd.ShowDialog();
            }

            if (dr != DialogResult.OK)
            {
                return;
            }

            if (filename == string.Empty)
            {
                filename = ofd.FileName;
            }

            var tempAdapter = SelectImageAdapter(filename);

            try
            {
                if (tempAdapter != null)
                {
                    tempAdapter.Load(filename);

                    _imageAdapter       = tempAdapter;
                    _fileOpen           = true;
                    _hasChanges         = false;
                    imbPreview.Zoom     = 100;
                    _selectedImageIndex = 0;

                    UpdatePreview();
                    UpdateImageList();
                    if (_imageAdapter.Bitmaps?.Count <= 0)
                    {
                        MessageBox.Show(this, $"{FileName()} was loaded by the \"{tempAdapter.Description}\" adapter but it provided no images.", "Supported Format Load Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        _imageAdapter = null;
                        _fileOpen     = false;
                    }
                    UpdateForm();
                }

                Settings.Default.LastDirectory = new FileInfo(filename).DirectoryName;
                Settings.Default.Save();
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.ToString(), tempAdapter != null ? $"{tempAdapter.Name} - {tempAdapter.Description} Adapter" : "Supported Format Load Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Exemple #13
0
 private IImageAdapter RenderGlyphs(GlyphBase[] glyphs, IImageAdapter renderSurface)
 {
     foreach (GlyphBase glyphBase in glyphs)
     {
         Point pt = new Point((int)(glyphBase.Position.X + .5), (int)(glyphBase.Position.Y + .5));
         renderSurface = ImageUtility.CopyImageAdapter(renderSurface, glyphBase.Render(), pt, glyphBase.Size, true);
     }
     return(renderSurface);
 }
Exemple #14
0
        /// <summary>
        /// Filter Implementation
        /// </summary>
        protected override IImageAdapter ProcessFilter(IImageAdapter source)
        {
            //Check params
            if (source == null)
            {
                throw new ArgumentNullException("source", "The IImageAdapter passed in cannot be null");
            }

            ImageAdapter retVal = new ImageAdapter(source.Width, source.Height);

            if (Amount == 0.0 || Radius == 0.0)
            {
                // Do nothing filter, return a clone of the original IImageAdapter
                for (int y = 0; y < source.Height; y++)
                {
                    for (int x = 0; x < source.Width; x++)
                    {
                        retVal[x, y] = source[x, y];
                    }
                }
                return(retVal);
            }

            // Perform Blur (Gaussian Filter)
            BlurFilter blurFilter = new BlurFilter();

            blurFilter.Radius = Radius;
            blurFilter.Expand = true;
            retVal            = (ImageAdapter)blurFilter.Process(source);

            // Compute weights factors
            double weight         = (0.4 - 0.4 * Amount) + 0.6;
            double originalFactor = (weight / (2.0 * weight - 1.0));
            double blurFactor     = ((1.0 - weight) / (2.0 * weight - 1.0));

            // Combine original image with blurred one to get the Sharpen Image
            IColor sourceColor = null;
            IColor blurColor   = null;
            IColor retValColor = null;

            for (int y = 0; y < retVal.Height; y++)
            {
                for (int x = 0; x < retVal.Width; x++)
                {
                    sourceColor = (IColor)source[x, y].Clone();
                    blurColor   = retVal[x, y];
                    retValColor = retVal[x, y];
                    retValColor.ExtendedAlpha = sourceColor.ExtendedAlpha * originalFactor - blurColor.ExtendedAlpha * blurFactor;
                    retValColor.ExtendedRed   = sourceColor.ExtendedRed * originalFactor - blurColor.ExtendedRed * blurFactor;
                    retValColor.ExtendedGreen = sourceColor.ExtendedGreen * originalFactor - blurColor.ExtendedGreen * blurFactor;
                    retValColor.ExtendedBlue  = sourceColor.ExtendedBlue * originalFactor - blurColor.ExtendedBlue * blurFactor;
//                            retVal[x, y] = retValColor;
                }
            }

            return(retVal);
        }
 public AppService(ILogger <IAppService> logger, IImageLoaderService imageLoaderService, IImageAdapter imageAdapter, IFilePickerService filePickerService, ISolverService solverService, IImageDrawerService imageDrawerService)
 {
     _imageList          = new List <ImageListItem>();
     _imageLoaderService = imageLoaderService;
     _imageAdapter       = imageAdapter;
     _filePickerService  = filePickerService;
     _solverService      = solverService;
     _imageDrawerService = imageDrawerService;
     _logger             = logger;
 }
        public EncodeImageViewModel(FileManager fileManager, IImageAdapter adapter, BitmapInfo bitmapInfo)
        {
            _fileManager = fileManager;
            _adapter     = adapter;
            _bitmapInfo  = bitmapInfo;

            SelectedEncoding = _bitmapInfo.ImageEncoding;
            SourceImage      = _bitmapInfo.Image.ToBitmapImage(true);
            OutputImage      = SourceImage;
        }
Exemple #17
0
        /// <summary>
        /// Try to find the GlyphBase specified within second GlyphBase
        /// </summary>
        /// <param name="glyphToFind">The GlyphBase to look for</param>
        /// <param name="glyphToParse">The GlyphBase to search</param>
        /// <param name="errorMax">The maximum number of pixel mismatching (normalized percentage)</param>
        /// <returns>true if match, false otherwise</returns>
        public bool FindSingleGlyph(GlyphBase glyphToFind, GlyphBase glyphToParse, double errorMax)
        {
            _glyphToFind     = glyphToFind;
            _glyphSearched   = glyphToParse;
            MatchFoundEvent += new MatchFoundEventHandler(GlyphComparator_MatchFoundInternal);

            IImageAdapter imageToParse = glyphToParse.Render();
            IImageAdapter imageToFind  = glyphToFind.Render();

            return(FindImageAdapter(imageToParse, imageToFind, errorMax));
        }
Exemple #18
0
        private void OpenFile(string filename = "")
        {
            OpenFileDialog ofd = new OpenFileDialog();

            ofd.InitialDirectory = Settings.Default.LastDirectory;

            // Supported Types
            ofd.Filter = Tools.LoadImageFilters(_imageAdapters);

            DialogResult dr = DialogResult.OK;

            if (filename == string.Empty)
            {
                dr = ofd.ShowDialog();
            }

            if (dr == DialogResult.OK)
            {
                if (filename == string.Empty)
                {
                    filename = ofd.FileName;
                }

                IImageAdapter _tempAdapter = SelectImageAdapter(filename);

                try
                {
                    if (_tempAdapter != null && _tempAdapter.Load(filename) == LoadResult.Success)
                    {
                        _imageAdapter = _tempAdapter;
                        _fileOpen     = true;
                        _hasChanges   = false;

                        UpdatePreview();
                        UpdateForm();
                    }

                    Settings.Default.LastDirectory = new FileInfo(filename).DirectoryName;
                    Settings.Default.Save();
                }
                catch (Exception ex)
                {
                    if (_tempAdapter != null)
                    {
                        MessageBox.Show(this, ex.ToString(), _tempAdapter.Name + " - " + _tempAdapter.Description + " Adapter", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    else
                    {
                        MessageBox.Show(this, ex.ToString(), "Supported Format Load Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }
Exemple #19
0
        private void tsbBatchExport_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fbd = new FolderBrowserDialog();

            fbd.Description         = "Select the source directory containing image files..." + (Settings.Default.BatchScanSubdirectories ? "\r\nSub-directories will be scanned." : string.Empty);
            fbd.SelectedPath        = Settings.Default.LastBatchDirectory == string.Empty ? Settings.Default.LastDirectory : Settings.Default.LastBatchDirectory;
            fbd.ShowNewFolderButton = false;

            if (fbd.ShowDialog() == DialogResult.OK)
            {
                string path  = fbd.SelectedPath;
                int    count = 0;

                if (Directory.Exists(path))
                {
                    var types = _imageAdapters.Select(x => x.Extension.ToLower()).Select(y => y.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)).SelectMany(z => z).Distinct().ToList();

                    List <string> files = new List <string>();
                    foreach (string type in types)
                    {
                        files.AddRange(Directory.GetFiles(path, type, Settings.Default.BatchScanSubdirectories ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly));
                    }

                    foreach (string file in files)
                    {
                        if (File.Exists(file))
                        {
                            try
                            {
                                FileInfo      fi             = new FileInfo(file);
                                IImageAdapter currentAdapter = SelectImageAdapter(file, true);

                                if (currentAdapter != null)
                                {
                                    currentAdapter.Load(file);
                                    for (var i = 0; i < currentAdapter.Bitmaps.Count; i++)
                                    {
                                        currentAdapter.Bitmaps[i].Bitmap.Save(fi.FullName + "." + i.ToString("00") + ".png");
                                    }
                                    count++;
                                }
                            }
                            catch (Exception) { }
                        }
                    }

                    MessageBox.Show("Batch export completed successfully. " + count + " image(s) succesfully exported.", "Batch Export", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }

            Settings.Default.LastBatchDirectory = fbd.SelectedPath;
            Settings.Default.Save();
        }
        /// <summary>
        /// Filter implementation
        /// </summary>
        protected override IImageAdapter ProcessFilter(IImageAdapter source)
        {
            IImageAdapter     retVal    = null;
            Image2DTransforms transform = new Image2DTransforms(source);

            transform.ResizeToFitOutputImage = ResizeOutputImage;
            if (UseMatrix == false)
            {
                if (Rotation % 360.0 != 0.0)
                {
                    transform.RotateTransform(Rotation, AngleUnit.Degree);
                }

                transform.TranslateTransform(HorizontalOffset, VerticalOffset);
                transform.ScaleTransform(HorizontalScaling, VerticalScaling);
                // Note : Cannot use Matrix property as it will reset the "UseMatrix" field
                this[MATRIX].Parameter = transform.ConvertTransformsToMatrix();
            }

            transform.Transform(Matrix);
            retVal = transform.ImageTransformed;

            if (VerticalFlip || HorizontalFlip)
            {
                int           x = 0;
                int           y = 0;
                IImageAdapter imageTransformed = retVal;
                int           width            = (int)imageTransformed.Width;
                int           height           = (int)imageTransformed.Height;
                if (UseMatrix == false)
                {
                    if (HorizontalFlip)
                    {
                        y = height - 1;
                    }
                    if (VerticalFlip)
                    {
                        x = width - 1;
                    }
                }

                retVal = new ImageAdapter(imageTransformed.Width, imageTransformed.Height);
                for (int j = 0; j < height; j++)
                {
                    for (int i = 0; i < width; i++)
                    {
                        retVal[(int)Math.Abs(x - i), (int)Math.Abs(y - j)] = imageTransformed[i, j];
                    }
                }
            }
            return(retVal);
        }
Exemple #21
0
        private void tsbBatchExport_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fbd = new FolderBrowserDialog();

            fbd.Description         = "Select the source directory containing image files...";
            fbd.SelectedPath        = Settings.Default.LastBatchDirectory == string.Empty ? Settings.Default.LastDirectory : Settings.Default.LastBatchDirectory;
            fbd.ShowNewFolderButton = false;

            if (fbd.ShowDialog() == DialogResult.OK)
            {
                string path  = fbd.SelectedPath;
                int    count = 0;

                if (Directory.Exists(path))
                {
                    string[] types = _imageAdapters.Select(x => x.Extension.ToLower()).ToArray();

                    List <string> files = new List <string>();
                    foreach (string type in types)
                    {
                        string[] subTypes = type.Split(';');
                        foreach (string subType in subTypes)
                        {
                            files.AddRange(Directory.GetFiles(path, subType));
                        }
                    }

                    foreach (string file in files)
                    {
                        if (File.Exists(file))
                        {
                            FileInfo      fi             = new FileInfo(file);
                            IImageAdapter currentAdapter = SelectImageAdapter(file, true);

                            if (currentAdapter != null)
                            {
                                currentAdapter.Load(file);
                                currentAdapter.Bitmap.Save(fi.FullName + ".png");
                                count++;
                            }
                        }
                    }

                    MessageBox.Show("Batch export completed successfully. " + count + " image(s) succesfully exported.", "Batch Export", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }

            Settings.Default.LastBatchDirectory = fbd.SelectedPath;
            Settings.Default.Save();
        }
        // Constructor
        public ImageEditorViewModel(FileManager fileManager, KoreFileInfo koreFile)
        {
            _fileManager = fileManager;
            KoreFile     = koreFile;

            _adapter = KoreFile.Adapter as IImageAdapter;

            if (_adapter?.BitmapInfos != null)
            {
                Bitmaps = new ObservableCollection <BitmapEntry>(_adapter.BitmapInfos.Select(bi => new BitmapEntry(bi)));
            }

            SelectedBitmap    = Bitmaps?.FirstOrDefault();
            SelectedZoomLevel = 1;
        }
Exemple #23
0
        /// <summary>
        /// Prepares an image adapter based on a bitmapped Master image
        /// </summary>
        /// <param name="filepath"></param>
        /// <returns></returns>
        private static IImageAdapter PrepareBitmapImageAdapter(String filepath)
        {
            IImageAdapter adapter = null;

            TestLog.Current.LogStatus("Master=" + filepath);
            if (filepath.Contains(".bmp"))
            {
                adapter = new ImageAdapter(filepath);
            }
            else
            {
                throw new Exception("Test error - PrepareBitmapImageAdapter expects a bmp file for its filepath");
            }
            return(adapter);
        }
Exemple #24
0
        private int[] CreateGreyHistogram(IImageAdapter source, out int lowerBound)
        {
            int       redLuminance   = 0;
            int       greenLuminance = 0;
            int       blueLuminance  = 0;
            int       luminance      = 0;
            int       maxLuminance   = int.MinValue;
            int       minLuminance   = int.MaxValue;
            IColor    color          = ColorByte.Empty;
            Hashtable hash           = new Hashtable((int)((source[0, 0].MaxChannelValue - source[0, 0].MinChannelValue) * source[0, 0].NormalizedValue + 1));

            for (int y = 0; y < source.Height; y++)
            {
                for (int x = 0; x < source.Width; x++)
                {
                    color          = source[x, y];
                    redLuminance   = (int)(color.R * LUMINANCE_RED);
                    greenLuminance = (int)(color.G * LUMINANCE_GREEN);
                    blueLuminance  = (int)(color.B * LUMINANCE_BLUE);
                    luminance      = redLuminance + greenLuminance + blueLuminance;
                    if (luminance > maxLuminance)
                    {
                        maxLuminance = luminance;
                    }
                    if (luminance < minLuminance)
                    {
                        minLuminance = luminance;
                    }
                    if (hash.Contains(luminance))
                    {
                        int count = (int)hash[luminance]; count++; hash[luminance] = count;
                    }
                    else
                    {
                        int one = 1; hash.Add(luminance, one);
                    }
                }
            }
            lowerBound = minLuminance;
            int[] retVal = new int[maxLuminance - minLuminance + 1];
            IDictionaryEnumerator iter = hash.GetEnumerator();

            while (iter.MoveNext())
            {
                retVal[(int)iter.Key - minLuminance] = (int)iter.Value;
            }
            return(retVal);
        }
Exemple #25
0
        /// <summary>
        /// Generates the Bitmap result
        /// </summary>
        private void GenerateMatchMap()
        {
            _matchMap = (IImageAdapter)Target.Clone();

            foreach (GlyphBase glyph in Glyphs)
            {
                int nbMatch = glyph.CompareInfo.Matches.Count;
                for (int i = 0; i < nbMatch; i++)
                {
                    MatchingInfo matchInfo = (MatchingInfo)(glyph.CompareInfo.Matches[i]);
                    Rectangle    rect      = matchInfo.BoundingBox;
                    ImageUtility.FillRect(_matchMap, rect, new ColorByte(80, 255, 0, 0));
                    ImageUtility.DrawRect(_matchMap, rect, (ColorByte)Color.Yellow);
                }
            }
        }
Exemple #26
0
        /// <summary>
        /// Create a IImageAdapter based on a histogram
        /// </summary>
        /// <param name="dictio">The histogram containg the points</param>
        /// <param name="source">The Histogram to convert</param>
        internal static IImageAdapter HistogramToIImageAdapter(Hashtable dictio, IImageAdapter source)
        {
            // check params
            if (dictio == null || source == null)
            {
                throw new ArgumentNullException((dictio == null) ? "dictio" : "source", "Argument cannot be null");
            }

            IImageAdapter imageAdapter = (IImageAdapter)source.Clone();

            // Build IImageAdapter based on histogram.
            IColor color = null;

            for (int channel = 0; channel < intColor.Length; channel++)
            {
                for (int index = 0; index < 256; index++)
                {
                    foreach (Point point in ((ArrayList[])dictio[intColor[channel]])[index])
                    {
                        color = imageAdapter[point.X, point.Y];
                        switch (intColor[channel])
                        {
                        case ALPHA:
                            color.A = (byte)index;
                            break;

                        case RED:
                            color.R = (byte)index;
                            break;

                        case GREEN:
                            color.G = (byte)index;
                            break;

                        case BLUE:
                            color.B = (byte)index;
                            break;
                        }
//                        imageAdapter[point.X, point.Y] = color;
                    }
                }
            }

            return(imageAdapter);
        }
Exemple #27
0
        /// <summary>
        /// Filter Implementation
        /// </summary>
        protected override IImageAdapter ProcessFilter(IImageAdapter source)
        {
/*
 *                  ImageAdapter iret = new ImageAdapter(source.Width, source.Height);
 *                  BitmapFormat sourceBitmatFormat = GetNativeBitmapFormat(SourceColorContext);
 *                  BitmapFormat destinationBitmatFormat = GetNativeBitmapFormat(DestinationColorContext);
 *
 * //                    m_hTransform = CreateMultiProfileTransform(&rghProfile[0],
 * //                                                       2,
 * //                                                       rgdwIntents,
 * //                                                       2,
 * //                                                       BEST_MODE |
 * //                                                       USE_RELATIVE_COLORIMETRIC,
 * //                                                       0);
 *                  return iret;
 */
            throw new NotImplementedException("Not implemented yet, soon to be");
        }
Exemple #28
0
        /// <summary>
        /// Perform the comparison operation
        /// This method abstracts out all the details of image comparison to a boolean result
        /// The basic assumption is that the default set of tolerances is adequate
        /// </summary>
        /// <param name="testImageAdapter"></param>
        /// <param name="masterImageAdapter"></param>
        /// <returns></returns>
        private static bool Compare(IImageAdapter testImageAdapter, IImageAdapter masterImageAdapter)
        {
            bool            TestPassed = false;
            ImageComparator comparator = null;

            if (File.Exists(toleranceFilePath))
            {
                CurveTolerance tolerance = new CurveTolerance();
                tolerance.LoadTolerance(toleranceFilePath);
                comparator = new ImageComparator(tolerance);
                TestLog.Current.LogStatus("Using custom tolerance (" + toleranceFilePath + ")");
            }
            else
            {
                comparator = new ImageComparator();
                TestLog.Current.LogStatus("Using default tolerance");
            }

            if (!xtcContainsDpiInfo)
            {
                // No master image dpi info found in test definition
                TestPassed = comparator.Compare(masterImageAdapter, testImageAdapter, true);
            }
            else
            {
                TestPassed = comparator.Compare(masterImageAdapter,                                                                            // master image adapter
                                                new Point((int)Math.Round(masterImageAdapter.DpiX), (int)Math.Round(masterImageAdapter.DpiY)), // master image dpi info
                                                testImageAdapter,                                                                              // test image adapter
                                                new Point((int)Math.Round(testImageAdapter.DpiX), (int)Math.Round(testImageAdapter.DpiY)),     // test image dpi info
                                                true);                                                                                         // populateMismatchingPoints
            }

            if (!TestPassed)
            {
                Package package = Package.Create(".\\FailurePackage.vscan",
                                                 ImageUtility.ToBitmap(masterImageAdapter),
                                                 ImageUtility.ToBitmap(testImageAdapter),
                                                 comparator.Curve.CurveTolerance.WriteToleranceToNode());
                package.Save();
                TestLog.Current.LogFile(package.PackageName);
            }

            return(TestPassed);
        }
        /// <summary>
        /// Filter Implementation
        /// </summary>
        protected override IImageAdapter ProcessFilter(IImageAdapter source)
        {
            // Check params
            if (source == null)
            {
                throw new ArgumentNullException("source", "Parameter passed in must be a valid instance of an object implementing IImageAdapter (null was passed in)");
            }

            IImageAdapter retVal = (IImageAdapter)source.Clone();

            if (Points.Length == 0)
            {
                return(retVal);
            }
            double[] fadingLUT = ComputeFading();
            for (int y = 0; y < source.Height; y++)
            {
                for (int x = 0; x < source.Width; x++)
                {
                    if (FadingDirection == FadingType.OpaqueToTranslucent)
                    {
                        retVal[x, y].ExtendedAlpha = 0.0;
                    }
                    foreach (System.Drawing.Point point in Points)
                    {
                        double dist = ComputeDistance(x, y, point);
                        if ((int)dist >= fadingLUT.Length)
                        {
                            continue;
                        }
                        if (FadingDirection == FadingType.OpaqueToTranslucent)
                        {
                            retVal[x, y].ExtendedAlpha += source[x, y].ExtendedAlpha * fadingLUT[(int)dist];
                        }
                        else
                        {
                            retVal[x, y].ExtendedAlpha -= source[x, y].ExtendedAlpha * fadingLUT[(int)dist];
                        }
                    }
                }
            }

            return(retVal);
        }
Exemple #30
0
        /// <summary>
        /// Build an ImageAdapter based on an existing IImageAdapter
        /// </summary>
        /// <param name="imageAdapterToClone"></param>
        public ImageAdapter(IImageAdapter imageAdapterToClone)
        {
            // Check argument
            if (imageAdapterToClone == null)
            {
                throw new ArgumentNullException("imageAdapterToClone", "Argument passed in must be set to valid instanceof the object (null was passed in)");
            }

            if (imageAdapterToClone.Width <= 0 || imageAdapterToClone.Height <= 0)
            {
                string errorMessage = string.Empty;
                string actualValue  = string.Empty;

                if (imageAdapterToClone.Width <= 0)
                {
                    errorMessage += "ImageAdapter Width is invalid (should be strictly > 0)\n";
                    actualValue  += "Width=" + imageAdapterToClone.Width + "\n";
                }

                if (imageAdapterToClone.Height <= 0)
                {
                    errorMessage += "ImageAdapter Height is invalid (should be strictly > 0)";
                    actualValue  += "Height=" + imageAdapterToClone.Height;
                }

                throw new ArgumentOutOfRangeException("imageAdapterToClone", actualValue, errorMessage);
            }

            _colors = new IColor[imageAdapterToClone.Width, imageAdapterToClone.Height];
            for (int y = 0; y < imageAdapterToClone.Height; y++)
            {
                for (int x = 0; x < imageAdapterToClone.Width; x++)
                {
                    if (imageAdapterToClone[x, y] != null)
                    {
                        _colors[x, y] = (IColor)imageAdapterToClone[x, y].Clone();
                    }
                }
            }
            if (imageAdapterToClone.Metadata != null)
            {
                _metadataInfo = (IMetadataInfo)imageAdapterToClone.Metadata.Clone();
            }
        }