Пример #1
0
        public static Image DrawOneScaledIndexSpectrogramTile(
            LdSpectrogramConfig config,
            IndexGenerationData indexGenerationData,
            Dictionary <string, IndexProperties> indexProperties,
            TimeSpan startTime,
            TimeSpan dataScale,
            TimeSpan imageScale,
            int superTileImageWidth,
            Dictionary <string, double[, ]> spectra,
            string basename,
            ImageChrome chromeOption)
        {
            Contract.Requires(!spectra.IsNullOrEmpty());

            // calculate data duration from column count of abitrary matrix
            var      matrix       = spectra.First().Value;
            int      columnCount  = matrix.GetLength(1);
            TimeSpan dataDuration = TimeSpan.FromSeconds(columnCount * dataScale.TotalSeconds);

            var analysisStartTime = indexGenerationData.RecordingStartDate.Value.TimeOfDay.Add(indexGenerationData.AnalysisStartOffset);

            TimeSpan offsetTime        = TimeSpan.Zero;
            TimeSpan imageDuration     = TimeSpan.FromTicks(superTileImageWidth * imageScale.Ticks);
            TimeSpan halfImageDuration = TimeSpan.FromTicks(superTileImageWidth * imageScale.Ticks / 2);

            if (startTime < TimeSpan.Zero)
            {
                offsetTime = TimeSpan.Zero - startTime;
                startTime  = TimeSpan.Zero;
            }

            TimeSpan endTime = startTime + imageDuration;

            if (endTime > dataDuration)
            {
                endTime = dataDuration;
            }

            // get the plain unchromed spectrogram
            Image ldSpectrogram = ZoomCommon.DrawIndexSpectrogramCommon(
                config,
                indexGenerationData,
                indexProperties,
                startTime,
                endTime,
                dataScale,
                imageScale,
                superTileImageWidth,
                spectra,
                basename);

            if (chromeOption == ImageChrome.Without)
            {
                return(ldSpectrogram);
            }

            Graphics g2 = Graphics.FromImage(ldSpectrogram);

            int nyquist = 22050 / 2;

            if (indexGenerationData.SampleRateResampled > 0)
            {
                nyquist = indexGenerationData.SampleRateResampled / 2;
            }

            int hertzInterval = 1000;

            if (config != null)
            {
                hertzInterval = config.YAxisTicInterval;
            }

            string title = $"ZOOM SCALE={imageScale.TotalSeconds}s/pixel";

            Image titleBar = ZoomFocusedSpectrograms.DrawTitleBarOfZoomSpectrogram(title, ldSpectrogram.Width);

            startTime    += analysisStartTime;
            ldSpectrogram = ZoomFocusedSpectrograms.FrameZoomSpectrogram(
                ldSpectrogram,
                titleBar,
                startTime,
                imageScale,
                config.XAxisTicInterval,
                nyquist,
                hertzInterval);

            // create the base image
            Image    image = new Bitmap(ldSpectrogram.Width, ldSpectrogram.Height);
            Graphics g1    = Graphics.FromImage(image);

            g1.Clear(Color.DarkGray);

            var xOffset = (int)(offsetTime.Ticks / imageScale.Ticks);

            g1.DrawImage(ldSpectrogram, xOffset, 0);

            return(image);
        }
Пример #2
0
        public static void Execute(Arguments arguments)
        {
            if (arguments == null)
            {
                throw new NoDeveloperMethodException();
            }

            string description;

            switch (arguments.ZoomAction)
            {
            case Arguments.ZoomActionType.Focused:
                description =
                    "# DRAW STACK OF FOCUSED MULTI-SCALE LONG DURATION SPECTROGRAMS DERIVED FROM SPECTRAL INDICES.";
                break;

            case Arguments.ZoomActionType.Tile:
                description =
                    "# DRAW ZOOMING SPECTROGRAMS DERIVED FROM SPECTRAL INDICES OBTAINED FROM AN AUDIO RECORDING";
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            LoggedConsole.WriteLine(description);

            LoggedConsole.WriteLine("# Spectrogram Zooming config  : " + arguments.SpectrogramZoomingConfig);
            LoggedConsole.WriteLine("# Input Directory             : " + arguments.SourceDirectory);
            LoggedConsole.WriteLine("# Output Directory            : " + arguments.Output);

            var common = new ZoomParameters(
                arguments.SourceDirectory.ToDirectoryInfo(),
                arguments.SpectrogramZoomingConfig.ToFileInfo(),
                !string.IsNullOrEmpty(arguments.OutputFormat));

            LoggedConsole.WriteLine("# File name of recording      : " + common.OriginalBasename);

            // create file systems for reading input and writing output. It gets
            //arguments.SourceDirectory.ToDirectoryInfo(),
            //arguments.Output.ToDirectoryInfo(),

            var io = FileSystemProvider.GetInputOutputFileSystems(
                arguments.SourceDirectory,
                FileSystemProvider.MakePath(arguments.Output, common.OriginalBasename, arguments.OutputFormat, "Tiles"))
                     .EnsureInputIsDirectory();

            switch (arguments.ZoomAction)
            {
            case Arguments.ZoomActionType.Focused:
                // draw a focused multi-resolution pyramid of images
                TimeSpan focalTime;
                if (arguments.FocusMinute.HasValue)
                {
                    focalTime = TimeSpan.FromMinutes(arguments.FocusMinute.Value);
                }
                else
                {
                    throw new ArgumentException("FocusMinute is null, cannot proceed");
                }

                ZoomFocusedSpectrograms.DrawStackOfZoomedSpectrograms(
                    arguments.SourceDirectory.ToDirectoryInfo(),
                    arguments.Output.ToDirectoryInfo(),
                    io,
                    common,
                    AcousticIndices.TowseyAcoustic,
                    focalTime,
                    imageWidth: 1500);
                break;

            case Arguments.ZoomActionType.Tile:
                // Create the super tiles for a full set of recordings
                ZoomTiledSpectrograms.DrawTiles(
                    io,
                    common,
                    AcousticIndices.TowseyAcoustic);

                break;

            default:
                Log.Warn("Other ZoomAction results in standard LD Spectrogram to be drawn");

                // draw standard false color spectrograms - useful to check what spectrograms of the individual
                // indices are like.

                throw new NotImplementedException();

                /*LDSpectrogramRGB.DrawSpectrogramsFromSpectralIndices(
                 * arguments.SourceDirectory,
                 * arguments.Output,
                 * arguments.SpectrogramConfigPath,
                 * arguments.IndexPropertiesConfig);*/
                break;
            }
        }
Пример #3
0
        /// <summary>
        /// HERVE GLOTIN
        /// Combined audio2csv + zooming spectrogram task.
        /// This is used to analyse Herve Glotin's BIRD50 data set.
        /// ############################# IMPORTANT ########################################
        /// In order to analyse the short recordings in BIRD50 dataset, need following change to code:
        /// need to modify    AudioAnalysis.AnalysisPrograms.AcousticIndices.cs #line648
        /// need to change    AnalysisMinSegmentDuration = TimeSpan.FromSeconds(20),
        /// to                AnalysisMinSegmentDuration = TimeSpan.FromSeconds(1),
        /// THIS iS to analyse BIRD50 short recordings.
        /// </summary>
        public static void HiRes1()
        {
            string recordingPath = @"C:\SensorNetworks\WavFiles\TestRecordings\TEST_7min_artificial.wav";

            //// HERVE GLOTIN BIRD50 TRAINING RECORDINGS
            //DirectoryInfo dataDir = new DirectoryInfo(@"D:\SensorNetworks\WavFiles\Glotin\Bird50\AmazonBird50_training_input");
            //string parentDir = @"C:\SensorNetworks\Output\BIRD50";
            //string speciesLabelsFile = parentDir + @"\AmazonBird50_training_output.csv";
            //int speciesCount = 50;
            //////set file name format -depends on train or test. E.g.  "ID0003";
            //string fileStemFormatString = "ID{0:d4}";   // for training files
            //string indexPropertiesConfig = @"C:\Work\GitHub\audio-analysis\AudioAnalysis\AnalysisConfigFiles\IndexPropertiesConfigHiRes.yml";
            //string learningMode = "Train";

            //// HERVE GLOTIN BIRD50 TESTING RECORDINGS
            DirectoryInfo dataDir = new DirectoryInfo(@"D:\SensorNetworks\WavFiles\Glotin\Bird50\AmazonBird50_testing_input");
            string parentDir = @"C:\SensorNetworks\Output\BIRD50";
            string speciesLabelsFile = null;
            int speciesCount = 50;
            ////set file name format -depends on train or test. E.g.  "ID0003";
            string fileStemFormatString = "ID1{0:d3}"; // for testing files
            string indexPropertiesConfig = @"C:\Work\GitHub\audio-analysis\AudioAnalysis\AnalysisConfigFiles\IndexPropertiesConfigHiRes.yml";
            string learningMode = "Test";

            // HERVE GLOTIN BOMBYX WHALE RECORDINGS
            //DirectoryInfo dataDir = new DirectoryInfo(@"C:\SensorNetworks\WavFiles\WhaleFromGlotin");
            //string parentDir = @"C:\SensorNetworks\Output\Glotin\Bombyx_SpermWhales";
            //string speciesLabelsFile = null;
            //int speciesCount = 0;
            //////set file name format -depends on train or test. E.g.  "ID0003";
            //string fileStemFormatString = null;
            ////string fileStemFormatString = "ID1{0:d3}"; // for testing files
            //string indexPropertiesConfig = @"C:\Work\GitHub\audio-analysis\AudioAnalysis\AnalysisConfigFiles\IndexPropertiesConfigHiResGianniPavan.yml";
            //string learningMode = "Train";

            // GIANNI PAVAN SASSAFRAS RECORDINGS
            //DirectoryInfo dataDir = new DirectoryInfo(@"C:\SensorNetworks\WavFiles\GianniPavan\SABIOD - TEST SASSOFRATINO");
            //string parentDir = @"C:\SensorNetworks\Output\GianniPavan";
            //string speciesLabelsFile = null;
            //int speciesCount = 0;
            //string fileStemFormatString = null;
            //string indexPropertiesConfig = @"C:\Work\GitHub\audio-analysis\AudioAnalysis\AnalysisConfigFiles\IndexPropertiesConfigHiResGianniPavan.yml";
            //string learningMode = "Train";

            // ######################################################################

            string outputDir = parentDir + @"\" + learningMode;
            string imageOutputDir = parentDir + @"\" + learningMode + "Images";
            string csvDir = outputDir + @"\Towsey.Acoustic";
            string zoomOutputDir = outputDir;

            string audio2csvConfigPath = @"C:\Work\GitHub\audio-analysis\AudioAnalysis\AnalysisConfigFiles\Towsey.AcousticHiRes.yml";
            string hiResZoomConfigPath = @"C:\Work\GitHub\audio-analysis\AudioAnalysis\AnalysisConfigFiles\SpectrogramHiResConfig.yml";

            FileInfo[] wavFiles = { new FileInfo(recordingPath) };

            // comment next two lines when debugging a single recording file
            string match = @"*.wav";
            wavFiles = dataDir.GetFiles(match, SearchOption.AllDirectories);

            // READ IN THE SPECIES LABELS FILE AND SET UP THE DATA
            string[] fileID = new string[wavFiles.Length];
            int[] speciesID = new int[speciesCount];
            if (speciesLabelsFile != null)
            {
                BirdClefExperiment1.ReadGlotinsSpeciesLabelFile(speciesLabelsFile, wavFiles.Length, out fileID, out speciesID);
            }
            else // make seperate species name for each file
            {
                speciesID = new int[wavFiles.Length];
            }

            //LOOP THROUGH ALL WAV FILES
            //for (int i = 538; i < 539; i++)
            //for (int i = 0; i < 8; i++)
            for (int i = 0; i < wavFiles.Length; i++)
            {
                FileInfo file = wavFiles[i];
                recordingPath = file.FullName;
                string idName = Path.GetFileNameWithoutExtension(file.FullName);
                string name = string.Format("{0}_Species{1:d2}", idName, speciesID[i]);
                outputDir = parentDir + @"\" + learningMode + @"\" + name;
                csvDir = parentDir + @"\" + learningMode + @"\" + name + @"\Towsey.Acoustic";
                zoomOutputDir = outputDir;
                Console.WriteLine("\n\n");
                Console.WriteLine($@">>>>{i}: File<{name}>");

                try
                {
                    // A: analyse the recording files == audio2csv.
                    var audio2csvArguments = new AnalyseLongRecordings.AnalyseLongRecording.Arguments
                    {
                        Source = recordingPath.ToFileInfo(),
                        Config = audio2csvConfigPath,
                        Output = outputDir.ToDirectoryInfo(),
                    };

                    if (!audio2csvArguments.Source.Exists)
                    {
                        LoggedConsole.WriteWarnLine(" >>>>>>>>>>>> WARNING! The Source Recording file cannot be found! This will cause an exception.");
                    }

                    if (!File.Exists(audio2csvArguments.Config))
                    {
                        LoggedConsole.WriteWarnLine(" >>>>>>>>>>>> WARNING! The Configuration file cannot be found! This will cause an exception.");
                    }

                    AnalyseLongRecordings.AnalyseLongRecording.Execute(audio2csvArguments);

                    // B: Concatenate the summary indices and produce images
                    // Use the Zoomingspectrograms action.

                    // need to find out how long the recording is.
                    string fileName = audio2csvArguments.Source.BaseName();
                    string testFileName = fileName + @"__Towsey.Acoustic.ACI.csv";
                    List<string> data = FileTools.ReadTextFile(Path.Combine(csvDir, testFileName));
                    int lineCount = data.Count - 1;  // -1 for header.
                    int imageWidth = lineCount;

                    //assume scale is index calculation duration = 0.1s
                    // i.e. image resolution  0.1s/px. or 600px/min
                    double focalMinute = (double)lineCount / 600 / 2;
                    if (focalMinute < 0.016666)
                    {
                        focalMinute = 0.016666; // shortest recording = 1 second.
                    }

                    var zoomingArguments = new DrawZoomingSpectrograms.Arguments
                    {
                        // use the default set of index properties in the AnalysisConfig directory.
                        SourceDirectory = csvDir,
                        Output = zoomOutputDir,
                        SpectrogramZoomingConfig = hiResZoomConfigPath,

                        // draw a focused multi-resolution pyramid of images
                        ZoomAction = DrawZoomingSpectrograms.Arguments.ZoomActionType.Focused,
                    };

                    LoggedConsole.WriteLine("# Spectrogram Zooming config  : " + zoomingArguments.SpectrogramZoomingConfig);
                    LoggedConsole.WriteLine("# Input Directory             : " + zoomingArguments.SourceDirectory);
                    LoggedConsole.WriteLine("# Output Directory            : " + zoomingArguments.Output);

                    var common = new ZoomParameters(zoomingArguments.SourceDirectory.ToDirectoryEntry(), zoomingArguments.SpectrogramZoomingConfig.ToFileEntry(), false);
                    var io = FileSystemProvider.GetInputOutputFileSystems(
                        zoomingArguments.SourceDirectory,
                        FileSystemProvider.MakePath(zoomingArguments.Output, common.OriginalBasename, zoomingArguments.OutputFormat, "Tiles"))
                        .EnsureInputIsDirectory();

                    // Create directory if not exists
                    if (!Directory.Exists(zoomingArguments.Output))
                    {
                        Directory.CreateDirectory(zoomingArguments.Output);
                    }

                    ZoomFocusedSpectrograms.DrawStackOfZoomedSpectrograms(
                        zoomingArguments.SourceDirectory.ToDirectoryInfo(),
                        zoomingArguments.Output.ToDirectoryInfo(),
                        io,
                        common,
                        AcousticIndices.TowseyAcoustic,
                        TimeSpan.FromMinutes(focalMinute),
                        imageWidth);

                    // DRAW THE VARIOUS IMAGES
                    string fileStem = fileName;
                    if (fileStemFormatString != null)
                    {
                        fileStem = string.Format(fileStemFormatString, i + 1); // training images
                    }

                    var ldfcSpectrogramArguments = new DrawLongDurationSpectrograms.Arguments
                    {
                        // use the default set of index properties in the AnalysisConfig directory.
                        InputDataDirectory = csvDir,
                        OutputDirectory = imageOutputDir,
                        IndexPropertiesConfig = indexPropertiesConfig,
                    };

                    // there are two possible tasks
                    // 1: draw the aggregated grey scale spectrograms
                    int secDuration = DrawLongDurationSpectrograms.DrawAggregatedSpectrograms(ldfcSpectrogramArguments, fileStem);

                    // 2: draw the coloured ridge spectrograms
                    secDuration = DrawLongDurationSpectrograms.DrawRidgeSpectrograms(ldfcSpectrogramArguments, fileStem);

                    // copy files
                    // POW, EVN, SPT, RHZ, RVT, RPS, RNG
                    // WARNING: POW was removed December 2018
                    string[] copyArray = { "POW", "EVN", "SPT", "RHZ", "RVT", "RPS", "RNG" };
                    DirectoryInfo sourceDirectory = new DirectoryInfo(csvDir);
                    string destinationDirectory = parentDir + @"\TrainingClassifier";
                    foreach (string key in copyArray)
                    {
                        // ID0002__Towsey.Acoustic.BGN.csv    fileName += @"__Towsey.Acoustic.ACI.csv";
                        string sourceFileName = string.Format(idName + "__Towsey.Acoustic." + key + ".csv");
                        string sourcePath = Path.Combine(sourceDirectory.FullName, sourceFileName);
                        string nameOfParentDirectory = sourceDirectory.Parent.Name;
                        string destinationFileName = string.Format(nameOfParentDirectory + "." + key + ".csv");
                        string destinationPath = Path.Combine(destinationDirectory, destinationFileName);
                        File.Copy(sourcePath, destinationPath, true);
                    }
                } // try block
                catch (Exception e)
                {
                    LoggedConsole.WriteErrorLine(string.Format("ERROR!!!!! RECORDING {0}   FILE {1}", i, name));
                    LoggedConsole.WriteErrorLine(string.Format(e.ToString()));
                }
            } // end loop through all wav files
        } // HiRes1()