// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [<assembly: AssemblyVersion("1.0.*")>]
-[<assembly: AssemblyVersion("1.0.0.5")>]
-[<assembly: AssemblyFileVersion("1.0.0.5")>]
+[<assembly: AssemblyVersion("1.0.0.6")>]
+[<assembly: AssemblyFileVersion("1.0.0.6")>]
do
()
\ No newline at end of file
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
// 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
// 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'.
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.
// 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
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
ellipsesWithNeigbors
|> List.choose (fun (e, neighbors) ->
- if e.Removed
+ if e.State = CellState.Removed
then
None
else
let nucleusPixels = List<Point>()
let parasitePixels = List<Point>()
- let mutable darkStainPixels = 0
let mutable nbElement = 0
let elements = new Matrix<byte>(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
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
factorNbValidPick = 0.06 //1.0
factorNbMaxPick = 4.
- darkStainLevel = 1.1
+ darkStainLevel = 1.
maxDarkStainRatio = 0.1 // 10 %
parasiteRadiusRatio = 0.5f // 50 %
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [<assembly: AssemblyVersion("1.0.*")>]
-[<assembly: AssemblyVersion("1.0.0.5")>]
-[<assembly: AssemblyFileVersion("1.0.0.5")>]
+[<assembly: AssemblyVersion("1.0.0.6")>]
+[<assembly: AssemblyFileVersion("1.0.0.6")>]
do
()
\ No newline at end of file
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
| :? 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)
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)
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 ()
// Information associated to a document.
type JSONInformation = {
patientID: string
- fileVersion: int
-}
+ fileVersion: int }
// Information associated to each images.
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"
runningMode, Array.exists ((=) "--debug") args
+let showArgsHelp () =
+ printfn "Usage of Parasitemia :"
+ printfn "Non-interactive mode:"
+ printfn " %s (--folder <folder>|--file <file>) --output <folder> [--debug]" System.AppDomain.CurrentDomain.FriendlyName
+ printfn " --folder <folder> : an input folder containing images to analyze"
+ printfn " --file <file> : an image file to be analyzed"
+ printfn " --output <folder> : a folder to put the results"
+ printfn " --debug: output more information like intermediate images if set"
+
+ printfn "Interactive mode:"
+ printfn " %s [<document-file>] [--debug]" System.AppDomain.CurrentDomain.FriendlyName
+ printfn " <document-file> : a PIAZ file to automatically open at startup"
+ printfn " --debug : output information like intermediate images if set in the current directory"
+
+[<System.Runtime.InteropServices.DllImport("kernel32.dll")>]
+extern bool AttachConsole(int dwProcessId)
+
[<EntryPoint>]
[<STAThread()>]
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<Bgr, byte>(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<Bgr, byte>(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
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
+ [<JsonIgnore>]
mutable infected: bool
+
+ [<JsonIgnore>]
mutable setManually: bool
center: Point
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">
<Grid Margin="3">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>