public static void InsertFile(string destinationFileName, Dictionary <int, string> pageList)
        {
            TiffBitmapEncoder encoder = new TiffBitmapEncoder();

            encoder.Compression = GetImageCompression(Image.FromFile(destinationFileName));

            for (int i = 0; i < GetPageCount(destinationFileName); i++)
            {
                BitmapDecoder decoder = TiffBitmapDecoder.Create(ReadFile(destinationFileName), BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                encoder.Frames.Add(decoder.Frames[i]);
            }

            foreach (var item in pageList)
            {
                BitmapDecoder newDecoder = TiffBitmapDecoder.Create(ReadFile(item.Value), BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                int           indx       = item.Key == 0 ? 0 : item.Key - 1;
                encoder.Frames.Insert(indx, newDecoder.Frames[0]);
            }

            MemoryStream memoryStream = new MemoryStream();

            encoder.Save(memoryStream);

            Stream UpdateFile = File.Open(destinationFileName, FileMode.Create, FileAccess.Write);

            UpdateFile.Write(memoryStream.ToArray(), 0, (int)memoryStream.Length);
            UpdateFile.Close();
            UpdateFile.Dispose();
        }
        /// <summary>
        /// Merges files to tifffile
        /// </summary>
        public static void MergeFiles(string destinationFileName, IEnumerable <string> filesToMerge)
        {
            TiffBitmapEncoder encoder = new TiffBitmapEncoder();

            encoder.Compression = GetImageCompression(Image.FromFile(filesToMerge.ElementAt(0)));

            foreach (var file in filesToMerge)
            {
                BitmapDecoder decoder = TiffBitmapDecoder.Create(
                    ReadFile(file), BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);

                for (int i = 0; i < decoder.Frames.Count; i++)
                {
                    encoder.Frames.Add(decoder.Frames[i]);
                }
            }

            MemoryStream memoryStream = new MemoryStream();

            encoder.Save(memoryStream);

            using (Stream stream = File.Open(destinationFileName, FileMode.CreateNew, FileAccess.Write))
            {
                stream.Write(memoryStream.ToArray(), 0, (int)memoryStream.Length);
            }
        }
        /// <summary>
        /// Rotates specified page in tifffile. Rotate angle should be 0, 90, 180, 270
        /// </summary>
        public static Stream Rotate(Stream stream, int pageIndex, double angle)
        {
            TiffBitmapDecoder decoder = (TiffBitmapDecoder)TiffBitmapDecoder.Create(
                stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);

            TiffBitmapEncoder encoder = new TiffBitmapEncoder();

            encoder.Compression = GetImageCompression(new Bitmap(stream));

            for (int i = 0; i < decoder.Frames.Count; i++)
            {
                if (i == pageIndex)
                {
                    encoder.Frames.Add(RotateImage(decoder.Frames[i], angle));
                }
                else
                {
                    encoder.Frames.Add(decoder.Frames[i]);
                }
            }

            MemoryStream imageStream = new MemoryStream();

            encoder.Save(imageStream);

            return(imageStream);
        }
        /// <summary>
        /// Swaps pages in tiff file
        /// </summary>
        /// <param name="fileName">Multitiff file name</param>
        /// <param name="sourcePageIndex">Source index</param>
        /// <param name="destinationPageIndex">Destination index</param>
        public static Stream SwapPages(Stream stream, int sourcePageIndex, int destinationPageIndex)
        {
            TiffBitmapDecoder decoder = (TiffBitmapDecoder)TiffBitmapDecoder.Create(
                stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);

            TiffBitmapEncoder encoder = new TiffBitmapEncoder();

            encoder.Compression = GetImageCompression(new Bitmap(stream));

            for (int i = 0; i < decoder.Frames.Count; i++)
            {
                if (i == sourcePageIndex)
                {
                    encoder.Frames.Add(decoder.Frames[destinationPageIndex]);
                }
                else if (i == destinationPageIndex)
                {
                    encoder.Frames.Add(decoder.Frames[sourcePageIndex]);
                }
                else
                {
                    encoder.Frames.Add(decoder.Frames[i]);
                }
            }

            MemoryStream imageStream = new MemoryStream();

            encoder.Save(imageStream);

            return(imageStream);
        }
        /// <summary>
        /// Returns the pages number in given tiff file
        /// </summary>
        public static int GetPageCount(string fileName)
        {
            using (Stream stream = File.OpenRead(fileName))
            {
                BitmapDecoder decoder = TiffBitmapDecoder.Create(
                    stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);

                return(decoder.Frames.Count);
            }
        }
        public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (values != null && values.Length == 2)
            {
                string fileName = values[0] as string;
                int    pageNo   = (int)values[1];

                string key = fileName + "_P" + pageNo.ToString();

                BitmapImage bitmapImage;

                if (bitmapCache.TryGetValue(key, out bitmapImage) == false)
                {
                    // Performance -  Do nothing while the system is running -
                    if (AppDataCenter.Singleton.IsRunning == true)
                    {
                        return(null);
                    }

                    lock (m_lock)
                    {
                        using (var srcFile = System.IO.File.OpenRead(fileName))
                        {
                            var dec = TiffBitmapDecoder.Create(srcFile, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);

                            var page = dec.Frames[pageNo - 1];

                            var buff = BitmapFrameToStream(page);

                            bitmapImage = new BitmapImage();

                            bitmapImage.BeginInit();
                            bitmapImage.CacheOption       = BitmapCacheOption.OnLoad;
                            bitmapImage.DecodePixelHeight = 200;
                            bitmapImage.StreamSource      = buff;
                            bitmapImage.CreateOptions     = BitmapCreateOptions.PreservePixelFormat;
                            bitmapImage.EndInit();

                            bitmapCache[key] = bitmapImage;
                        }
                    }
                }

                return(bitmapImage);
            }
            else
            {
                return(null);
            }
        }
        /// <summary>
        /// Splits multitiff to jpegs files
        /// </summary>
        public static void SplitFiles(string sourceFileName, IEnumerable <string> destinationFileNames, bool convertToJpeg)
        {
            string extension = convertToJpeg ? ".jpg" : ".prv";
            // Get compression
            var compression = GetImageCompression(Image.FromFile(sourceFileName));

            MemoryStream stream = ReadFile(sourceFileName);

            BitmapDecoder decoder = TiffBitmapDecoder.Create(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);

            for (int i = 0; i < destinationFileNames.Count(); i++)
            {
                MemoryStream outputStream = new MemoryStream();

                BitmapEncoder encoder = CreateBitmapEncoder(true, compression);

                if (i >= decoder.Frames.Count())
                {
                    continue;
                }

                encoder.Frames.Add(decoder.Frames[i]);

                encoder.Save(outputStream);
                string fileName = Path.Combine(Path.GetDirectoryName(destinationFileNames.ElementAt(i)), Path.GetFileNameWithoutExtension(destinationFileNames.ElementAt(i)) + extension);

                using (BinaryWriter writer = new BinaryWriter(File.Open(fileName, FileMode.Create, FileAccess.Write)))
                {
                    writer.Write(outputStream.ToArray());
                }
            }

            //destinationFileNames = destinationFileNames.Select(x =>
            //{
            //    x = (x == string.Empty) ? string.Empty : Path.Combine(Path.GetDirectoryName(x), Path.GetFileNameWithoutExtension(x) + extension);
            //    return x;
            //}).ToList();
        }
        public static TiffHeaderInfo ReadHeaderInfo(String filePath)
        {
            using (Stream fs = File.Open(filePath, FileMode.Open, FileAccess.Read))
            {
                try
                {
                    TiffHeaderInfo headerInfo = new TiffHeaderInfo();
                    BitmapDecoder  decoder    = TiffBitmapDecoder.Create(fs, BitmapCreateOptions.None, BitmapCacheOption.Default);
                    BitmapMetadata metadata   = decoder.Frames[0].Metadata as BitmapMetadata;

                    if (metadata != null)
                    {
                        List <RawMetadataItem> dataItems = new List <RawMetadataItem>();
                        CaptureMetadata(metadata, "", dataItems);


                        try
                        {
                            foreach (RawMetadataItem item in dataItems)
                            {
                                switch (item.location)
                                {
                                case NEW_SUBFILE_TYPE:
                                    break;

                                case IMAGE_WIDTH:
                                    headerInfo.ImageWidth = Convert.ToInt32(item.value);
                                    break;

                                case IMAGE_LENGTH:
                                    headerInfo.ImageLength = Convert.ToInt32(item.value);
                                    break;

                                case BITS_PER_SAMPLE:
                                    headerInfo.BitsPerSample = Convert.ToInt32(item.value);
                                    break;

                                case PHOTO_INTERP:
                                    headerInfo.PhotoInterpolation = Convert.ToInt32(item.value);
                                    break;

                                case IMAGE_DESCRIPTION:
                                    headerInfo.Description = item.value.ToString();
                                    break;

                                case STRIP_OFFSETS:
                                    headerInfo.StripOffsets = Convert.ToInt32(item.value);
                                    break;

                                case SAMPLES_PER_PIXEL:
                                    headerInfo.SamplesPerPixel = Convert.ToInt32(item.value);
                                    break;

                                case ROWS_PER_STRIP:
                                    headerInfo.RowsPerStrip = Convert.ToInt32(item.value);
                                    break;

                                case STRIP_BYTE_COUNT:
                                    headerInfo.StripByteCount = Convert.ToInt32(item.value);
                                    break;

                                case X_RESOLUTION:
                                    headerInfo.XResolution = ToRationalNumber((ulong)item.value);
                                    break;

                                case Y_RESOLUTION:
                                    headerInfo.YResolution = ToRationalNumber((ulong)item.value);
                                    break;

                                case RESOLUTION_UNIT:
                                    headerInfo.ResolutionUnit = Convert.ToInt32(item.value);
                                    break;

                                case COLOR_MAP:
                                    ushort[]   values = (ushort[])item.value;
                                    List <int> colors = new List <int>();
                                    foreach (ushort u in values)
                                    {
                                        colors.Add((int)u);
                                    }
                                    headerInfo.ColorMap = colors.ToArray();
                                    break;
                                }
                            }
                        }
                        catch (FormatException) { } // Ignore an unsuccessful cast, default values will remain
                        catch (InvalidCastException) { }
                    }

                    return(headerInfo);
                }
                finally
                {
                    fs.Close();
                }
            }
        }
Beispiel #9
0
        protected override void LoadData(object state)
        {
            m_reportsData.Clear();
            m_parameters.Clear();

            AppDataCenter.Singleton.StartAnalyzer();

            try
            {
                var vm = state as MultiRunConfigurationViewModel;

                // Build set of configuration according the selected parameters
                BuildConfigurations(vm.Parameters.Where(x => x.IsSelected == true).ToList());

                int noOfRuns = AppDataCenter.Singleton.SetupData.ClassifierConfigurations.Count();


                for (int i = 0; i < noOfRuns; i++)
                {
                    ReportData reportData = m_reportsData[i];

                    var startTime = DateTime.Now;

                    // Train...


                    try
                    {
                        ConcurrentBag <Page> trainPages = new ConcurrentBag <Page>();
                        Parallel.ForEach(AppDataCenter.Singleton.TrainPages.GroupBy(x => x.FileName), pagesDate =>
                        {
                            var dec = TiffBitmapDecoder.Create(new Uri(pagesDate.Key), BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
                            foreach (var pageData in pagesDate)
                            {
                                var frame = dec.Frames[pageData.PageNo - 1];
                                var image = ImageHelper.BitmapFromSource(frame);
                                var page  = new Page()
                                {
                                    Image     = image,
                                    ClassName = pageData.ClassName
                                };
                                trainPages.Add(page);

                                PageReportData pageReportData = new PageReportData()
                                {
                                    Page = pageData
                                };
                                pageReportData.ClassMatch.Clear();
                                pageReportData.ClassMatch.Add(page.ClassName, 1);
                                reportData.PagesReportData.Add(pageReportData);
                            }
                        });

                        ClassifierService.Service.Train(trainPages,
                                                        AppDataCenter.Singleton.SetupData.ClassifierConfigurations.ElementAt(i));

                        // Run...
                        Parallel.ForEach(AppDataCenter.Singleton.SetupData.Pages
                                         .Where(x => AppDataCenter.Singleton.TrainPages.Contains(x) == false)
                                         .GroupBy(x => x.FileName), pagesDate =>
                        {
                            var dec = TiffBitmapDecoder.Create(new Uri(pagesDate.Key), BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
                            foreach (var pageData in pagesDate)
                            {
                                var frame = dec.Frames[pageData.PageNo - 1];
                                var image = ImageHelper.BitmapFromSource(frame);
                                var page  = new Page()
                                {
                                    Image     = image,
                                    ClassName = ""
                                };
                                ClassifierService.Service.Run(page, null, classesMatch =>
                                {
                                    PageReportData pageReportData = new PageReportData()
                                    {
                                        Page = pageData
                                    };

                                    if (classesMatch.Count() > 0)
                                    {
                                        foreach (var classMatch in classesMatch)
                                        {
                                            pageReportData.ClassMatch.Add(classMatch.Key, classMatch.Value);
                                        }
                                    }
                                    else
                                    {
                                        pageReportData.ClassMatch.Clear();
                                    }
                                    reportData.PagesReportData.Add(pageReportData);
                                });
                            }
                        });
                    }
                    // In case the configuration is not valid
                    catch (Exception)
                    {
                    }

                    reportData.Duration = DateTime.Now - startTime;

                    // Add report data to system
                    AppDataCenter.Singleton.AddReportData(reportData);
                }

                if (AppDataCenter.Singleton.ReportsData.Count() > 2)
                {
                    var result = AppDataCenter.Singleton.ReportsData.OrderBy(x => x, new AppDataCenter.CompareReportData()).First();

                    AppDataCenter.Singleton.SetReportByParameter(result.ParameterValue);
                }
            }
            finally
            {
                AppDataCenter.Singleton.FinishAnalyzer();
            }
        }