Pixpipejs

v0.2.0

_CORE

The core of Pixpipe is a list of the base classes that most of Pixpipe objects will inherit from. Some are supposed to be used extensively by developers (Signal1D, Image2D, Image3D) and some are just fundamental parts that work in the shadow (Filter, PixpipeContainer, PixpipeObject).
Make sure you understand who is who before you start.

CoreTypes

CoreTypes is bit of an exception in Pixpipejs because it does not inherit from PixpipeObject and it contains only static methods. In a sens, it's comparable to a singleton that stores all the core types constructors of Pixpipe so that they can be retrived only by querying their name.

At the creation of a new type, the static method .addCoreType() should be called right after the closing curly bracket of the class declaration. This is if we want to reference this class as a core type.

new CoreTypes()
Static Members
addCoreType(typeClass)
getCoreType(typeName)

Decoder

The class Decoder is an interface and is not supposed to be used as-is. The file decoderd (in the decoder folder) must inherit from this class because it implements some handy logic, for example the static function isBinary to tell if the associated format is binary or text based. In addition, it has a method to convert a utf8 binary buffer into a utf8 string. This is usefull in case the associated filetype is text based but the given buffer (of a valid file) is encoded in a binary way. The metadata targetType must be overwritten with a string matching one of the Pixpipe type (e.g. "Image3DAlt");

new Decoder()

Extends Filter

Static Members
isBinary()

Filter

Filter is a base class and must be inherited to be used properly. A filter takes one or more Image instances as input and returns one or more instances of images as output. Every filter has a addInput(), a getOutput() and a update() methods. Every input and output can be arranged by category, so that internaly, a filter can use and output diferent kind of data.

Usage

new Filter()

Extends PixpipeObject

Static Members
TYPE()
Instance Members
_run()
addInput(inputObject, category)
addInputValidator(category, InputType)
clearAllInputs()
forEachOutput(cb)
getInputCategories()
getNumberOfInputs()
getNumberOfOutputs()
getOutput(category)
getOutputCategories()
hasEvent(eventName)
hasInputOfCategory(category)
hasValidInput()
on(eventId, callback)
setMetadata(key, value)
triggerEvent(eventName, any)
update()

Image2D

Image2D class is one of the few base element of Pixpipejs. It is always considered to be 4 channels (RGBA) and stored as a Float32Array typed array.

Usage

new Image2D(options: Object)

Extends PixpipeContainer

Parameters
options (Object = null) if present:
  • options.width {Number} width in pixel
  • options.height {Number} height in pixel
  • options.color {Array} can be [r, g, b, a] or just [i]. Optional.
Static Members
TYPE()
Instance Members
clone()
computeSimpleStat()
float32Clone()
get1dIndexFrom2dPosition(position)
get2dPositionFrom1dIndex(i)
getAvg()
getComponentsPerPixel()
getData()
getDataAsFloat32Array()
getDataAsUInt8Array()
getDataCopy()
getHeight()
getMax()
getMin()
getNcpp()
getPixel(position)
getSegmentSample(posFrom, posTo)
getWidth()
hollowClone()
isInside(pos)
setData(array, width, height, ncpp, deepCopy)
setPixel(position, color, computeStat)

Image3D

Image3D class is one of the few base element of Pixpipejs. It is always considered to be 4 channels (RGBA) and stored as a Float32Array typed array.

new Image3D(options: Object)

Extends PixpipeContainer

Parameters
options (Object = null) may contain the following:
  • options.xSize {Number} space length along x axis
  • options.ySize {Number} space length along y axis
  • options.zSize {Number} space length along z axis
  • options.tSize {Number} space length along t axis (time)
  • options.ncpp {Number} number of components per pixel. Default = 1 If at least xSize, ySize and zSize are specified, a buffer is automatically initialized with the value 0.
Static Members
TYPE()
Instance Members
addTransformation(transform, name)
clone()
getData()
getDataCopy()
getDataUint8()
getDimensionIndexFromName(name)
getDimensionSize(dimIndex)
getMaxValue()
getMinValue()
getNumberOfSlices(normalAxis, dimIndex)
getPositionFromTransfoSpaceToVoxelSpace(spacePosition, transformName, round)
getPositionFromVoxelSpaceToTransfoSpace(voxelPosition, transformName)
getPositionWorldToVoxel(wPos, round)
getSegmentSampleTransfoSpace(space2voxelTransformName, voxel2spaceTransformName, posFrom, posTo, time)
getSegmentSampleVoxelSpace(posFrom, posTo, time)
getSlice(normalAxis, sliceIndex, time, dimIndex)
getSliceSize(normalAxis, dimIndex)
getTimeLength()
getTransfoBox(transformName)
getTransformMatrix(transformName)
getTransfoVolumeCorners(transformName)
getVoxel(position, time)
getVoxelBox()
getVoxelCoordinatesSwapMatrix(hflip, output4x4)
getVoxelSafe(position, time)
getVoxelTransfoSpace(spaceToVoxelTransfoName, spacePosition, time)
getW2VMatrixSwapped()
hasTransform(transformName)
isInsideTransfoSpace(pos, transformName)
isInsideVoxelSpace(pos)
resetData(value)
setData(buffer, options)
setVoxel(position, value, time)
setVoxelTransfoSpace(spaceToVoxelTransfoName, spacePosition, value, time)

ImageToImageFilter

ImageToImageFilter is not to be used as-is but rather as a base class for any filter that input a single Image2D and output a single Image2D. This class does not overload the update() method.

new ImageToImageFilter()

Extends Filter

Instance Members
hasSameNcppInput()
hasSameSizeInput()

LineString

A LineString is a vectorial reprensation of a line or polyline, open or closed. When closed, it can be considered as a polygon.
By default, a LineString is 2 dimensional but the dimension can be changed when using the .setData(...) method or before any point addition with .setNod(). To close a LineString, use .setMetadata("closed", true);, this will not add any point but will flag this LineString as "closed".

new LineString()

Extends PixpipeContainer

Static Members
TYPE()
Instance Members
addPoint(position)
close()
getData()
getDataCopy()
getNod()
getNumberOfPoints()
getPoint(index)
hasPoint(p)
open()
peekPoint()
popPoint()
setData(points, nod, deepCopy)
setNod(nod)

Mesh3D

A Mesh3D object contains the necessary informations to create a 3D mesh (for example using ThreeJS) and provide a generic datastructure so that it can accept data from arbitrary mesh file format.

Usage

new Mesh3D()

Extends PixpipeContainerMultiData

Static Members
TYPE()
Instance Members
buildBox()
buildBvhTree()
buildTriangleList()
buildTriangleList()
getBox()
getBoxCenter()
getNumberOfComponentsPerColor()
getNumberOfVertices()
getNumberOfVerticesPerShapes()
getPolygonFacesNormals()
getPolygonFacesNormalsCopy()
getPolygonFacesOrder()
getPolygonFacesOrderCopy()
getVertexColors()
getVertexColorsCopy()
getVertexPositionCopy()
getVertexPositions()
intersectBox(box)
intersectRay(origin, direction, backfaceCulling)
intersectSphere(sphere)
isInside(pos)
setNumberOfComponentsPerColor(num)
setNumberOfVerticesPerShapes(num)
setPolygonFacesNormals(data)
setPolygonFacesOrder(data)
setVertexColors(data)
setVertexPositions(data)
updateColorTriangle(index, color)

PixpipeContainer

PixpipeContainer is a common interface for Image2D and Image3D (and possibly some other future formats). Should not be used as-is.

new PixpipeContainer()

Extends PixpipeObject

Instance Members
setRawData(d)

PixpipeContainerMultiData

PixpipeContainerMultiData is a generic container very close from PixpipeContainer (from which it inherits). The main diference is that an instance of PixpipeContainerMultiData can contain multiple dataset since the _data property is an Array. This is particularly convenient when storing large arrays of numbers that must be split in multiple collections such as meshes (a typed array for vertices positions, another typed array for grouping as triangle, another one for colors, etc.) The class PixpipeContainerMultiData should not be used as-is and should be iherited by a more specific datastructure.

new PixpipeContainerMultiData()

Extends PixpipeContainer

Instance Members
checkIntegrity()
clone()
doesDataExist(name)
getData(name)
getDataCopy(name)
getDataIndex(name)
setData(d, name)

PixpipeObject

PixpipeObject is the base object of all. It creates a uuid and has few generic attributes like type, name and description. Not all these attributes always useful;

new PixpipeObject()
Static Members
TYPE()
Instance Members
_buildMetadataSchema()
_metadataRawCopied()
addTimeRecord(recordName)
copyMetadataFrom(otherObject)
getMetadata(key)
getMetadataClone()
getMetadataCopy()
getMetadataKeys()
getTime(fromRecord, toRecord, print)
getType()
getUuid()
hasMetadata(key)
isMetadataCyclic()
isOfType(t)
metadataIntegrityCheck(metadataObj, a)
metadataToString()
setMetadata(key, value)
setRawMetadata(m)

Signal1D

An object of type Signal1D is a single dimensional signal, most likely by a Float32Array and a sampling frequency. To change the sampling frequency use the method .setMetadata('samplingFrequency', Number);, defaut value is 100. We tend to considere this frequency to be in Hz, but there is no hardcoded unit and it all depends on the application. This is important to specify this metadata because some processing filters may use it.

Usage

new Signal1D()

Extends PixpipeContainer

Instance Members
clone()
dataToString()
getData()
hollowClone()
setData(array, deepCopy)
toString()

_DECODER

All decoders inherit from Filter, they intend to parse specific file format and output one of the basic PixpipeObject. In addition to decoders, you can also find some encoders (PixBinEncoder).

A decoder will usually take an ArrayBuffer as input.

AllFormatsGenericDecoder

AllFormatsGenericDecoder is a generic decoder for all the file formats Pixpipe can handle. This means an instance of AllFormatsGenericDecoder can output object of various modality: a Image3D, Image2D, Signal1D or a Mesh3D. As any generic decoder, this one performs attemps of decoding and if it suceeds, an object is created. Some of the compatible formats do not have a easy escape like a magic number checking and thus need a full decoding attemps before the decoder can take a decision if wether or not the buffer being decoded matches the such or such decoder. This can create a bottel neck and we advise not to use AllFormatsGenericDecoder if you know your file will be of a specific type or of a specific modality.

Notice: at the moment, AllFormatsGenericDecoder does not decode the pixBin format.

new AllFormatsGenericDecoder()

Extends GenericDecoderInterface

EdfDecoder

An instance of EdfDecoder takes an ArrayBuffer as input. This ArrayBuffer must come from a edf file (European Data Format). Such file can have multiple signals encoded internally, usually from different sensors, this filter will output as many Signal1D object as there is signal in the input file. In addition, each signal is composed of records (e.g. 1sec per record). This decoder concatenates records to output a longer signal. Still, the metadata in each Signal1D tells what the is the length of original record.

Usage

new EdfDecoder()

Extends Decoder

GenericDecoderInterface

GenericDecoderInterface is an intreface and should not be used as is. GenericDecoderInterface provides the elementary kit ti build a multiformat decoder. Classes that implements GenericDecoderInterface must have a list of decoder constructors stored in this._decoders. The classes Image2DGenericDecoder, Image3DGenericDecoderAlt and Mesh3DGenericDecoder are using GenericDecoderInterface.

new GenericDecoderInterface()

Extends Decoder

Image2DGenericDecoder

This class implements GenericDecoderInterface that already contains the successive decoding logic. For this reason this filter does not need to have the _run method to be reimplemented.

An instance of Image2DGenericDecoder takes a ArrayBuffer as input 0 (.addInput(myArrayBuffer)) and output an Image2D. The update method will perform several decoding attempts, using the readers specified in the constructor. In case of success (one of the registered decoder was compatible to the data) the metadata decoderConstructor and decoderName are made accessible and give information about the file format. If no decoder managed to decode the input buffer, this filter will not have any output.

Developers: if a new 2D dataset decoder is added, reference it here and in the import list

Usage

new Image2DGenericDecoder()

Extends GenericDecoderInterface

Image3DGenericDecoder

This class implements GenericDecoderInterface that already contains the successive decoding logic. For this reason this filter does not need to have the _run method to be reimplemented.

An instance of Image3DGenericDecoder takes a ArrayBuffer as input 0 (.addInput(myArrayBuffer)) and output an Image3D. The update method will perform several decoding attempts, using the readers specified in the constructor. In case of success (one of the registered decoder was compatible to the data) the metadata decoderConstructor and decoderName are made accessible and give information about the file format. If no decoder managed to decode the input buffer, this filter will not have any output.

Developers: if a new 3D dataset decoder is added, reference it here.

Usage

new Image3DGenericDecoder()

Extends GenericDecoderInterface

JpegDecoder

An instance of JpegDecoder will decode a JPEG image in native Javascript and output an Image2D. This is of course slower than using io/FileImageReader.js but this is compatible with Node and not rely on HTML5 Canvas.

Usage

new JpegDecoder()

Extends Decoder

Mesh3DGenericDecoder

This class implements GenericDecoderInterface that already contains the successive decoding logic. For this reason this filter does not need to have the _run method to be reimplemented.

An instance of Mesh3DGenericDecoder takes a ArrayBuffer as input 0 (.addInput(myArrayBuffer)) and output a Mesh3D object. The update method will perform several decoding attempts, using the readers specified in the constructor. In case of success (one of the registered decoder was compatible to the data) the metadata decoderConstructor and decoderName are made accessible and give information about the file format. If no decoder managed to decode the input buffer, this filter will not have any output.

Developers: if a new format decoder is added, reference it here.

Usage

new Mesh3DGenericDecoder()

Extends GenericDecoderInterface

MghDecoder

Decodes a MGH file. Takes an ArrayBuffer as input (0) and output a Image3D Some doc can be found here

Usage

new MghDecoder()

Extends Decoder

Minc2Decoder

Decode a HDF5 file, but is most likely to be restricted to the features that are used for Minc2 file format. The metadata "debug" can be set to true to enable a verbose mode. Takes an ArrayBuffer as input (0) and output a Image3D

Usage

new Minc2Decoder()

Extends Decoder

Instance Members
isRgbVolume(header, image)
rgbVoxels(image)
scaleVoxels(image, image_min, image_max, valid_range, debug)

MniObjDecoder

When most parser need an ArrayBuffer as input, the MNI OBJ mesh file being text files, an instance of MniObjDecoder takes the string content of such files. The string content of a file can be provided by a FileToArrayBufferReader or UrlToArrayBufferReader with the metadata readAsText being true. Then use the method .addInput( myString ) to provide the input and call the method .update(). If the input is suscceessfully parsed, the output of a MniObjDecoder is a Mesh3D. If the file is invalid, a message is probably written in the JS console and no output is available.

Usage

new MniObjDecoder()

Extends Decoder

Static Members
isBinary()

NiftiDecoder

Important information: NIfTI dataset are using two indexing methods:

  • A voxel based system (i, j, k), the most intuitive, where i is the fastest varying dim and k is the sloest varying dim. Thus for a given (i, j, k) the value is at (i + jdim[1] + kdim[1]*dim[2])
  • A subject based system (x, y, z), where +x is right, +y is anterior, +z is superior (right handed coord system). This system is CENTER pixel/voxel and is the result of a transformation from (i, j, k) and a scaling given by the size of each voxel in a world unit (eg. mm)

NIfTI provides three alternatives to characterize this transformation:

METHOD 1 , when header.qform_code = 0 Here, no specific orientation difers in [x, y, z], only spatial scaling based on voxel world dimensions. This method is NOT the default one, neither it is the most common. It is mainly for bacward compatibility to ANALYZE 7.5. Thus we simply have: x = pixdim[1] i y = pixdim[2] j z = pixdim[3] * k

METHOD 2, the "normal" case, when header.qform_code > 0 In this situation, three components are involved in the transformation: 1. voxel dimensions (header.pixDims[]) for the spatial scaling 2. a rotation matrix, for orientation 3. a shift Thus, we have: x header.pixDims[1] * i [ y ] = [ R21 R22 R23 ] header.pixDims[2] j ] + header.qoffset_y [ R31 R32 R33 ] qfac header.pixDims[3] * k ] [ header.qoffset_z ] Info: The official NIfTI header description ( https://nifti.nimh.nih.gov/pub/dist/src/niftilib/nifti1.h ) was used to interpret the data.

new NiftiDecoder()

Extends Decoder

PixBinDecoder

A PixBinDecoder instance decodes a pixbin file and output an Image2D or Image3D. The input, specified by .addInput(...) must be an ArrayBuffer (from an UrlToArrayBufferFilter, an UrlToArrayBufferReader or anothrer source ). The metadata targetType can be a string or an array of string being the name(s) of the accepted contructor(s). The defaut value ("*") means the decoder will decode blocks of the pixBin file that are of any type. If the you decide to use myPixBinDecoder.setMetadata("targetType", ["Image2D", "Mesh3D"]); then the block being something else will bne skiped and not part of the outputs.

Usage

new PixBinDecoder()

Extends Decoder

PixBinEncoder

A PixBinEncoder instance takes an Image2D or Image3D as input with addInput(...) and encode it so that it can be saved as a *.pixp file. An output filename can be specified using .setMetadata("filename", "yourName.pixp");, by default, the name is "untitled.pixp". When update() is called, a gzip blog is prepared as output[0] and can then be downloaded when calling the method .download(). The gzip blob could also be sent over AJAX using a third party library.

Usage

new PixBinEncoder()

Extends Filter

Static Members
MAGIC_NUMBER()

PixpDecoder

A PixpDecoder instance decodes a *.pixp file and output an Image2D or Image3D. The input, specified by .addInput(...) must be an ArrayBuffer (from an UrlToArrayBufferFilter, an UrlToArrayBufferReader or anothrer source ).

Usage

new PixpDecoder()

Extends Decoder

PixpEncoder

A PixpEncoder instance takes an Image2D or Image3D as input with addInput(...) and encode it so that it can be saved as a *.pixp file. An output filename can be specified using .setMetadata("filename", "yourName.pixp");, by default, the name is "untitled.pixp". When update() is called, a gzip blog is prepared as output[0] and can then be downloaded when calling the method .download(). The gzip blob could also be sent over AJAX using a third party library.

Usage

new PixpEncoder()

Extends Filter

Instance Members
download()

PngDecoder

An instance of PngDecoder will decode a PNG image in native Javascript and output an Image2D. This is of course slower than using io/FileImageReader.js but this is compatible with Node and not rely on HTML5 Canvas.

Usage

new PngDecoder()

Extends Decoder

Instance Members
_isPng(buffer)

Signal1DGenericDecoder

This class implements GenericDecoderInterface that already contains the successive decoding logic. For this reason this filter does not need to have the _run method to be reimplemented.

An instance of Signal1DGenericDecoder takes a ArrayBuffer as input 0 (.addInput(myArrayBuffer)) and output an Signal1D. The update method will perform several decoding attempts, using the readers specified in the constructor. In case of success (one of the registered decoder was compatible to the data) the metadata decoderConstructor and decoderName are made accessible and give information about the file format. If no decoder managed to decode the input buffer, this filter will not have any output.

Developers: if a new 2D dataset decoder is added, reference it here and in the import list

Usage

new Signal1DGenericDecoder()

Extends GenericDecoderInterface

TiffDecoder

Read and decode Tiff format. The decoder for BigTiff is experimental. Takes an ArrayBuffer of a tiff file as input and the TiffDecoder outputs an Image2D. Tiff format is very broad and this decoder, thanks to the Geotiff npm package is compatible with single or multiband images, with or without compression, using various bith depth and types (8bits, 32bits, etc.)

Info: Tiff 6.0 specification http://www.npes.org/pdf/TIFF-v6.pdf

Usage

new TiffDecoder()

Extends Decoder

_FILTER

Filters are objects that takes one or more input, performs some task and creates one or more output.
The input is never to be overwritten by a filter and an entirely new object should be created by a filter.

ApplyColormapFilter

An instance of ApplyColormapFilter applies a colormap on a chose channel (aka. component) of an Image2D. Several optional metadata are available to tune the end result:

  • .setMetadata("style", xxx: String); see the complete list at http://www.pixpipe.io/pixpipejs/examples/colormap.html . Default is "jet"
  • .setMetadata("flip", xxx; Bolean ); a fliped colormap reverses its style. Default: false
  • .setMetadata("min", xxx: Number ); and .setMetadata("max", xxx: Number ); if specified, will replace the min and max of the input image. This can be used to enhance of lower the contrast
  • setMetadata("clusters", xxx: Number ); The number of color clusters. If not-null, this will turn a smooth gradient into a set of xxx iso levels of color. Default: null
  • .setMetadata("component", xxx: Number ) The component to use on the input image to perform the colormapping. Default: 0

This filter requires an Image2D as input 0 and output a 3-components RGB Image2D of the same size as the input.

Usage

new ApplyColormapFilter()

Extends ImageToImageFilter

BandPassSignal1D

new BandPassSignal1D()

Extends Filter

ContourHolesImage2DFilter

new ContourHolesImage2DFilter()

Extends Filter

ContourImage2DFilter

An instance of ContourImage2DFilter takes a seed (.setMetadata("seed", [x, y])) and finds the contour of the shape of a segmented image by going north. The input must be an Image2D and the output is a LineString.
Two options are availble for neighbour connexity: 4 or 8. Set this option using .setMetadata("connexity", n).

Usage

new ContourImage2DFilter()

Extends Filter

CropImageFilter

An instance of CropImageFilter is used to crop an Image2D. This filter accepts a single input, using .addInput( myImage ), then, it requires a top left point that must be set with .setMetadata( "x", Number) and .setMetadata( "y", Number). In addition, you must specify the width and heigth of the output using .setMetadata( "w", Number) and .setMetadata( "h", Number).

Usage

new CropImageFilter()

Extends ImageToImageFilter

DifferenceEquationSignal1D

Performs a difference equation (= discrete version of a differential equation) on a Signal1D object. This is convenient to perform a lo-pass or hi-pass filter. Coefficients are needed to run this filter, set them using the following methods: .setMetadata("coefficientsB", [Number, Number, ...]) and .setMetadata("coefficientsB", [Number, Number, ...]). This is related to the following: Where coeefticients A and B are array of the same size, knowing the first number of the array coefficients A will not be used (just set it to 1.0). more information on the module repo and even more on the original description page.

Usage

new DifferenceEquationSignal1D()

Extends Filter

FloodFillImageFilter

A FloodFillImageFilter instance takes an Image2D as input and gives a Image2D as output.
The starting point of the flood (seed) has to be set using .setMetadata("seed", [x, y]) where x and y are winthin the boundaries of the image.
The tolerance can also be set using .setMetadata("tolerance", n). The tolerance is an absolute average over each component per pixel.

Neighbour connexity can be 4 or 8 using .setMetadata("connexity", n). Destination color can be set with .setMetadata("color", [r, g, b]). The color array depends on your input image and can be of size 1 (intensity), 3 (RGB), 4 (RBGA) or other if multispectral.

In addition to the output image, the list of internal hit points is created and availble with .getOutput("hits").

Usage

new FloodFillImageFilter()

Extends ImageToImageFilter

ForEachPixelImageFilter

A filter of type ForEachPixelImageFilter can perform a operation on evey pixel of an Image2D with a simple interface. For this purpose, a per-pixel-callback must be specified using method .on( "pixel" , function( coord, color ){ ... }) where coord is of form {x, y} and color is of form [r, g, b, a] (with possibly) a different number of components per pixel. This callback must return, or null (original color not modified), or a array of color (same dimension as the one in arguments).

Usage

new ForEachPixelImageFilter()

Extends ImageToImageFilter

Example
var forEachPixelFilter = new pixpipe.ForEachPixelImageFilter();
forEachPixelFilter.on( "pixel", function(position, color){

    return [
      color[1], // red (takes the values from green)
      color[0], // green (takes the values from red)
      color[2] * 0.5, // blue get 50% darker
      255 // alpha, at max
    ]

  }
);
Instance Members
_run()

ForEachPixelReadOnlyFilter

This Filter is a bit special in a sense that it does not output anything. It takes an Image2D as output "0" and the event "pixel" must be defined, with a callback taking two arguments: the position as an object {x: Number, y: Number} and the color as an array, ie. [Number, Number, Number] for an RGB image.

This filter is convenient for computing statistics or for anything where the output is mannually created ( because the filter ForEachPixelImageFilter creates an output with same number of band.)

Usage

new ForEachPixelReadOnlyFilter()

Extends Filter

GradientImageFilter

An instance of GradientImageFilter takes 2 input Image2D: a derivative in x, with the category "dx" and a derivative in y with the category "dy". They must be the same size and have the same number of components per pixel.

Usage

new GradientImageFilter()

Extends ImageToImageFilter

HighPassSignal1D

new HighPassSignal1D()

Extends Filter

IDWSparseInterpolationImageFilter

An instance of IDWSparseInterpolationImageFilter performs a 2D interpolation from a sparse dataset using the method of Inverse Distance Weighting.

The original dataset is specified using the method .addInput( seeds ), where seeds is an Array of {x: Number, y: Number, value: Number}. You specify the seeds with the methodd .addInput( seeds , "seeds" );. This filter outputs an Image2D with interpolated values. The size of the output must be specified using the method .setMetadata( "outputSize", {width: Number, height: Number}).

The IDW algorithm can be tuned with a "strength", which is essentially the value of exponent of the distances. Default is 2 but it is common the see a value of 1 or 3. With higher values, the output will look like a cells pattern. The strength can be defined using the method .setMetadata( "strength", Number )

The metadata "k" specifies the number of closest neighbors seed to consider for each pixel of the output. If larger than the number of seeds, it will be automatically clamped to the number of seeds. Set "k" with .setMetadata( "k", Number )

To make the interpolation faster when done several times with seed of the same position but different values, a distance map is built at the begining. The map that is firstly built will be reuse unless the metadata 'forceBuildMap' is set to 'true'. If true, the map will be rebuilt at every run. It can take a while so make sure you rebuild the map only if you need (= seed changed position, output image changed size). Use the method .setMetadata( "forceBuildMap", Boolean )

Note 1: seeds can be outside the boundaries of the original image Note 2: interpolated values are floating point

Note that only single-component images are outputed from this filter. Ressources: https://www.e-education.psu.edu/geog486/node/1877

Usage

new IDWSparseInterpolationImageFilter()

Extends Filter

Image3DToMosaicFilter

An instance of Image3DToMosaicFilter takes an Image3D as Input and output a mosaic composed of each slice. The axis: "x", "y" or "z" can be specified with setMetadata("axis", "x"), the default being x. The default output image is 4096x4096 but these boundaries can be changed using setMetadata("maxWidth", n) and setMetadata("maxHeight", m). These are boundaries so the size of the output image(s) will possibly be lower to not contain unused space. If mosaicing the whole given Image3D does not fit in maxWidth*maxHeight, more Image2D will be created and accessible through getOutput(n). All output image have the same size so that the last one may have dead space. To know precisely the size of the output mosaic use getMetadata("gridWidth") and getMetadata("gridHeight"), this will give the number of slices used in horizontal and vertical respectively.

By setting the time metadata we can get a mosaic at a given time position, the default being 0. If set to -1, then the filter outputs the whole time series.

Usage

new Image3DToMosaicFilter()

Extends Filter

ImageBlendExpressionFilter

An instance of ImageBlendExpressionFilter takes Image2D inputs, as many as we need as long as they have the same size and the same number of components per pixel. This filter blends images pixel values using a literal expression. This expression should be set using setMetadata( "expresssion", "A * B" ) , where A and B are the categories set in input.

Using a blending expression is the aesiest way to test a blending but it is a pretty slow process since the expresion has to be evaluated for every process. To speed-up your process, it is recomended to develop a new filter that does exactly (and only) the blending method you want.

usage

new ImageBlendExpressionFilter()

Extends ImageToImageFilter

ImageDerivativeFilter

A ImageDerivativeFilter filter will compute the dx and dy derivative using the filters h = [1, -1]

You can change the built-in filters that perform the derivative by setting the metadata "dxFilter" and "dyFilter" with the method .setMetadata(). See the documentation of SpatialConvolutionFilter to make your custom filter compatible.

Usage

new ImageDerivativeFilter()

Extends ImageToImageFilter

LowPassFreqSignal1D

An object of type LowPassFreqSignal1D perform a low pass in the frequency domain, which means the input Signal1D object must already be in the frequency domain. This filter requires 2 inputs:

  • the real part of the Fourier transform output as a Signal1D. To be set with with .addInput("real", Signal1D)
  • the imaginary part of the Fourier transform output as a Signal1D. To be set with with .addInput("imaginary", Signal1D)

In addition to data, few metada can be used:

  • mandatory the cutoffFrequency in Hz using the method .setMetadata("cutoffFrequency", Number) - cannot be higher than half of the sampling frequency (cf. Nyquist)
  • optional the filterType in Hz using the method .setMetadata("filterType", String) can be gaussian or rectangular (default: gaussian)
  • optional the gaussianTolerance in Hz using the method .setMetadata("gaussianTolerance", Number) value (frequency response) under which we want to use 0 instead of the actual gaussian value. Should be small. (default: 0.01)

Note: the filter type rectangular should be used with caution because it simply thresholds the frequency spectrum on a given range. When transformed back to the time domain, this is likely to produce artifact waves due to Gibbs phenomenon.

  • Usage
new LowPassFreqSignal1D()

Extends Filter

LowPassSignal1D

new LowPassSignal1D()

Extends Filter

Mesh3DToVolumetricHullFilter

An instance of Mesh3DToVolumetricHullFilter creates a voxel based volume (Image3D) of a Mesh3D (input). The hull of the mesh is represnted by voxels in the output.

new Mesh3DToVolumetricHullFilter()

Extends Filter

MultiplyImageFilter

Multiply two Image2D pixel by pixel. They must have the same number of components per pixel and the same size. Output an new Image3D. Equivalent to SpectralScaleImageFilter.

Usage

new MultiplyImageFilter()

Extends ImageToImageFilter

NaturalNeighborSparseInterpolationImageFilter

Inputs are alternatively

  • "seeds" , an array of seeds
  • "samplingMap"

As metadata:

  • "outputSize" as {width: Number, height: Number}
  • "samplingMapOnly" as a boolean. If true generated only the sampling map, if false, generate the sampling map and the output image

As output:

  • "0" or not arg, the output image
  • "samplingMap", the sampling map. Only available if "samplingMap" is not already as input
new NaturalNeighborSparseInterpolationImageFilter()

Extends Filter

NearestNeighborSparseInterpolationImageFilter

With a given set of seeds ( each being {x: Number, y: Number, value: Number} ) An instance of NearestNeighborSparseInterpolationImageFilter creates an image where each value is the closest from the given point.

The original seeds must be given as an Array of Object using the method .addInput( seeds, "seeds")

The output image size must be set using the method .setMetadata( "outputSize", {width: Number, height: Number})

The given point can be outside the output image boundaries.

Usage

new NearestNeighborSparseInterpolationImageFilter()

Extends Filter

NormalizeImageFilter

A NormalizeImageFilter instance takes an Image2D as input and outputs an Image2D. The output images will have values in [0.0, 1.0]. One of the usage is that is can then be used as a scaling function.

The max value to normalize with will be the max value of the input image (among all components) but an manual max value can be given to this filter using .setMetadata("max", m).

Usage

new NormalizeImageFilter()

Extends ImageToImageFilter

PatchImageFilter

A instance of PatchImageFilter will copy an Image2D into another at a given position. The same process can be repeated mutiple times so that the output is the result of several patched applied on a image with a solid color background.

Usage

new PatchImageFilter()

Extends ImageToImageFilter

SimpleThresholdFilter

An instance of SimpleThresholdFilter perform a threshold on an input image. The input must be an Image2D with 1, 3 or 4 bands. The default threshold can be changed using .setMetadata("threshold", 128) and the low and high value can be replaced using .setMetadata("lowValue", 0) and .setMetadata("highValue", 255). In addition, in case of dealing with a RGBA image, you can decide of preserving the alpha channel or not, using .setMetadata("preserveAlpha", true).

Usage

new SimpleThresholdFilter()

Extends ImageToImageFilter

SimplifyLineStringFilter

An instance of SimplifyLineStringFilter takes a LineString and simplifies upon a given tolerance distance (in pixel, possibly being sub-pixel). This filter outputs another LineString with a fewer amount of points.

Usage

new SimplifyLineStringFilter()

Extends Filter

SpatialConvolutionFilter

An instance of SpatialConvolutionFilter perform a convolution in a spatial reference, this can be applying a Sobel filter, a median or gaussian blur or perform a derivative. The filter is a NxM (aka. an array of arrays) of the following form:

  var medianBlurFilter = [
    [1/9, 1/9, 1/9],
    [1/9, 1/9, 1/9],
    [1/9, 1/9, 1/9],
  ];

For example, in the case of a simple derivative, it will be like that:

 var dx = [
   [1, -1]
 ];

 // or

 var dy = [
   [1],
   [-1]
 ];

The filter must be specified using the method .setMetadata('filter', ...).

Usage

new SpatialConvolutionFilter()

Extends ImageToImageFilter

SpectralScaleImageFilter

Multiply an image by the other, like a scaling function. The image requires two inputs named "0" and "1". Simply use addInput( myImg1, "0" ) and addInput( myImg2, "1" ). The input "0" can have 1 or more bands while the input "1" can have only one band since the same scale is apply to each band.

Usage

new SpectralScaleImageFilter()

Extends ImageToImageFilter

Instance Members
_run()

TerrainRgbToElevationImageFilter

This filter's purpose is to convert Mapbox's TerrainRGB image data into monochannel elevation (in meter). See more info about the format here: https://www.mapbox.com/blog/terrain-rgb/ The filter takes an Image2D that respect Mapbox's format (can be a result of stictching tiles together) and output a single component image with possibly up to 16777216 different values.

Usage

new TerrainRgbToElevationImageFilter()

Extends ImageToImageFilter

TriangulationSparseInterpolationImageFilter

An instance of TriangulationSparseInterpolationImageFilter performs a triangulation of an original dataset followed by a barycentric 2D interpolation. It is used to perform a 2D linear interpolation of a sparse dataset. The original dataset is specified using the method .addInput( seeds, "seeds" ), where seeds is an Array of {x: Number, y: Number, value: Number}. The triangulation is the result of a Delaunay triangulation. This filter outputs an Image2D with interpolated values only within the boundaries of the convex hull created by the triangulation. The size of the output must be specified using the method .setMetadata( "outputSize", {width: Number, height: Number}).

Note 1: at least 3 unaligned points are required to perform a triangulation Note 2: points can be outside the boundaries of the original image Note 3: interpolated values are floating point

Note that only single-component images are outputed from this filter.

Usage

new TriangulationSparseInterpolationImageFilter()

Extends Filter

_HELPER

Helpers are here to help.

AngleToHueWheelHelper

AngleToHueWheelHelper has for goal to help visualize angular data such as gradient orientation. The idea behind the "hue wheel" is to associate every direction (angle) to a color without having the 0/360 interuption. The helper takes one Image2D input and gives one RGBA Image2D output. From the output, the index of the compnent that contains angular information has to be given using: .setMetadata("component", n) where n by default is 0.

Depending on the usage of this filter, the range of angle can varry, ie. in [0, 2PI] (the default), or in [-PI/2, PI/2] (in the case of a gradient) or even in degrees [0, 360]. In any case, use .setMetadata("minAngle", ...) and .setMetadata("maxAngle", ...). If the metadata "minAngle" or "maxAngle" is given the value "auto", then the min and max values of the image will be looked-up (or computed if not defined).

Usage

new AngleToHueWheelHelper()

Extends ImageToImageFilter

Instance Members
_hsl2Rgba(h, s, l)

ColorScales

From https://github.com/bpostlethwaite/colormap

ColorScales

Colormap

A Colormap instance is a range of color and can be used in two ways. The first, is by getting a single color using .getValueAt(p) where p is a position in [0, 1] and, second, by building en entire LUT with a given granularity and then getting back these values. In case of intensive use (ie. applying fake colors), building a LUT is a faster option. Once a LUT is built, an image of this LUT can be created (horizontal or vertical, flipped or not). The image will be flipped is the flip matadata is set to true; This image, which is an Image2D is not supposed to be used as a LUT but just as a visual reference.

Usage

new Colormap(options: Object)

Extends PixpipeObject

Parameters
options (Object = {}) here is the list of options: style {String} - one of the available styles (see property names in ColorScales.js) description {Object} - colormap description like in ColorScales.js. Can also be the equivalent JSON string. lutSize {Number} - Number of samples to pregenerate a LUT Note: "style" and "description" are mutually exclusive and "style" has the priority in case both are set.
Static Members
getAvailableStyles()
TYPE()
Instance Members
addColor(index, rgb)
buildLut(size)
createHorizontalLutImage(forceRGBA)
createVerticalLutImage(forceRGBA)
getLutAt(index)
getValueAt(position)
getValueAtWithClusters(position, clusters)
removeColor(index)
setDescription(d)
setStyle(style)
toJson()

LineStringPrinterOnImage2DHelper

A instance of LineStringPrinterOnImage2DHelper prints a list of LineStrings on an Image2D. To add the Image2D input, use .addInput(myImage2D). To add a LineString, use .addLineString(ls, c ); where ls is a LineString instance and c is an Array representing a color (i.e. [255, 0, 0] for red).

Usage

new LineStringPrinterOnImage2DHelper()

Extends ImageToImageFilter

Instance Members
addLineString(ls, color)

_IO

the input/output are special kinds of Filter objects. they read or write file from a server or from disk.

BrowserDownloadBuffer

An instance of BrowserDownloadBuffer takes an ArrayBuffer as input and triggers a download when update() is called. This is for browser only!
A filename must be specified using .setMetadata( "filename", "myFile.ext" ).

new BrowserDownloadBuffer()

Extends Filter

CanvasImageWriter

CanvasImageWriter is a filter to output an instance of Image into a HTML5 canvas element. The metadata "parentDivID" has to be set using setMetadata("parentDivID", "whatever") The metadata "alpha", if true, enable transparency. Default: false. If the input Image2D has values not in [0, 255], you can remap/stretch using setMetadata("min", xxx ) default: 0 setMetadata("max", xxx ) default: 255 We can also use setMetadata("reset", false) so that we can add another canvas with a new image at update.

Usage

new CanvasImageWriter(parentDivID: String)

Extends Filter

Parameters
parentDivID (String) dom id of the future canvas' parent. (most likely the ID of a div)
Example
// create an image
var myImage = new pixpipe.Image2D({width: 100, height: 250, color: [255, 128, 64, 255]})

// create a filter to write the image into a canvas
var imageToCanvasFilter = new pixpipe.CanvasImageWriter( "myDiv" );
imageToCanvasFilter.addInput( myImage );
imageToCanvasFilter.update();
Instance Members
_run()
getCanvas()

FileImageReader

An instance of FileImageReader takes a HTML5 File object of a png or jpeg image as input and returns an Image2D as output. For Tiff format, use TiffDecoder instead. The point is mainly to use it with a file dialog. Use the regular addInput() and getOuput() with no argument for that. Reading a local file is an asynchronous process. For this reason, what happens next, once the Image2D is created must take place in the callback defined by the event .on("ready", function(){ ... }).

Usage

new FileImageReader()

Extends Filter

Example
var file2ImgFilter = new pixpipe.file2ImgFilter( ... );
file2ImgFilter.addInput( fileInput.files[0] );
file2ImgFilter.update();
Instance Members
_run()
hasValidInput()

FileToArrayBufferReader

Takes the File inputs from a HTML input of type "file" (aka. a file dialog), and reads it as a ArrayBuffer. Every File given in input should be added separately using addInput( file[i], 'uniqueID' ). The event "ready" must be set up ( using .on("ready", function(){}) ) and will be triggered when all the files given in input are translated into ArrayBuffers. Once ready, all the outputs are accecible using the same uniqueID with the method getOutput("uniqueID"). Gzip compressed files will be uncompressed.

Once the filter is updated, you can query the filenames metadata (sorted by categories) and also the checksums metadata using .getMetadata(). This later metadata give a unique md5, very convenient to compare if two files are actually the same. Note that in case the file is gziped, the checksum is computed on the raw file, not on the un-gziped buffer.

It happens that a file is not binary but text, then, set the metadata "readAsText" to true.

Usage

new FileToArrayBufferReader()

Extends Filter

UrlImageReader

An instance of UrlImageReader takes an image URL to jpeg or png as input and returns an Image2D as output. Use the regular addInput() and getOuput() with no argument for that. For Tiff format, use TiffDecoder instead. Reading a file from URL takes an AJAX request, which is asynchronous. For this reason, what happens next, once the Image2D is created must take place in the callback defined by the event .on("ready", function(){ ... }). Usage: examples/urlToImage2D.html

UrlImageReader can also load multiple images and call the "ready" event only when all of them are loaded.

Usage

new UrlImageReader(callback: function)

Extends Filter

Parameters
callback (function) function to call when the image is loaded. The this object will be in argument of this callback.
Example
var url2ImgFilter = new pixpipe.UrlImageReader( ... );
url2ImgFilter.addInput( "images/sd.jpg" );
url2ImgFilter.update();
Instance Members
_run()

UrlToArrayBufferReader

Open a files as ArrayBuffer using their URL. You must specify one or several URL (String) using addInput("...") and add function to the event "ready" using .on( "ready", function(filter){ ... }). The "ready" event will be called only when all input are loaded. Gzip compressed files will be uncompressed. Once the filter is updated, you can query the filenames metadata (sorted by categories) and also the checksums metadata using .getMetadata(). This later metadata give a unique md5, very convenient to compare if two files are actually the same. Note that in case the file is gziped, the checksum is computed on the raw file, not on the un-gziped buffer.

It happens that a file is not binary but text, then, set the metadata "readAsText" to true.

Usage

new UrlToArrayBufferReader()

Extends Filter

_UTILS

The Utils are usually not respecting the inheritance schema provided by Pixpipe because they are neither data structure, nor filters. They just provide some small feature that can be used by multiple PixpipeObjects.

FunctionGenerator

The FunctionGenerator is a collection of static methods to get samples of function output such as gaussian values.

new FunctionGenerator()
Static Members
gaussianFrequencyResponse(sigma, begin, end, step, onlyAbove)
gaussianFrequencyResponseSingle(sigma, x)

MatrixTricks

MatrixTricks contains only static functions that add features to glMatrix. Like in glMatrix, all the matrices arrays are expected to be column major.

new MatrixTricks()
Static Members
getExpandedMatrix3x3To4x4(matrix, horizontalStick, verticalStick)
getHorizontalFlipMatrix33(matrix)
getHorizontalFlipMatrix44(matrix)
getHorizontalFlipSquareMatrix(matrix, sideSize)
getValueMatrix33(matrix, colIndex, rowIndex)
getValueMatrix44(matrix, colIndex, rowIndex)
getValueSquareMatrix(matrix, sideSize, colIndex, rowIndex)
setValueMatrix33(matrix, colIndex, rowIndex, value)
setValueMatrix44(matrix, colIndex, rowIndex, value)
setValueSquareMatrix(matrix, sideSize, colIndex, rowIndex, value)

_misc

convertImage3DMetadata

Converts the original Image3D metadata into the new

convertImage3DMetadata(oldMeta: any)
Parameters
oldMeta (any)

swapn

[STATIC] swap the data to be used from the outside (ie. nifti)

swapn(byte_data: any, n_per_item: any)
Parameters
byte_data (any)
n_per_item (any)

transformToMinc

[STATIC] mainly used by the ouside world (like from Nifti)

transformToMinc(transform: any, header: any)
Parameters
transform (any)
header (any)

ForwardFourierImageFilter

An instance of ForwardFourierImageFilter performs a forward Fourier transform on an Image2D or a Signa1D.

Usage

new ForwardFourierImageFilter()

Extends BaseFourierImageFilter

ignore_offsets

This is here because there are two different ways of interpreting the origin of an MGH file. One can ignore the offsets in the transform, using the centre of the voxel grid. Or you can correct these naive grid centres using the values stored in the transform. The first approach is what is used by surface files, so to get them to register nicely, we want ignore_offsets to be true. However, getting volumetric files to register correctly implies setting ignore_offsets to false.

ignore_offsets

InverseFourierImageFilter

An instance of ForwardFourierImageFilter performs an inverse Fourier transform on an Image2D or a Signa1D.

Usage

new InverseFourierImageFilter()

Extends BaseFourierImageFilter