Skip to content

Instantly share code, notes, and snippets.

@vschep
Created September 22, 2016 10:05
Show Gist options
  • Select an option

  • Save vschep/8a2151c857b58957f67d1c2ae2f52631 to your computer and use it in GitHub Desktop.

Select an option

Save vschep/8a2151c857b58957f67d1c2ae2f52631 to your computer and use it in GitHub Desktop.
#I __SOURCE_DIRECTORY__
#r @"bin/Debug/EvalWrapper.dll"
open Microsoft.MSR.CNTK.Extensibility.Managed
open System.Drawing
open System.Collections.Generic
open System
let createModel modelPath =
let model = new IEvaluateModelManagedF()
model.CreateNetwork((sprintf "modelPath=\"%s\"" modelPath))
model
let imageToCntkList imgPath =
// create bitmap
let img = Image.FromFile(imgPath)
let bmp = new Bitmap(img)
//iterate over bitmap
let cntkList = new List<float32>(2 * bmp.Height * bmp.Width)
for c in 0..2 do
for h in 0..(bmp.Height-1) do
for w in 0..(bmp.Width-1) do
let pixel = bmp.GetPixel(w, h)
let value =
match c with
| 0 -> pixel.B
| 1 -> pixel.G
| 2 -> pixel.R
| _ -> failwith "No such channel"
|> float32
cntkList.Add(value)
cntkList
let imgToFeatures imgPath =
let imgList = imageToCntkList imgPath
let feature = new Dictionary<string,List<float32>>(HashIdentity.Structural)
feature.["features"] <- imgList
feature
let getIdxOfMaxVal aSequence =
aSequence |> Array.ofSeq |> Array.indexed |> Array.maxBy snd |> fst
let predictImage (model:IEvaluateModelManagedF) imgPath =
let features = imgToFeatures imgPath
let evalResult = (model.Evaluate(features, "z"))
getIdxOfMaxVal evalResult
let model = createModel "path to trained model file"
predictImage model "path to an image file"
model.Dispose()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment