From: Greg Burri Date: Tue, 2 Feb 2016 23:01:45 +0000 (+0100) Subject: Peculiar elements overlap RBC now. X-Git-Tag: 1.0.11~17 X-Git-Url: http://git.euphorik.ch/index.cgi?a=commitdiff_plain;h=154264f33619b78e17182082b483cba97e128698;p=master-thesis.git Peculiar elements overlap RBC now. --- diff --git a/Parasitemia/ParasitemiaCore/AssemblyInfo.fs b/Parasitemia/ParasitemiaCore/AssemblyInfo.fs index 21b305e..f473726 100644 --- a/Parasitemia/ParasitemiaCore/AssemblyInfo.fs +++ b/Parasitemia/ParasitemiaCore/AssemblyInfo.fs @@ -34,8 +34,8 @@ open System.Runtime.InteropServices // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [] -[] -[] +[] +[] do () \ No newline at end of file diff --git a/Parasitemia/ParasitemiaCore/Classifier.fs b/Parasitemia/ParasitemiaCore/Classifier.fs index 0012a4f..ea3f9dd 100644 --- a/Parasitemia/ParasitemiaCore/Classifier.fs +++ b/Parasitemia/ParasitemiaCore/Classifier.fs @@ -10,10 +10,12 @@ open Emgu.CV.Structure open Types open Utils +type CellState = RBC = 1 | Removed = 2 | Peculiar = 3 + type private EllipseFlaggedKd (e: Ellipse) = inherit Ellipse (e.Cx, e.Cy, e.A, e.B, e.Alpha) - member val Removed = false with get, set + member val State = CellState.RBC with get, set interface KdTree.I2DCoords with member this.X = this.Cx @@ -38,32 +40,45 @@ let findCells (ellipses: Ellipse list) (parasites: ParasitesMarker.Result) (widt // Return 'true' if the point 'p' is owned by e. // The lines represents all intersections with other ellipses. - let pixelOwnedByE (p: PointF) (e: Ellipse) (others: (Ellipse * Line) list) = + let pixelOwnedByE (p: PointF) (e: EllipseFlaggedKd) (neighbors: (EllipseFlaggedKd * PointF * PointF) list) = e.Contains p.X p.Y && seq { let c = PointF(e.Cx, e.Cy) - for e', d1 in others do - let d2 = lineFromTwoPoints c p - let c' = PointF(e'.Cx, e'.Cy) - let v = pointFromTwoLines d1 (lineFromTwoPoints c c') - let case1 = sign (v.X - c.X) <> sign (v.X - c'.X) || Utils.squaredDistanceTwoPoints v c > Utils.squaredDistanceTwoPoints v c' - if not (Single.IsInfinity d2.A) + for e', d1 in neighbors + |> List.choose (fun (otherE, p1, p2) -> + if otherE.State = CellState.Removed + then None + else Some (otherE, Utils.lineFromTwoPoints p1 p2)) do + if e'.State = e.State // Peculiar vs peculiar or RBC vs RBC. then - let p' = Utils.pointFromTwoLines d1 d2 - let delta, delta' = - let dx1, dx2 = (c.X - p.X), (c.X - p'.X) - // To avoid rounding issue. - if abs dx1 < 0.01f || abs dx2 < 0.01f then c.Y - p.Y, c.Y - p'.Y else dx1, dx2 - - // Yield 'false' when the point is owned by another ellipse. - if case1 + let d2 = lineFromTwoPoints c p + let c' = PointF(e'.Cx, e'.Cy) + let v = pointFromTwoLines d1 (lineFromTwoPoints c c') + let case1 = sign (v.X - c.X) <> sign (v.X - c'.X) || Utils.squaredDistanceTwoPoints v c > Utils.squaredDistanceTwoPoints v c' + if not (Single.IsInfinity d2.A) then - yield sign delta <> sign delta' || Utils.squaredDistanceTwoPoints c p' > Utils.squaredDistanceTwoPoints c p + let p' = Utils.pointFromTwoLines d1 d2 + let delta, delta' = + let dx1, dx2 = (c.X - p.X), (c.X - p'.X) + // To avoid rounding issue. + if abs dx1 < 0.01f || abs dx2 < 0.01f then c.Y - p.Y, c.Y - p'.Y else dx1, dx2 + + // Yield 'false' when the point is owned by another ellipse. + if case1 + then + yield sign delta <> sign delta' || Utils.squaredDistanceTwoPoints c p' > Utils.squaredDistanceTwoPoints c p + else + yield sign delta = sign delta' && Utils.squaredDistanceTwoPoints c p' < Utils.squaredDistanceTwoPoints c p else - yield sign delta = sign delta' && Utils.squaredDistanceTwoPoints c p' < Utils.squaredDistanceTwoPoints c p + yield case1 + + elif e.State = CellState.Peculiar // A peculiar always win against a RBC. + then + yield true else - yield case1 + yield not <| e'.Contains p.X p.Y + } |> Seq.forall id let ellipses = ellipses |> List.map EllipseFlaggedKd @@ -71,7 +86,7 @@ let findCells (ellipses: Ellipse list) (parasites: ParasitesMarker.Result) (widt // 1) Associate touching ellipses with each ellipses and remove ellipse with more than two intersections. let tree = KdTree.Tree.BuildTree ellipses let neighbors (e: EllipseFlaggedKd) : (EllipseFlaggedKd * PointF * PointF) list = - if not e.Removed + if e.State <> CellState.Removed then tree.Search (searchRegion e) // We only keep the ellipses touching 'e'. @@ -80,24 +95,23 @@ let findCells (ellipses: Ellipse list) (parasites: ParasitesMarker.Result) (widt then match EEOver.EEOverlapArea e otherE with | Some (_, px, _) when px.Length > 2 -> - otherE.Removed <- true + otherE.State <- CellState.Removed None | Some (area, px, py) when area > 0.f && px.Length = 2 -> Some (otherE, PointF(px.[0], py.[0]), PointF(px.[1], py.[1])) | _ -> None else - None ) + None) else [] - // We reverse the list to get the lower score ellipses first. - let ellipsesWithNeigbors = ellipses |> List.map (fun e -> e, neighbors e) |> List.rev + let ellipsesWithNeigbors = ellipses |> List.map (fun e -> e, neighbors e) // 2) Remove ellipses touching the edges. let widthF, heightF = float32 width, float32 height for e in ellipses do - if e.isOutside widthF heightF then e.Removed <- true + if e.isOutside widthF heightF then e.State <- CellState.Removed // 3) Remove ellipses with a high standard deviation (high contrast). // Obsolete. It was useful when the ellipses result quality wasn't good. @@ -126,7 +140,7 @@ let findCells (ellipses: Ellipse list) (parasites: ParasitesMarker.Result) (widt // 4) Remove ellipses with little area. let minArea = config.RBCRadius.MinArea for e, neighbors in ellipsesWithNeigbors do - if not e.Removed + if e.State <> CellState.Removed then let minX, minY, maxX, maxY = ellipseWindow e @@ -134,13 +148,37 @@ let findCells (ellipses: Ellipse list) (parasites: ParasitesMarker.Result) (widt for y in (if minY < 0 then 0 else minY) .. (if maxY >= height then height - 1 else maxY) do for x in (if minX < 0 then 0 else minX) .. (if maxX >= width then width - 1 else maxX) do let p = PointF(float32 x, float32 y) - if pixelOwnedByE p e (neighbors |> List.choose (fun (otherE, p1, p2) -> if otherE.Removed then None else Some (otherE :> Ellipse, Utils.lineFromTwoPoints p1 p2))) + if pixelOwnedByE p e neighbors then area <- area + 1 if area < int minArea then - e.Removed <- true + e.State <- CellState.Removed + + // 5) Define non-rbc (peculiar) cells. + let darkStainData = parasites.darkStain.Data + ellipsesWithNeigbors + |> List.choose (fun (e, neighbors) -> + if e.State = CellState.Removed + then + None + else + let mutable darkStainPixels = 0 + let mutable nbElement = 0 + let minX, minY, maxX, maxY = ellipseWindow e + for y in minY .. maxY do + for x in minX .. maxX do + let p = PointF(float32 x, float32 y) + if pixelOwnedByE p e neighbors + then + nbElement <- nbElement + 1 + if darkStainData.[y, x, 0] > 0uy + then + darkStainPixels <- darkStainPixels + 1 + + if float darkStainPixels > config.Parameters.maxDarkStainRatio * (float nbElement) then Some e else None) + |> List.iter (fun e -> e.State <- CellState.Peculiar) // 5) Define pixels associated to each ellipse and create the cells. let diameterParasiteSquared = (2.f * config.RBCRadius.ParasiteRadius) ** 2.f |> roundInt @@ -152,7 +190,7 @@ let findCells (ellipses: Ellipse list) (parasites: ParasitesMarker.Result) (widt ellipsesWithNeigbors |> List.choose (fun (e, neighbors) -> - if e.Removed + if e.State = CellState.Removed then None else @@ -161,14 +199,13 @@ let findCells (ellipses: Ellipse list) (parasites: ParasitesMarker.Result) (widt let nucleusPixels = List() let parasitePixels = List() - let mutable darkStainPixels = 0 let mutable nbElement = 0 let elements = new Matrix(maxY - minY + 1, maxX - minX + 1) for y in minY .. maxY do for x in minX .. maxX do let p = PointF(float32 x, float32 y) - if pixelOwnedByE p e (neighbors |> List.choose (fun (otherE, p1, p2) -> if otherE.Removed then None else Some (otherE :> Ellipse, Utils.lineFromTwoPoints p1 p2))) + if pixelOwnedByE p e neighbors then elements.[y - minY, x - minX] <- 1uy nbElement <- nbElement + 1 @@ -181,20 +218,18 @@ let findCells (ellipses: Ellipse list) (parasites: ParasitesMarker.Result) (widt then parasitePixels.Add(Point(x, y)) - if darkStainData.[y, x, 0] > 0uy - then - darkStainPixels <- darkStainPixels + 1 - - let mutable parasiteArea = 0 - if nucleusPixels.Count > 0 - then - for parasitePixel in parasitePixels do - if nucleusPixels.Exists(fun p -> pown (p.X - parasitePixel.X) 2 + pown (p.Y - parasitePixel.Y) 2 <= diameterParasiteSquared) - then - parasiteArea <- parasiteArea + 1 + let parasiteArea = + if nucleusPixels.Count > 0 + then + seq { + for parasitePixel in parasitePixels do + if nucleusPixels.Exists(fun p -> pown (p.X - parasitePixel.X) 2 + pown (p.Y - parasitePixel.Y) 2 <= diameterParasiteSquared) + then yield 1 } |> Seq.sum + else + 0 let cellClass = - if float darkStainPixels > config.Parameters.maxDarkStainRatio * (float nbElement) + if e.State = CellState.Peculiar then Peculiar diff --git a/Parasitemia/ParasitemiaCore/Config.fs b/Parasitemia/ParasitemiaCore/Config.fs index 18c64cc..8159173 100644 --- a/Parasitemia/ParasitemiaCore/Config.fs +++ b/Parasitemia/ParasitemiaCore/Config.fs @@ -62,7 +62,7 @@ let defaultParameters = { factorNbValidPick = 0.06 //1.0 factorNbMaxPick = 4. - darkStainLevel = 1.1 + darkStainLevel = 1. maxDarkStainRatio = 0.1 // 10 % parasiteRadiusRatio = 0.5f // 50 % diff --git a/Parasitemia/ParasitemiaUI/AssemblyInfo.fs b/Parasitemia/ParasitemiaUI/AssemblyInfo.fs index 46c0c22..49cbbb3 100644 --- a/Parasitemia/ParasitemiaUI/AssemblyInfo.fs +++ b/Parasitemia/ParasitemiaUI/AssemblyInfo.fs @@ -34,8 +34,8 @@ open System.Runtime.InteropServices // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [] -[] -[] +[] +[] do () \ No newline at end of file diff --git a/Parasitemia/ParasitemiaUI/GUI.fs b/Parasitemia/ParasitemiaUI/GUI.fs index 8438b4b..0b0d6dd 100644 --- a/Parasitemia/ParasitemiaUI/GUI.fs +++ b/Parasitemia/ParasitemiaUI/GUI.fs @@ -273,7 +273,7 @@ let run (defaultConfig: Config) (fileToOpen: string option) = with | :? IOException as ex -> Log.Error(ex.ToString()) - MessageBox.Show(sprintf "The document cannot be save in '%s'" state.FilePath, "Error saving the document", MessageBoxButton.OK, MessageBoxImage.Error) |> ignore + MessageBox.Show(sprintf "The document cannot be save in \"%s\"" state.FilePath, "Error saving the document", MessageBoxButton.OK, MessageBoxImage.Error) |> ignore let saveCurrentDocumentAsNewFile () = match askDocumentPathToSave () with @@ -394,7 +394,7 @@ let run (defaultConfig: Config) (fileToOpen: string option) = | :? IOException as ex -> Log.Error(ex.ToString()) state.FilePath <- previousFilePath - MessageBox.Show(sprintf "The document cannot be loaded from '%s'" state.FilePath, "Error loading the document", MessageBoxButton.OK, MessageBoxImage.Error) |> ignore + MessageBox.Show(sprintf "The document cannot be loaded from \"%s\"" filepath, "Error loading the document", MessageBoxButton.OK, MessageBoxImage.Error) |> ignore let askLoadFile () = let dialog = OpenFileDialog(Filter = PiaZ.filter) @@ -425,7 +425,7 @@ let run (defaultConfig: Config) (fileToOpen: string option) = with | :? IOException as ex -> Log.Error(ex.ToString()) - MessageBox.Show(sprintf "The results cannot be exported in '%s'" state.FilePath, "Error exporting the files", MessageBoxButton.OK, MessageBoxImage.Error) |> ignore + MessageBox.Show(sprintf "The results cannot be exported in \"%s\"" state.FilePath, "Error exporting the files", MessageBoxButton.OK, MessageBoxImage.Error) |> ignore win.txtPatient.TextChanged.AddHandler(fun obj args -> state.PatientID <- win.txtPatient.Text) @@ -450,7 +450,7 @@ let run (defaultConfig: Config) (fileToOpen: string option) = with | _ as ex -> Log.Error(ex.ToString()) - MessageBox.Show(sprintf "Unable to read the image from '%s'" filename, "Error adding an image", MessageBoxButton.OK, MessageBoxImage.Error) |> ignore + MessageBox.Show(sprintf "Unable to read the image from \"%s\"" filename, "Error adding an image", MessageBoxButton.OK, MessageBoxImage.Error) |> ignore updateGlobalParasitemia () diff --git a/Parasitemia/ParasitemiaUI/PiaZ.fs b/Parasitemia/ParasitemiaUI/PiaZ.fs index bdd6d07..bb553b8 100644 --- a/Parasitemia/ParasitemiaUI/PiaZ.fs +++ b/Parasitemia/ParasitemiaUI/PiaZ.fs @@ -20,8 +20,7 @@ let filter = "PIA|*.piaz" // Information associated to a document. type JSONInformation = { patientID: string - fileVersion: int -} + fileVersion: int } // Information associated to each images. type JSONSourceImage = { @@ -34,13 +33,11 @@ type JSONSourceImage = { rbcs: RBC List healthyRBCBrightness: float32 // 0 to 1. - infectedRBCBrightness: float32 // 0 to 1. -} + infectedRBCBrightness: float32 } // 0 to 1. type DocumentData = { patientID: string - images: SourceImage list -} + images: SourceImage list } let mainEntryName = "info.json" let imageExtension = ".tiff" diff --git a/Parasitemia/ParasitemiaUI/Program.fs b/Parasitemia/ParasitemiaUI/Program.fs index ce7cdd4..a26abfc 100644 --- a/Parasitemia/ParasitemiaUI/Program.fs +++ b/Parasitemia/ParasitemiaUI/Program.fs @@ -39,63 +39,87 @@ let parseArgs (args: string[]) : Arguments = runningMode, Array.exists ((=) "--debug") args +let showArgsHelp () = + printfn "Usage of Parasitemia :" + printfn "Non-interactive mode:" + printfn " %s (--folder |--file ) --output [--debug]" System.AppDomain.CurrentDomain.FriendlyName + printfn " --folder : an input folder containing images to analyze" + printfn " --file : an image file to be analyzed" + printfn " --output : a folder to put the results" + printfn " --debug: output more information like intermediate images if set" + + printfn "Interactive mode:" + printfn " %s [] [--debug]" System.AppDomain.CurrentDomain.FriendlyName + printfn " : a PIAZ file to automatically open at startup" + printfn " --debug : output information like intermediate images if set in the current directory" + +[] +extern bool AttachConsole(int dwProcessId) + [] [] let main args = - try - Log.User("Starting of Parasitemia UI ...") - - let result = - match parseArgs args with - | mode, debug -> - let config = Config(defaultParameters) - - match mode with - | CmdLine (input, output) -> - if debug - then - config.Debug <- DebugOn output - - Directory.CreateDirectory output |> ignore - - use logFile = new StreamWriter(new FileStream(Path.Combine(output, "log.txt"), FileMode.Append, FileAccess.Write)) - let listener = { new IListener with member this.NewEntry severity mess = logFile.WriteLine(mess) } - Log.AddListener(listener) - - Log.User (sprintf "=== New run : %A %A ===" DateTime.Now (if debug then "[DEBUG]" else "[RELEASE]")) - - let files = match input with - | File file -> [ file ] - | Dir dir -> Directory.EnumerateFiles dir |> List.ofSeq - - use resultFile = new StreamWriter(new FileStream(Path.Combine(output, "results.txt"), FileMode.Append, FileAccess.Write)) - - - let images = [ for file in files -> Path.GetFileNameWithoutExtension(FileInfo(file).Name), config.Copy(), new Image(file) ] - - Log.LogWithTime("Whole analyze", Severity.USER, (fun () -> - match ParasitemiaCore.Analysis.doMultipleAnalysis images None with - | Some results -> - for id, cells in results do - let config, img = images |> List.pick (fun (id', config', img') -> if id' = id then Some (config', img') else None) - img.Dispose() - let total, infected = countCells cells - fprintf resultFile "File: %s %d %d %.2f (diameter: %A)\n" id total infected (100. * (float infected) / (float total)) config.RBCRadius - | None -> - fprintf resultFile "Analysis aborted" - Some ())) |> ignore - - Log.RmListener(listener) - 0 - - | Window fileToOpen -> - if debug then config.Debug <- DebugOn "." - GUI.run config fileToOpen - - Log.User("Parasitemia UI closed") - result - - with - | ex -> - Log.Fatal("Error: {0}", ex) - 1 \ No newline at end of file + // To redirect stdout to the attached console. + AttachConsole(-1) |> ignore // -1 to attach to the parent process. + + if Array.exists (fun e -> e = "--help" || e = "-h") args + then + showArgsHelp () + 0 + else + try + Log.User("Starting of Parasitemia UI ...") + + let result = + match parseArgs args with + | mode, debug -> + let config = Config(defaultParameters) + + match mode with + | CmdLine (input, output) -> + if debug + then + config.Debug <- DebugOn output + + Directory.CreateDirectory output |> ignore + + use logFile = new StreamWriter(new FileStream(Path.Combine(output, "log.txt"), FileMode.Append, FileAccess.Write)) + let listener = { new IListener with member this.NewEntry severity mess = logFile.WriteLine(mess) } + Log.AddListener(listener) + + Log.User (sprintf "=== New run : %A %A ===" DateTime.Now (if debug then "[DEBUG]" else "[RELEASE]")) + + let files = match input with + | File file -> [ file ] + | Dir dir -> Directory.EnumerateFiles dir |> List.ofSeq + + use resultFile = new StreamWriter(new FileStream(Path.Combine(output, "results.txt"), FileMode.Append, FileAccess.Write)) + + let images = [ for file in files -> Path.GetFileNameWithoutExtension(FileInfo(file).Name), config.Copy(), new Image(file) ] + + Log.LogWithTime("Whole analyze", Severity.USER, (fun () -> + match ParasitemiaCore.Analysis.doMultipleAnalysis images None with + | Some results -> + for id, cells in results do + let config, img = images |> List.pick (fun (id', config', img') -> if id' = id then Some (config', img') else None) + img.Dispose() + let total, infected = countCells cells + fprintf resultFile "File: %s %d %d %.2f (diameter: %A)\n" id total infected (100. * (float infected) / (float total)) config.RBCRadius + | None -> + fprintf resultFile "Analysis aborted" + Some ())) |> ignore + + Log.RmListener(listener) + 0 + + | Window fileToOpen -> + if debug then config.Debug <- DebugOn "." + GUI.run config fileToOpen + + Log.User("Parasitemia UI closed") + result + + with + | ex -> + Log.Fatal("Error: {0}", ex) + 1 \ No newline at end of file diff --git a/Parasitemia/ParasitemiaUI/Types.fs b/Parasitemia/ParasitemiaUI/Types.fs index 92d39b8..e29465c 100644 --- a/Parasitemia/ParasitemiaUI/Types.fs +++ b/Parasitemia/ParasitemiaUI/Types.fs @@ -7,13 +7,18 @@ open System.Windows.Media open Emgu.CV open Emgu.CV.Structure +open Newtonsoft.Json + let healthyRBColor = Color.FromRgb(255uy, 255uy, 0uy) // Yellow-green. let infectedRBColor = Color.FromRgb(255uy, 0uy, 40uy) // Red with a bit of blue. type RBC = { num: int + [] mutable infected: bool + + [] mutable setManually: bool center: Point diff --git a/Parasitemia/ParasitemiaUI/XAML/PPICalculatorWindow.xaml b/Parasitemia/ParasitemiaUI/XAML/PPICalculatorWindow.xaml index d52a144..2ac8540 100644 --- a/Parasitemia/ParasitemiaUI/XAML/PPICalculatorWindow.xaml +++ b/Parasitemia/ParasitemiaUI/XAML/PPICalculatorWindow.xaml @@ -3,7 +3,7 @@ xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" - x:Name="PPICalculatorWindow" Height="200" Width="378.5" MinHeight="200" MinWidth="280" Title="About" Icon="pack://application:,,,/Resources/icon.ico"> + x:Name="PPICalculatorWindow" Height="200" Width="378.5" MinHeight="200" MinWidth="280" Title="PPI Calculator" Icon="pack://application:,,,/Resources/icon.ico">