image-js

0.35.6

Class representing an image. This class allows to manipulate easily images directly in the browser or in node.

This library is designed to deal with scientific images (8 or 16 bit depth) and will be able to open and process jpeg, png and uncompressed tiff images. It is designed to work in the browser as on the server side in node.

An image is characterized by:

  • width and height
  • colorModel (RGB, HSL, CMYK, GREY, ...)
  • components: number of components, Grey scale images will have 1 component while RGB will have 3 and CMYK 4.
  • alpha: 0 or 1 depending if there is an alpha channel. The alpha channel define the opacity of each pixel
  • channels: number of channels (components + alpha)
  • bitDepth : number of bits to define the intensity of a point. The values may be 1 for a binary image (mask), 8 for a normal image (each channel contains values between 0 and 255) and 16 for scientific images (each channel contains values between 0 and 65535). The png library and tiff library included in image-js allow to deal correctly with 8 and 16 bit depth images.
  • position : an array of 2 elements that allows to define a relative position to a parent image. This will be used in a crop or in the management of Region Of Interests (Roi) for example
  • data : an array that contains all the points of the image. Depending the bitDepth Uint8Array (1 bit), Uint8Array (8 bits), Uint16Array (16 bits), Float32Array (32 bits)

In an image there are pixels and points:

  • A pixel is an array that has as size the number of channels and that contains all the values that define a particular pixel of the image.
  • A point is an array of 2 elements that contains the x / y coordinate of a specific pixel of the image
new Image(width: number, height: number, data: Array?, options: object?)
Parameters
width (number = 1)
height (number = 1)
data (Array?) Image data to load
options (object?)
Example
// JavaScript code using Node.js to get some info about the image.
// We load the library that was installed using 'npm install image-js'
const { Image } = require('image-js');

// Loading an image is asynchronous and will return a Promise.
Image.load('cat.jpg').then(function (image) {
  console.log('Width', image.width);
  console.log('Height', image.height);
  console.log('colorModel', image.colorModel);
  console.log('components', image.components);
  console.log('alpha', image.alpha);
  console.log('channels', image.channels);
  console.log('bitDepth', image.bitDepth);
});
// Convert an image to greyscale
const { Image } = require('image-js');

Image.load('cat.jpg').then(function (image) {
  var grey = image.grey();
  grey.save('cat-grey.jpg');
});
// Split an RGB image in its components
const { Image } = require('image-js');

Image.load('cat.jpg').then(function (image) {
  var components = image.split();
  components[0].save('cat-red.jpg');
  components[1].save('cat-green.jpg');
  components[2].save('cat-blur.jpg');
});
// For this example you will need the picture of an ecstasy pill that is available on
// wget https://raw.githubusercontent.com/image-js/core/854e70f50d63cc73d2dde1d2020fe61ba1b5ec05/test/img/xtc.png // the goal is to isolate the picture and to get a RGB histogram of the pill.
// Practically this allows to classify pills based on the histogram similarity
// This work was published at: http://dx.doi.org/10.1016/j.forsciint.2012.10.004

const { Image } = require('image-js');

const image = await Image.load('xtc.png');

const grey = image.grey({
  algorithm:'lightness'
});
// we create a mask, which is basically a binary image
// a mask has as source a grey image and we will decide how to determine
// the threshold to define what is white and what is black
var mask = grey.mask({
  algorithm: 'li'
});

// it is possible to create an array of Region Of Interest (Roi) using
// the RoiManager. A RoiManager will be applied on the original image
// in order to be able to extract from the original image the regions

// the result of this console.log result can directly be pasted
// in the browser
// console.log(mask.toDataURL());


var manager = image.getRoiManager();
manager.fromMask(mask);
var rois = manager.getRoi({
  positive: true,
  negative: false,
  minSurface: 100
});

// console.log(rois);

// we can sort teh rois by surface
// for demonstration we use an arrow function
rois.sort((a, b) => b.surface - a.surface);

// the first Roi (the biggest is expected to be the pill)

var pillMask = rois[0].getMask({
  scale: 0.7   // we will scale down the mask to take just the center of the pill and avoid border effects
});

// image-js remembers the parent of the image and the relative
// position of a derived image. This is the case for a crop as
// well as for Roi

var pill = image.extract(pillMask);
pill.save('pill.jpg');

var histogram = pill.getHistograms({ maxSlots: 16 });

console.log(histogram);
// Example of use of IJS in the browser

<script>
 var canvas = document.getElementById('myCanvasID');
 var image = IJS.fromCanvas(canvas);
</script>
// Image from matrix of values
const [min, max] = d3.extent(temperatures)
const colorScaler = d3.scaleSequential([min, max], d3.interpolateRdYlBu);

// size = rows * columns * channels
const data = new Uint8Array(2*3*3);
for (let i = 0; i < temperatures.length; i++) {
  const {r, g, b} = d3.rgb(colorScaler(temperatures[i]));
  data[i*3] = r;
  data[i*3 + 1] = g;
  data[i*3 + 2] = b;
}

const image = new Image(2, 3, data, { kind: 'RGB' });
// or
const image = new Image({ width: 2, height: 3, data, kind: 'RGB'});
Static Members
createFrom(other, options?)
fromCanvas(canvas)
load(image, options?)
Instance Members
abs(options = {})
add(value, options = {})
alpha
background(coordinates, values, options?)
bitDepth
blackHat(options = {})
blurFilter(options = {})
cannyEdge(options?)
channels
checkProcessable(processName, options = {})
clearBit(pixel)
clearBitXY(x, y)
clone()
close(options = {})
cmyk()
colorDepth(newColorDepth)
colorModel
combineChannels(method, options = {})
components
convolution(kernel, options = {})
copyImage(fromImage, toImage, x, y)
countAlphaPixels(options = {})
crop(options = {})
cropAlpha(options = {})
data
dilate(options = {})
divide(value, options = {})
erode(options = {})
extendedPoints()
extract(mask, options = {})
feretDiameters(options = {})
flipX()
flipY()
gaussianFilter(options)
getBestMatch(image, options = {})
getBit(pixel)
getBitXY(x, y)
getCanvas()
getChannel(channel, options = {})
getClosestCommonParent(mask)
getColorHistogram(options = {})
getColumn(column, channel)
getHistogram(options = {})
getHistograms(options = {})
getIntersection(mask2)
getMatrix(options = {})
getMoment(xPower, yPower)
getPixel(index)
getPixelsArray()
getPixelsGrid(options = {})
getPixelXY(x, y)
getRelativePosition(targetImage, options)
getRGBAData(options = {})
getRoiManager(options?)
getRow(row, channel)
getSimilarity(image, options = {})
getThreshold(options = {})
getValue(index, channel)
getValueXY(x, y, channel)
gradientFilter(options = {})
grey(options = {})
height
hsl()
hsv()
hypotenuse(otherImage, options)
insert(toInsert, options = {})
invert(options = {})
level(options = {})
localMaxima(options = {})
mask(options = {})
max()
maxValue
mean()
median()
medianFilter(options)
meta
min()
minimalBoundingRectangle(options = {})
monotoneChainConvexHull()
morphologicalGradient(options = {})
multiply(value, options = {})
open(options = {})
pad(options = {})
paintLabels(labels?, positions?, options = {})
paintMasks(masks, options = {})
paintPoints(points, options = {})
paintPolygon(points, options = {})
paintPolygons(polygons, options = {})
paintPolyline(points, options = {})
paintPolylines(polylines, options = {})
points()
resize(options = {})
rgba8()
rotate(angle, options?)
rotateLeft()
rotateRight()
save(path, options = {})
scharrFilter(options?)
setBit(pixel)
setBitXY(x, y)
setBorder(options = {})
setChannel(channel, image)
setMatrix(matrix, options = {})
setPixel(index, value)
setPixelXY(x, y, value)
setValue(index, channel, value)
setValueXY(x, y, channel, value)
size
sobelFilter(options?)
split(options = {})
subtract(value, options = {})
subtractImage(otherImage, options)
sum()
toBase64(type, options = {})
toBlob(type, quality)
toBuffer(options = {})
toDataURL(type, options = {})
toggleBit(pixel)
toggleBitXY(x, y)
topHat(options = {})
warpingFourPoints(pts?, options = {})
width

Class representing stack of images

new Stack()
Instance Members
averageImage()
histogram(options?)
histograms(options?)
matchAndCrop(options = {})
maxImage()
minImage()

Class to manage Region Of Interests

new Roi()
Instance Members
border
borderIDs
borderLengths
box
boxIDs
contourMask
eqpc
external
getMask(options = {})
holesInfo
mask
maxLength
ped
perimeter
perimeterInfo

Color model of an image

ColorModel

Type: ("GREY" | "RGB" | "HSL" | "HSV" | "CMYK")

A manager of Regions of Interest. A RoiManager is related to a specific Image and may contain multiple layers. Each layer is characterized by a label whose is name by default 'default'

new RoiManager(image: Image, options: object?)
Parameters
image (Image)
options (object?)
Instance Members
colsInfo(options = {})
createRoi()
findCorrespondingRoi(roiMap, options = {})
fromMask(mask, options = {})
fromMaxima(options = {})
fromPoints(pointsToPaint, options = {})
fromWaterShed(options)
getAnalysisMasks(options = {})
getData(options = {})
getMap(options = {})
getMasks(options = {})
getRoi(roiId, options)
getRoiIds(options = {})
getRois(options)
mergeRoi(options = {})
mergeRois(roiIds, options = {})
paint(options = {})
putMap(map, options = {})
resetPainted(options = {})
rowsInfo(options = {})

Class representing a shape

new Shape(options: object?)
Parameters
options (object?)
Name Description
options.kind string (default 'cross') Predefined matrix shape, 'cross' or 'smallCross'
options.shape string? Value may be 'square', 'rectangle', 'circle', 'ellipse' or 'triangle' The size of the shape will be determined by the size, width and height. A Shape is by default filled.
options.size number?
options.width number (default options.size) width of the shape. Must be odd.
options.height number (default options.size) width of the shape. Must be odd.
options.filled boolean (default true) If false only the border ot the shape is taken into account.
Instance Members
getMask()
getPoints()

Direction of a gradient filter

GradientDirection

Type: ("x" | "y" | "xy")

GreyAlgorithm

Type: ("luma709" | "luma601" | "maximum" | "minimum" | "average" | "minmax" | "red" | "green" | "blue" | "cyan" | "magenta" | "yellow" | "black" | "hue" | "saturation" | "lightness")

GreyAlgorithmCallback

src/image/transform/grey.js

Call back that converts the RGB channels to grey. It will be clamped after.

GreyAlgorithmCallback(red: number, green: number, blue: number): number

Type: Function

Parameters
red (number) value of the red channel
green (number) value of the green channel
blue (number) value of the blue channel
Returns
number: value of the grey channel

InterpolationAlgorithm

src/image/internal/checks.js
InterpolationAlgorithm

Type: ("nearestNeighbor" | "bilinear")

Returns the perimeter represented by the points (a polygon)

perimeter(vertices: any, points: Array<Array<number>>)
Parameters
vertices (any)
points (Array<Array<number>>)

SelectedChannels

src/util/channel.js

Specify which channels should be processed

  • undefined : we take all the channels but alpha
  • number : this specific channel
  • string : converted to a channel based on rgb, cmyk, hsl or hsv (one letter code)
  • [number] : array of channels as numbers
  • [string] : array of channels as one letter string
SelectedChannels

Type: (undefined | number | string | Array<number> | Array<string>)

Returns the surface represented by the points (a polygon)

surface(vertices: any, points: Array<Array<number>>)
Parameters
vertices (any)
points (Array<Array<number>>)
ThresholdAlgorithm

Type: ("huang" | "intermodes" | "isodata" | "li" | "maxentropy" | "mean" | "minerror" | "minimum" | "moments" | "otsu" | "percentile" | "renyientropy" | "shanbhag" | "triangle" | "yen")