Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support non-byte volumes for MINC. Also fixes #259. #281

Merged
merged 1 commit into from
Nov 5, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions examples/css/volume-viewer-demo.css
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,8 @@ canvas.slice-display {
-moz-box-shadow: 1px 1px 0px 0px #787878;
-webkit-box-shadow: 1px 1px 0px 0px #787878;
box-shadow: 1px 1px 0px 0px #787878;
width: 2em;
width: 3em;
font-size: 10px;
}

.coords .control-inputs {
Expand Down Expand Up @@ -162,5 +163,8 @@ canvas.slice-display {
}

.intensity-value {
padding: 1px;
padding: 2px;
-moz-border-radius: 3px;
-webkit-border-radius: 3px;
border-radius: 3px;
}
84 changes: 74 additions & 10 deletions scripts/minc2volume-viewer.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
* Author: Tarek Sherif <tsherif@gmail.com> (http://tareksherif.ca/)
* Author: Nicolas Kassis
* Author: Paul Mougel
* Author: Robert D. Vincent <robert.d.vincent@mcgill.ca>
*/

/*
Expand All @@ -44,15 +45,37 @@
var fs = require("fs");
var exec = require("child_process").exec;
var spawn = require("child_process").spawn;
var version = "0.3.1";
var version = "0.3.2";

var datatypes = [
'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'float32', 'float64'
];

if (require.main === module) {
var filename = process.argv[2];
var args = process.argv.slice(2);
var arg;
while ((arg = args.shift()) !== undefined) {
var filename;
var datatype;
if (arg === '-T') {
datatype = args.shift();
if (datatypes.indexOf(datatype) < 0) {
printUsage();
process.exit(0);
}
}
else {
filename = arg;
}
}

if (filename === undefined) {
printUsage();
process.exit(0);
}
if (datatype === undefined) {
datatype = 'uint8';
}

fs.exists(filename, function(exists) {

Expand All @@ -73,15 +96,15 @@ if (require.main === module) {
console.log("Processing file:", filename);

console.log("Creating header file: ", basename + ".header");
getHeader(filename, function(err, header) {
getHeaderWithType(filename, datatype, function(err, header) {
if (err) {
return logExecutionError(err);
}
fs.writeFile(basename + ".header", JSON.stringify(header));
});

console.log("Creating raw data file: ", basename + ".raw");
rawDataStream = getRawDataStream(filename);
rawDataStream = getRawDataStream(filename, datatype);
rawDataStream.on('error', logExecutionError);
rawFileStream = fs.createWriteStream(basename + ".raw");
rawDataStream.pipe(rawFileStream);
Expand All @@ -90,6 +113,7 @@ if (require.main === module) {
});
} else {
module.exports.getHeader = getHeader;
module.exports.getHeaderWithType = getHeaderWithType;
module.exports.getRawDataStream = getRawDataStream;
}

Expand All @@ -99,11 +123,45 @@ if (require.main === module) {

function printUsage() {
console.log("minc2volume-viewer.js v" + version);
console.log("\nUsage: node minc2volume-viewer.js <filename>\n");
console.log("Usage: node minc2volume-viewer.js [-T <datatype>] <filename>");
console.log(" Where datatype is one of: ");
for (var k in datatypes)
console.log(" " + datatypes[k]);
}

function getRawDataStream(filename) {
var minctoraw = spawn("minctoraw", ["-byte", "-unsigned", "-normalize", filename]);
function getRawDataStream(filename, datatype) {
var args = ["-normalize", filename];

if (datatype === undefined)
datatype = 'uint8';

switch (datatype) {
case 'int8':
args.unshift('-byte', '-signed');
break;
case 'uint8':
args.unshift('-byte', '-unsigned');
break;
case 'int16':
args.unshift('-short', '-signed');
break;
case 'uint16':
args.unshift('-short', '-unsigned');
break;
case 'int32':
args.unshift('-int', '-signed');
break;
case 'uint32':
args.unshift('-int', '-unsigned');
break;
case 'float32':
args.unshift('-float');
break;
case 'float64':
args.unshift('-double');
break;
}
var minctoraw = spawn("minctoraw", args);
minctoraw.on("exit", function (code) {
if (code === null || code !== 0) {
var err = new Error("Process minctoraw failed with error code " + code);
Expand All @@ -117,7 +175,11 @@ function getRawDataStream(filename) {
}

function getHeader(filename, callback) {

getHeaderWithType(filename, 'uint8', callback);
}

function getHeaderWithType(filename, datatype, callback) {

function getSpace(filename, header, space, callback) {
header[space] = {};
exec("mincinfo -attval " + space + ":start " + filename, function(error, stdout) {
Expand Down Expand Up @@ -210,8 +272,10 @@ function getHeader(filename, callback) {
});
}

function buildHeader(filename, callback) {
function buildHeader(filename, datatype, callback) {
var header = {};

header.datatype = datatype;

getOrder(header, filename, function(err, header) {
if (err) {
Expand Down Expand Up @@ -240,7 +304,7 @@ function getHeader(filename, callback) {
});
}

buildHeader(filename, callback);
buildHeader(filename, datatype, callback);
}

function logExecutionError(error) {
Expand Down
87 changes: 60 additions & 27 deletions scripts/minc2volume-viewer.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
#!/usr/bin/env python3
#!/usr/bin/env python
#
# BrainBrowser: Web-based Neurological Visualization Tools
# (https://brainbrowser.cbrain.mcgill.ca)
#
# Copyright (C) 2011 McGill University
# Copyright (C) 2011 McGill University
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
Expand All @@ -19,34 +19,44 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.

# Author: Jon Pipitone <jon@pipitone.ca>
# Author: Robert D. Vincent <robert.d.vincent@mcgill.ca>
# (Made it work with Python 2.7, supported multiple voxel types)

from __future__ import print_function
import sys
import shutil
import os.path
import argparse
import subprocess
import json

required_minc_cmdline_tools = ['mincinfo', 'minctoraw']
required_minc_cmdline_tools = ['mincinfo', 'minctoraw']

def console_error(message, exit_code):
def console_error(message, exit_code):
print(message, file=sys.stderr)
sys.exit(1)
sys.exit(exit_code)

def console_log(message):
print(message)

def check_minc_tools_installed():
def which(pgm):
path=os.getenv('PATH')
for p in path.split(os.path.pathsep):
p=os.path.join(p, pgm)
if os.path.exists(p) and os.access(p, os.X_OK):
return p

def check_minc_tools_installed():
for tool in required_minc_cmdline_tools:
if not shutil.which(tool):
if not which(tool):
console_error(
"minc2volume-viewer.py requires that the MINC tools be installed.\n"
"Visit http://www.bic.mni.mcgill.ca/ServicesSoftware/MINC for info.", 1)

def cmd(command):
def cmd(command):
return subprocess.check_output(command.split(), universal_newlines=True).strip()

def get_space(mincfile, space):
def get_space(mincfile, space):
header = {
"start" : float(cmd("mincinfo -attval {}:start {}".format(space,mincfile))),
"space_length" : float(cmd("mincinfo -dimlength {} {}".format(space,mincfile))),
Expand All @@ -60,45 +70,63 @@ def get_space(mincfile, space):

return header

def make_header(mincfile, headerfile):
def make_header(mincfile, datatype, headerfile):
header = {}

header["datatype"] = datatype;

# find dimension order
order = cmd("mincinfo -attval image:dimorder {}".format(mincfile))
order = order.split(",")

if len(order) < 3 or len(order) > 4:
order = cmd("mincinfo -dimnames {}".format(mincfile))
order = order.split(" ")

header["order"] = order

if len(order) == 4:
if len(order) == 4:
time_start = cmd("mincinfo -attval time:start {}".format(mincfile))
time_length = cmd("mincinfo -dimlength time {}".format(mincfile))
header["time"] = { "start" : float(time_start),

header["time"] = { "start" : float(time_start),
"space_length" : float(time_length) }

# find space
header["xspace"] = get_space(mincfile,"xspace")
header["yspace"] = get_space(mincfile,"yspace")
header["xspace"] = get_space(mincfile,"xspace")
header["zspace"] = get_space(mincfile,"zspace")

if len(order) > 3:
header["time"] = get_space(mincfile,"time")

# write out the header
open(headerfile,"w").write(json.dumps(header))

def make_raw(mincfile, rawfile):
def make_raw(mincfile, datatype, rawfile):
raw = open(rawfile, "wb")
raw.write(
subprocess.check_output(["minctoraw","-byte","-unsigned","-normalize",mincfile]))

def main(filename):
args = ["-normalize", mincfile]
opts = {
"int8": ["-byte", "-signed"],
"uint8": ["-byte", "-unsigned"],
"int16": ["-short", "-signed"],
"uint16": ["-short", "-unsigned"],
"int32": ["-int", "-signed"],
"uint32": ["-int", "-unsigned"],
"int32": ["-int", "-signed"],
"uint32": ["-int", "-unsigned"],
"float32":["-float"],
"float64":["-double"],
}[datatype]
for opt in opts:
args.insert(0, opt)
args.insert(0, "minctoraw")
raw.write(
subprocess.check_output(args))

def main(filename, datatype):
if not os.path.isfile(filename):
console_error("File {} does not exist.".format(filename))
console_error("File {} does not exist.".format(filename), 1)

check_minc_tools_installed()

Expand All @@ -109,14 +137,19 @@ def main(filename):
console_log("Processing file: {}".format(filename))

console_log("Creating header file: {}".format(headername))
make_header(filename, headername)
make_header(filename, datatype, headername)

console_log("Creating raw data file: {}".format(rawname))
make_raw(filename, rawname)
make_raw(filename, datatype, rawname)

if __name__ == '__main__':
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("filename")
parser.add_argument("filename", help="the minc file to convert")
parser.add_argument("-T", dest="datatype",
choices=["int8", "int16", "int32",
"uint8", "uint16", "uint32",
"float32", "float64"],
action="store", default="uint8",
help="set the voxel data type of the output")
args = parser.parse_args()

main(args.filename)
main(args.filename, args.datatype)
15 changes: 2 additions & 13 deletions src/brainbrowser/volume-viewer/volume-loaders/mgh.js
Original file line number Diff line number Diff line change
Expand Up @@ -341,25 +341,14 @@
break;
}

var d = 0; // Generic loop counter.
var n_min = +Infinity;
var n_max = -Infinity;

for (d = 0; d < native_data.length; d++) {
if (native_data[d] > n_max)
n_max = native_data[d];
if (native_data[d] < n_min)
n_min = native_data[d];
}

header.voxel_min = n_min;
header.voxel_max = n_max;
VolumeViewer.utils.scanDataRange(native_data, header);

// Incrementation offsets for each dimension of the volume. MGH
// files store the fastest-varying dimension _first_, so the
// "first" dimension actually has the smallest offset. That is
// why this calculation is different from that for NIfTI-1.
//
var d;
var offset = 1;
for (d = 0; d < header.order.length; d++) {
header[header.order[d]].offset = offset;
Expand Down
Loading