#!/usr/bin/python
# 3D MRI - Converts a series of slices into a 3D grid of voxels.
# Render a series of slices on other axies.
# Copyright (C) November 2007 Neil Fraser
# http://neil.fraser.name/

# This program is free software; you can redistribute it and/or
# modify it under the terms of version 2 of the GNU General
# Public License as published by the Free Software Foundation.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# http://www.gnu.org/

import gd
import sys

x = 224
y = 256
z = 159

greyscale = True

# Obtain a colour in the colour palette of this image.
def getColourIndex(image, colour):
  global greyscale
  if greyscale:
    colour = (colour, colour, colour)
  colourIndex = image.colorExact(colour)
  if colourIndex == -1:
    colourIndex = image.colorAllocate(colour)
    if colourIndex == -1:
      colourIndex = image.colorClosest(colour)
      print "\nWarning, out of colour space."
  assert colourIndex != -1, "Failed to allocate colour"
  return colourIndex

# Build an empty 3D array of the correct size.
# Python is not the greatest language for this.
print "Initializing the image space",
a = []
for i in range(0, x):
  sys.stdout.write(".")
  sys.stdout.flush()
  a.append([])
  for j in range(0, y):
    a[i].append(range(0, z))
print "Done.\n"

print "Reading the LR image slices",
for k in range(0, z):
  sys.stdout.write(".")
  sys.stdout.flush()
  image = gd.image("LR/LR_%s.png" % ("000" + str(k))[-3:])
  for i in range(0, x):
    for j in range(0, y):
      colourIndex = image.getPixel((i, j))
      if greyscale:
        a[i][j][k] = colourIndex
      else:
        red = image.red(colourIndex)
        green = image.green(colourIndex)
        blue = image.blue(colourIndex)
        a[i][j][k] = (red, green, blue)
print "Done.\n"

print "Writing the TB image slices"
for j in range(0, y):
  sys.stdout.write(".")
  sys.stdout.flush()
  image = gd.image((x, z))
  for i in range(0, x):
    for k in range(0, z):
      colourIndex = getColourIndex(image, a[i][j][k])
      image.setPixel((i, k), colourIndex)
  image.writePng("TB/TB_%s.png" % ("000" + str(j))[-3:])
print "Done.\n"

print "Writing the FB image slices"
for i in range(0, x):
  sys.stdout.write(".")
  sys.stdout.flush()
  image = gd.image((z, y))
  for k in range(0, z):
    for j in range(0, y):
      colourIndex = getColourIndex(image, a[i][j][k])
      image.setPixel((k, j), colourIndex)
  image.writePng("FB/FB_%s.png" % ("000" + str(i))[-3:])
print "Done.\n"

