Beispiel #1
0
 /// <summary>
 /// Applies the DrawableComposite operation to the <see cref="Drawables" />.
 /// </summary>
 /// <param name="x">The X coordinate.</param>
 /// <param name="y">The Y coordinate.</param>
 /// <param name="compose">The algorithm to use.</param>
 /// <param name="image">The image to draw.</param>
 /// <returns>The <see cref="Drawables" /> instance.</returns>
 public IDrawables <QuantumType> Composite(double x, double y, CompositeOperator compose, IMagickImage <QuantumType> image)
 {
     _drawables.Add(new DrawableComposite(x, y, compose, image));
     return(this);
 }
Beispiel #2
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DrawableComposite"/> class.
 /// </summary>
 /// <param name="x">The X coordinate.</param>
 /// <param name="y">The Y coordinate.</param>
 /// <param name="image">The image to draw.</param>
 public DrawableComposite(double x, double y, IMagickImage <QuantumType> image)
     : this(x, y, CompositeOperator.In, image)
 {
 }
Beispiel #3
0
        private DrawableComposite(IMagickImage <QuantumType> image)
        {
            Throw.IfNull(nameof(image), image);

            _image = image;
        }
Beispiel #4
0
        public static void RemoveImageArtifacts(this IConnectedComponentsSettings self, IMagickImage <QuantumType> image)
        {
            if (self.AngleThreshold != null)
            {
                image.RemoveArtifact("connected-components:angle-threshold");
            }

            if (self.AreaThreshold != null)
            {
                image.RemoveArtifact("connected-components:area-threshold");
            }

            if (self.CircularityThreshold != null)
            {
                image.RemoveArtifact("connected-components:circularity-threshold");
            }

            if (self.DiameterThreshold != null)
            {
                image.RemoveArtifact("connected-components:diameter-threshold");
            }

            if (self.EccentricityThreshold != null)
            {
                image.RemoveArtifact("connected-components:eccentricity-threshold");
            }

            if (self.MajorAxisThreshold != null)
            {
                image.RemoveArtifact("connected-components:major-axis-threshold");
            }

            if (self.MeanColor)
            {
                image.RemoveArtifact("connected-components:mean-color");
            }

            if (self.MinorAxisThreshold != null)
            {
                image.RemoveArtifact("connected-components:minor-axis-threshold");
            }

            if (self.PerimeterThreshold != null)
            {
                image.RemoveArtifact("connected-components:perimeter-threshold");
            }
        }
Beispiel #5
0
        private void CalculateWidthAndHeightWithDimensions(IMagickImage image)
        {
            var aspect = image.Width / (double)image.Height;

            CalculateWidthAndHeightWithDimensions(aspect);
        }
Beispiel #6
0
        private List <List <System.Drawing.Color> > ToPixels(IMagickImage image)
        {
            var pixels = image.GetPixels();

            return(LinqExtensions.FromTo(0, image.Height).Select(y => LinqExtensions.FromTo(0, image.Width).Select(x => pixels.GetPixel(x, y).ToColor().ToColor()).ToList()).ToList());
        }
Beispiel #7
0
 /// <summary>
 /// Adds a new instance of the <see cref="DrawableComposite" /> class to the <see cref="Drawables" />.
 /// </summary>
 /// <param name="x">The X coordinate.</param>
 /// <param name="y">The Y coordinate.</param>
 /// <param name="compose">The algorithm to use.</param>
 /// <param name="image">The image to draw.</param>
 /// <returns>The <see cref="Drawables" /> instance.</returns>
 public Drawables Composite(double x, double y, CompositeOperator compose, IMagickImage image)
 {
     _drawables.Add(new DrawableComposite(x, y, compose, image));
     return(this);
 }
Beispiel #8
0
 private static void LosslessCompress(IMagickImage <QuantumType> image)
 {
     image.Strip();
     MagickImage.GetSettings(image).Interlace = Interlace.NoInterlace;
 }
Beispiel #9
0
 private static void LosslessCompress(IMagickImage image)
 {
     image.Strip();
     image.Settings.Interlace = Interlace.NoInterlace;
 }
Beispiel #10
0
 /// <summary>
 /// Adds a new instance of the <see cref="DrawableComposite" /> class to the <see cref="Drawables" />.
 /// </summary>
 /// <param name="x">The X coordinate.</param>
 /// <param name="y">The Y coordinate.</param>
 /// <param name="image">The image to draw.</param>
 /// <returns>The <see cref="Drawables" /> instance.</returns>
 public Drawables Composite(double x, double y, IMagickImage image)
 {
     _Drawables.Add(new DrawableComposite(x, y, image));
     return(this);
 }
Beispiel #11
0
 public void Composite(double x, double y, double width, double height, CompositeOperator compositeOperator, IMagickImage image)
 {
     _nativeInstance.Composite(x, y, width, height, compositeOperator, image);
 }
Beispiel #12
0
 /// <summary>
 /// Adds a new instance of the <see cref="DrawableComposite" /> class to the <see cref="Drawables" />.
 /// </summary>
 /// <param name="offset">The offset from origin.</param>
 /// <param name="image">The image to draw.</param>
 /// <returns>The <see cref="Drawables" /> instance.</returns>
 public Drawables Composite(MagickGeometry offset, IMagickImage image)
 {
     _Drawables.Add(new DrawableComposite(offset, image));
     return(this);
 }
Beispiel #13
0
 private static void Test_Image(IMagickImage image)
 {
     Assert.AreEqual(765, image.Width);
     Assert.AreEqual(361, image.Height);
     Assert.AreEqual(MagickFormat.Ai, image.Format);
 }
Beispiel #14
0
 public Task SaveSpriteAsync(IMagickImage sprite)
 {
     sprite.Write(SpriteFilename);
     return(Task.CompletedTask);
 }
Beispiel #15
0
        private SortedList <double, Point> FindTemplateCandidates(IMagickImage searchArea, IMagickImage template, MagickGeometry bounds, IProgress <double> progress, double threshold, HashSet <Point> tried)
        {
            Console.WriteLine("Searching an area {0}x{1} in {4}x{5} for {2}x{3} at {6}x{7}", bounds.Width, bounds.Height, template.Width, template.Height, searchArea.Width, searchArea.Height, bounds.X, bounds.Y);
            var templatePixels = ToPixels(template);
            var searchPixels   = ToPixels(searchArea);

            var candidates = new SortedList <double, Point>(new DuplicateKeyComparer <double>());

            double totalCycles   = (bounds.Width - template.Width) * (bounds.Height - template.Height);
            double currentCycles = 0;

            for (var y = bounds.Y; y < bounds.Y + bounds.Height - templatePixels.Count; y++)
            {
                var row = searchPixels[y];
                for (var x = bounds.X; x < bounds.X + bounds.Width - templatePixels.First().Count; x++)
                {
                    var point = new Point(x, y);
                    if (!tried.Contains(point))
                    {
                        var sumOfDistance    = 0.0;
                        var totalComparisons = 0.0;

                        var m2    = 0.0;
                        var mean  = 0.0;
                        var count = 0;

                        for (var y2 = 0; y2 < templatePixels.Count; y2++)
                        {
                            var templateRow = templatePixels[y2];

                            for (var x2 = 0; x2 < templateRow.Count; x2++)
                            {
                                var distance = PixelDistance(searchPixels[y + y2][x + x2], templateRow[x2]);

                                count++;
                                var delta = distance - mean;
                                mean = mean + delta / count;
                                var delta2 = distance = mean;
                                m2 = m2 + delta * delta2;

                                sumOfDistance += distance;
                                totalComparisons++;
                            }
                        }

                        var averageDistance = sumOfDistance / totalComparisons;

                        var variance = m2 / (count - 1);
                        if (averageDistance <= threshold && variance < 100000)
                        {
                            candidates.Add(averageDistance, point);
                        }
                        tried.Add(point);
                    }

                    progress.Report(currentCycles / totalCycles);
                    currentCycles++;
                }
            }
            return(candidates);
        }
Beispiel #16
0
        internal static void SetImageArtifacts(this IConnectedComponentsSettings self, IMagickImage <QuantumType> image)
        {
            if (self.AreaThreshold != null)
            {
                image.SetArtifact("connected-components:area-threshold", self.AreaThreshold.Value.ToString(CultureInfo.InvariantCulture));
            }

            if (self.MeanColor)
            {
                image.SetArtifact("connected-components:mean-color", "true");
            }
        }
Beispiel #17
0
        // TODO: Name of this method + signature is a mess
        private SearchResult FindTemplateInImage(IMagickImage needleImage, Gravity needleGravity, IMagickImage haystack, StitchTask task, Point anchor)
        {
            // Resize needle
            var pixelMagnification = 8.0;
            var magnification      = Math.Min(1 / (double)pixelMagnification, 1.0);
            var progress           = (IProgress <double>)task;

            var resizeAmount = new Percentage(magnification * 100);
            var template     = needleImage.Clone();

            template.Resize(resizeAmount);
            template.RePage();

            IMagickImage searchArea = null;
            var          resized    = false;

            while (!resized)
            {
                try
                {
                    lock (haystack)
                    {
                        searchArea = haystack.Clone();
                        searchArea.Resize(resizeAmount);
                        searchArea.RePage();
                    }
                    resized = true;
                } catch (AccessViolationException)
                {
                    Console.WriteLine("Corrupt Memory, trying again");
                    Thread.Sleep(500);
                }
            }

            // We need to get the actual values here, since Resize() has unexpected rounding logic
            // (only supports whole digit percentages) and if we don't use the actual values then
            // scaling math won't work properly.
            var oldWidth  = searchArea.Width;
            var oldHeight = searchArea.Height;

            var bounds     = new MagickGeometry(0, 0, searchArea.Width, searchArea.Height);
            var candidates = FindTemplateCandidates(searchArea, template, bounds, progress, 2000, new HashSet <Point>());

            if (candidates.Any())
            {
                var bestScore = candidates.First().Key;
                this.initialCandidates = candidates.Where(x => x.Key < bestScore * 1.05).Select(x => {
                    return(new Point(x.Value.X / magnification, x.Value.Y / magnification));
                }).ToList();
            }


            while (pixelMagnification > 1 && candidates.Any())
            {
                var newCandidates         = new SortedList <double, Point>(new DuplicateKeyComparer <double>());
                var newPixelMagnification = pixelMagnification / 2;
                var newMagnification      = Math.Min(1 / (double)newPixelMagnification, 1.0);
                var newResizeAmount       = new Percentage(newMagnification * 100);
                var threshold             = 2000.0;
                var bestSeen  = threshold;
                var bestScore = candidates.First().Key;
                var toLoop    = candidates.Where(x => x.Key < bestScore * 1.05);
                Console.WriteLine("Considering {0} candidates at {1}", toLoop.Count(), newMagnification);

                IMagickImage newHaystack = null;
                lock (haystack)
                {
                    newHaystack = haystack.Clone();
                    newHaystack.Resize(newResizeAmount);
                    newHaystack.RePage();
                }

                var t2 = needleImage.Clone();
                t2.Resize(newResizeAmount);
                t2.RePage();

                var cache = new HashSet <Point>();

                foreach (var candidate in toLoop)
                {
                    var point  = new Point(candidate.Value.X / oldWidth * newHaystack.Width, candidate.Value.Y / oldHeight * newHaystack.Height);
                    var margin = newPixelMagnification;

                    var clampedBounds = new MagickGeometry(
                        (int)(point.X - margin),
                        (int)(point.Y - margin),
                        (int)(NeedleSize * newMagnification + margin * 2),
                        (int)(NeedleSize * newMagnification + margin * 2)
                        );
                    clampedBounds.X      = Math.Max(0, clampedBounds.X);
                    clampedBounds.Y      = Math.Max(0, clampedBounds.Y);
                    clampedBounds.Width  = Math.Min(newHaystack.Width - clampedBounds.X, clampedBounds.Width);
                    clampedBounds.Height = Math.Min(newHaystack.Height - clampedBounds.Y, clampedBounds.Height);

                    var toAdd = FindTemplateCandidates(newHaystack, t2, clampedBounds, this, threshold, cache);
                    foreach (var add in toAdd)
                    {
                        newCandidates.Add(add.Key, add.Value);
                        if (add.Key < bestSeen)
                        {
                            bestSeen = add.Key;
                            Console.WriteLine("Updating best score: {0}", bestSeen);
                        }
                    }
                }
                candidates         = newCandidates;
                magnification      = newMagnification;
                pixelMagnification = newPixelMagnification;
                oldWidth           = newHaystack.Width;
                oldHeight          = newHaystack.Height;
            }

            Console.WriteLine("============ Final: {0}", candidates.Count);

            if (candidates.Any())
            {
                var bestCandidate = candidates.First();

                return(new SearchResult()
                {
                    Distance = bestCandidate.Key,
                    HaystackPoint = bestCandidate.Value,
                    NeedlePoint = anchor
                });
            }
            return(SearchResult.Null);
        }
        public async Task <IActionResult> UploadPhotos(ICollection <IFormFile> files)
        {
            if (Request.Form.Files.Count <= 0)
            {
                return(BadRequest("No Files"));
            }

            var userId = ControllerUtility.GetUserID(this._httpContextAccessor);

            if (userId == null)
            {
                return(StatusCode(401));
            }

            // Only care about the first file
            var file = Request.Form.Files[0];

            var fileSize  = file.Length;
            var filename1 = file.FileName;
            var idx1      = filename1.LastIndexOf('.');
            var fileext   = filename1.Substring(idx1);

            var filerst = new PhotoFileSuccess();

            // Copy file to uploads folder
            filerst.deleteType = "DELETE";
            var randomFileName = Guid.NewGuid().ToString("N");

            filerst.name = randomFileName;
            var targetfilename = randomFileName + fileext;

            filerst.size = (int)fileSize;
            // To avoid mass change the existing records in db, the URL won't return.
            // filerst.url = "PhotoFile/" + targetfilename;
            // filerst.thumbnailUrl = "PhotoFile/" + randomFileName + ".thumb" + fileext;
            filerst.url          = targetfilename;
            filerst.thumbnailUrl = randomFileName + ".thumb" + fileext;
            filerst.deleteUrl    = filerst.url;

            PhotoFileErrorResult   errrst  = null;
            PhotoFileSuccessResult succrst = new PhotoFileSuccessResult();

            try
            {
                var filePath    = Path.Combine(Startup.UploadFolder, targetfilename);
                var thmFilePath = Path.Combine(Startup.UploadFolder, randomFileName + ".thumb" + fileext);
                using (var fileStream = new FileStream(filePath, FileMode.Create))
                {
                    await file.CopyToAsync(fileStream);

                    using (IMagickImage image = new MagickImage(filePath))
                    {
                        filerst.width  = image.Width;
                        filerst.height = image.Height;

                        // Add the photo
                        var pht = new Photo();
                        pht.PhotoId = randomFileName;
                        pht.Title   = pht.PhotoId;
                        pht.Desp    = pht.PhotoId;
                        pht.FileUrl = filerst.url;
                        var exifprofile = image.GetExifProfile();
                        if (exifprofile != null)
                        {
                            // AV Number
                            IExifValue value = exifprofile.Values.FirstOrDefault(val => val.Tag == ExifTag.ApertureValue);
                            try
                            {
                                if (value != null)
                                {
                                    pht.AVNumber = value.GetValue().ToString();
                                }
                            }
                            catch
                            {
                                // DO nothing
                            }
                            // Camera Maker
                            value = exifprofile.Values.FirstOrDefault(val => val.Tag == ExifTag.Make);
                            try
                            {
                                if (value != null)
                                {
                                    pht.CameraMaker = value.GetValue().ToString();
                                }
                            }
                            catch
                            {
                                // DO nothing
                            }
                            // Camera Model
                            value = exifprofile.Values.FirstOrDefault(val => val.Tag == ExifTag.Model);
                            try
                            {
                                if (value != null)
                                {
                                    pht.CameraModel = value.GetValue().ToString();
                                }
                            }
                            catch
                            {
                                // DO nothing
                            }
                            // ISO number
                            value = exifprofile.Values.FirstOrDefault(val => val.Tag == ExifTag.ISOSpeed);
                            try
                            {
                                if (value != null)
                                {
                                    pht.ISONumber = (int)value.GetValue();
                                }
                            }
                            catch
                            {
                                // DO nothing
                            }
                            // Lens Model
                            value = exifprofile.Values.FirstOrDefault(val => val.Tag == ExifTag.LensModel);
                            try
                            {
                                if (value != null)
                                {
                                    pht.LensModel = value.GetValue().ToString();
                                }
                            }
                            catch
                            {
                                // DO nothing
                            }
                            // Shutter Speed
                            value = exifprofile.Values.FirstOrDefault(val => val.Tag == ExifTag.ShutterSpeedValue);
                            try
                            {
                                if (value != null)
                                {
                                    pht.ShutterSpeed = (string)value.GetValue();
                                }
                            }
                            catch
                            {
                                // DO nothing
                            }
                        }

                        var bThumbnailCreated = false;

                        // Retrieve the exif information
                        ExifProfile profile = (ExifProfile)image.GetExifProfile();
                        if (profile != null)
                        {
                            using (IMagickImage thumbnail = profile.CreateThumbnail())
                            {
                                // Check if exif profile contains thumbnail and save it
                                if (thumbnail != null)
                                {
                                    thumbnail.Write(thmFilePath);
                                    bThumbnailCreated = true;

                                    filerst.thumbwidth  = thumbnail.Width;
                                    filerst.thumbheight = thumbnail.Height;

                                    pht.ThumbnailFileUrl = filerst.thumbnailUrl;
                                    pht.ThumbHeight      = filerst.thumbheight;
                                    pht.ThumbWidth       = filerst.thumbwidth;
                                    pht.IsOrgThumbnail   = true;
                                }
                            }
                        }

                        if (!bThumbnailCreated)
                        {
                            MagickGeometry size = new MagickGeometry(256, 256);
                            // This will resize the image to a fixed size without maintaining the aspect ratio.
                            // Normally an image will be resized to fit inside the specified size.
                            size.IgnoreAspectRatio = false;

                            image.Resize(size);
                            filerst.thumbwidth  = image.Width;
                            filerst.thumbheight = image.Height;

                            pht.ThumbnailFileUrl = filerst.thumbnailUrl;
                            pht.ThumbHeight      = filerst.thumbheight;
                            pht.ThumbWidth       = filerst.thumbwidth;
                            pht.IsOrgThumbnail   = false;

                            // Save the result
                            image.Write(thmFilePath);
                        }

                        pht.UploadedBy   = userId;
                        pht.UploadedTime = DateTime.Now;
                        this._context.Photos.Add(pht);

                        _context.SaveChanges();
                    }
                }

                succrst.files = new List <PhotoFileSuccess>();
                succrst.files.Append(filerst);
            }
            catch (Exception exp)
            {
                errrst = new PhotoFileErrorResult();
                var fileerr = new PhotoFileError();
                fileerr.error = exp.Message;
                fileerr.name  = filename1;
                errrst.files  = new List <PhotoFileError>();
                errrst.files.Append(fileerr);
            }

            if (errrst != null)
            {
                return(new JsonResult(errrst));
            }
            return(new JsonResult(filerst));
        }
Beispiel #19
0
 /// <summary>
 /// Adds a new instance of the <see cref="DrawableComposite" /> class to the <see cref="Drawables" />.
 /// </summary>
 /// <param name="offset">The offset from origin.</param>
 /// <param name="compose">The algorithm to use.</param>
 /// <param name="image">The image to draw.</param>
 /// <returns>The <see cref="Drawables" /> instance.</returns>
 public Drawables Composite(MagickGeometry offset, CompositeOperator compose, IMagickImage image)
 {
     _drawables.Add(new DrawableComposite(offset, compose, image));
     return(this);
 }
 /// <summary>
 /// initializing constructor
 /// </summary>
 /// <param name="image"></param>
 public MagickImageLuminanceSource(IMagickImage image)
     : base(CalculateLuminance(image), image.Width, image.Height)
 {
 }
 internal MagickSearchResult(IMagickImage image, MagickGeometry bestMatch, double similarityMetric)
 {
     SimilarityImage  = image;
     BestMatch        = bestMatch;
     SimilarityMetric = similarityMetric;
 }
Beispiel #22
0
        public void CreateErrorInfo_ValueIsNull_ReturnsNull()
        {
            IMagickImage image = null;

            Assert.IsNull(image.CreateErrorInfo());
        }
Beispiel #23
0
        private static double GetMean(IMagickImage image)
        {
            var mean = image.Statistics().GetChannel(PixelChannel.Composite).Mean;

            return(mean * 100 / Quantum.Max);
        }
Beispiel #24
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DrawableComposite"/> class.
 /// </summary>
 /// <param name="offset">The offset from origin.</param>
 /// <param name="image">The image to draw.</param>
 public DrawableComposite(MagickGeometry offset, IMagickImage image)
     : this(offset, CompositeOperator.In, image)
 {
 }
 public void Map(IMagickImage <QuantumType> image, IQuantizeSettings settings, IMagickImage <QuantumType> remapImage)
 {
     using (INativeInstance settingsNative = QuantizeSettings.CreateInstance(settings))
     {
         IntPtr exception = IntPtr.Zero;
         #if PLATFORM_AnyCPU
         if (NativeLibrary.Is64Bit)
         #endif
         #if PLATFORM_x64 || PLATFORM_AnyCPU
         NativeMethods.X64.MagickImageCollection_Map(image.GetInstance(), settingsNative.Instance, remapImage.GetInstance(), out exception);
         #endif
         #if PLATFORM_AnyCPU
         else
         #endif
         #if PLATFORM_x86 || PLATFORM_AnyCPU
         NativeMethods.X86.MagickImageCollection_Map(image.GetInstance(), settingsNative.Instance, remapImage.GetInstance(), out exception);
         #endif
         CheckException(exception);
     }
 }
 private static void TestPixels(IMagickImage image, MagickColor color)
 {
     TestPixels(image, color, color);
 }
Beispiel #27
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DrawableComposite"/> class.
 /// </summary>
 /// <param name="offset">The offset from origin.</param>
 /// <param name="image">The image to draw.</param>
 public DrawableComposite(IMagickGeometry offset, IMagickImage <QuantumType> image)
     : this(offset, CompositeOperator.In, image)
 {
 }
 private static void TestResizeResult(IMagickImage result)
 {
     Assert.AreEqual("Magick.NET.Resize", result.Comment);
     Assert.AreEqual(62, result.Width);
     Assert.AreEqual(59, result.Height);
 }
Beispiel #29
0
 private void ExecuteClone(XmlElement element, IMagickImage image)
 {
     Execute(element, image.Clone());
 }
Beispiel #30
0
 /// <summary>
 /// Applies the DrawableComposite operation to the <see cref="Drawables" />.
 /// </summary>
 /// <param name="offset">The offset from origin.</param>
 /// <param name="compose">The algorithm to use.</param>
 /// <param name="image">The image to draw.</param>
 /// <returns>The <see cref="Drawables" /> instance.</returns>
 public IDrawables <QuantumType> Composite(IMagickGeometry offset, CompositeOperator compose, IMagickImage <QuantumType> image)
 {
     _drawables.Add(new DrawableComposite(offset, compose, image));
     return(this);
 }