Skip to content

Instantly share code, notes, and snippets.

@codec-abc
Last active August 7, 2017 14:37
Show Gist options
  • Select an option

  • Save codec-abc/e92ddfe1fcaf56b6f00a4994bea72113 to your computer and use it in GitHub Desktop.

Select an option

Save codec-abc/e92ddfe1fcaf56b6f00a4994bea72113 to your computer and use it in GitHub Desktop.
let nv21ToPPM() =
let clampBetween0And255 v =
if v < 0.0 then
0.0
else if v >= 255.0 then
255.0
else
v
let width = 1280
let height = 720
let bytes = IO.File.ReadAllBytes "NV21In.raw"
let content = System.Text.StringBuilder(width * height * 3 * 4)
let header = "P3\n" + width.ToString() + " " + height.ToString() + "\n255\n"
content.Append(header) |> ignore
let beginOfUVPlaneIndex = (width * height)
for j in 0 .. (height - 1) do
for i in 0 .. (width - 1) do
let y = double bytes.[j * width + i]
let delta = (j / 2) * width + 2 * (i / 2)
let cr = double bytes.[beginOfUVPlaneIndex + delta ] |> (fun a -> a - 128.0)
let cb = double bytes.[beginOfUVPlaneIndex + delta + 1] |> (fun a -> a - 128.0)
let r = (y + 1.40200 * cr);
let g = (y - 0.34414 * cb - 0.71414 * cr);
let b = (y + 1.77200 * cb);
let r = r |> (clampBetween0And255 >> int)
let g = g |> (clampBetween0And255 >> int)
let b = b |> (clampBetween0And255 >> int)
if i = 0 then
content.Append(r.ToString() + " " + g.ToString() + " " + b.ToString()) |> ignore
else
content.Append(" " + r.ToString() + " " + g.ToString() + " " + b.ToString()) |> ignore
content.Append("\n") |> ignore |> ignore
System.IO.File.WriteAllText("NV21.ppm", content.ToString())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment