a26abfc3a84a6611dc6afc0d451d39e67460bd03
[master-thesis.git] / Parasitemia / ParasitemiaUI / Program.fs
1 module ParasitemiaUI.Main
2
3 open System
4 open System.IO
5 open System.Threading
6
7 open Emgu.CV
8 open Emgu.CV.Structure
9
10 open Logger
11
12 open ParasitemiaCore.Utils
13 open ParasitemiaCore.Config
14
15 type Input =
16 | File of string
17 | Dir of string
18
19 type RunningMode =
20 | CmdLine of Input * string // A file or a directory to process and the output directory.
21 | Window of string option // An optional path to a file to open can be given in window mode.
22
23 type Arguments = RunningMode * bool
24
25 let parseArgs (args: string[]) : Arguments =
26
27 let output = Array.tryFindIndex ((=) "--output") args
28
29 let runningMode =
30 match Array.tryFindIndex ((=) "--folder") args, output with
31 | Some i, Some i_output when i < args.Length - 2 && i_output < args.Length - 2 ->
32 CmdLine ((Dir args.[i + 1]), args.[i_output + 1])
33 | _ ->
34 match Array.tryFindIndex ((=) "--file") args, output with
35 | Some i, Some i_output when i < args.Length - 2 && i_output < args.Length - 2 ->
36 CmdLine ((File args.[i + 1]), args.[i_output + 1])
37 |_ ->
38 Window (if args.Length > 0 && not (args.[0].StartsWith("--")) then Some args.[0] else None)
39
40 runningMode, Array.exists ((=) "--debug") args
41
42 let showArgsHelp () =
43 printfn "Usage of Parasitemia :"
44 printfn "Non-interactive mode:"
45 printfn " %s (--folder <folder>|--file <file>) --output <folder> [--debug]" System.AppDomain.CurrentDomain.FriendlyName
46 printfn " --folder <folder> : an input folder containing images to analyze"
47 printfn " --file <file> : an image file to be analyzed"
48 printfn " --output <folder> : a folder to put the results"
49 printfn " --debug: output more information like intermediate images if set"
50
51 printfn "Interactive mode:"
52 printfn " %s [<document-file>] [--debug]" System.AppDomain.CurrentDomain.FriendlyName
53 printfn " <document-file> : a PIAZ file to automatically open at startup"
54 printfn " --debug : output information like intermediate images if set in the current directory"
55
56 [<System.Runtime.InteropServices.DllImport("kernel32.dll")>]
57 extern bool AttachConsole(int dwProcessId)
58
59 [<EntryPoint>]
60 [<STAThread()>]
61 let main args =
62 // To redirect stdout to the attached console.
63 AttachConsole(-1) |> ignore // -1 to attach to the parent process.
64
65 if Array.exists (fun e -> e = "--help" || e = "-h") args
66 then
67 showArgsHelp ()
68 0
69 else
70 try
71 Log.User("Starting of Parasitemia UI ...")
72
73 let result =
74 match parseArgs args with
75 | mode, debug ->
76 let config = Config(defaultParameters)
77
78 match mode with
79 | CmdLine (input, output) ->
80 if debug
81 then
82 config.Debug <- DebugOn output
83
84 Directory.CreateDirectory output |> ignore
85
86 use logFile = new StreamWriter(new FileStream(Path.Combine(output, "log.txt"), FileMode.Append, FileAccess.Write))
87 let listener = { new IListener with member this.NewEntry severity mess = logFile.WriteLine(mess) }
88 Log.AddListener(listener)
89
90 Log.User (sprintf "=== New run : %A %A ===" DateTime.Now (if debug then "[DEBUG]" else "[RELEASE]"))
91
92 let files = match input with
93 | File file -> [ file ]
94 | Dir dir -> Directory.EnumerateFiles dir |> List.ofSeq
95
96 use resultFile = new StreamWriter(new FileStream(Path.Combine(output, "results.txt"), FileMode.Append, FileAccess.Write))
97
98 let images = [ for file in files -> Path.GetFileNameWithoutExtension(FileInfo(file).Name), config.Copy(), new Image<Bgr, byte>(file) ]
99
100 Log.LogWithTime("Whole analyze", Severity.USER, (fun () ->
101 match ParasitemiaCore.Analysis.doMultipleAnalysis images None with
102 | Some results ->
103 for id, cells in results do
104 let config, img = images |> List.pick (fun (id', config', img') -> if id' = id then Some (config', img') else None)
105 img.Dispose()
106 let total, infected = countCells cells
107 fprintf resultFile "File: %s %d %d %.2f (diameter: %A)\n" id total infected (100. * (float infected) / (float total)) config.RBCRadius
108 | None ->
109 fprintf resultFile "Analysis aborted"
110 Some ())) |> ignore
111
112 Log.RmListener(listener)
113 0
114
115 | Window fileToOpen ->
116 if debug then config.Debug <- DebugOn "."
117 GUI.run config fileToOpen
118
119 Log.User("Parasitemia UI closed")
120 result
121
122 with
123 | ex ->
124 Log.Fatal("Error: {0}", ex)
125 1