/*
 * image-js v1.6.1
 * Image processing and manipulation in JavaScript
 * https://github.com/image-js/image-js#readme
 *
 * Licensed under the MIT license.
 */
import assert$1 from 'node:assert';

function getDefaultExportFromCjs (x) {
	return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}

function getAugmentedNamespace(n) {
  if (Object.prototype.hasOwnProperty.call(n, '__esModule')) return n;
  var f = n.default;
	if (typeof f == "function") {
		var a = function a () {
			var isInstance = false;
      try {
        isInstance = this instanceof a;
      } catch {}
			if (isInstance) {
        return Reflect.construct(f, arguments, this.constructor);
			}
			return f.apply(this, arguments);
		};
		a.prototype = f.prototype;
  } else a = {};
  Object.defineProperty(a, '__esModule', {value: true});
	Object.keys(n).forEach(function (k) {
		var d = Object.getOwnPropertyDescriptor(n, k);
		Object.defineProperty(a, k, d.get ? d : {
			enumerable: true,
			get: function () {
				return n[k];
			}
		});
	});
	return a;
}

var matrix = {};

// eslint-disable-next-line @typescript-eslint/unbound-method
const toString = Object.prototype.toString;
/**
 * Checks if an object is an instance of an Array (array or typed array, except those that contain bigint values).
 *
 * @param value - Object to check.
 * @returns True if the object is an array or a typed array.
 */
function isAnyArray$1(value) {
  const tag = toString.call(value);
  return tag.endsWith('Array]') && !tag.includes('Big');
}

var libEsm = /*#__PURE__*/Object.freeze({
	__proto__: null,
	isAnyArray: isAnyArray$1
});

var require$$0 = /*@__PURE__*/getAugmentedNamespace(libEsm);

function max$2(input) {
  var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  if (!isAnyArray$1(input)) {
    throw new TypeError('input must be an array');
  }
  if (input.length === 0) {
    throw new TypeError('input must not be empty');
  }
  var _options$fromIndex = options.fromIndex,
    fromIndex = _options$fromIndex === void 0 ? 0 : _options$fromIndex,
    _options$toIndex = options.toIndex,
    toIndex = _options$toIndex === void 0 ? input.length : _options$toIndex;
  if (fromIndex < 0 || fromIndex >= input.length || !Number.isInteger(fromIndex)) {
    throw new Error('fromIndex must be a positive integer smaller than length');
  }
  if (toIndex <= fromIndex || toIndex > input.length || !Number.isInteger(toIndex)) {
    throw new Error('toIndex must be an integer greater than fromIndex and at most equal to length');
  }
  var maxValue = input[fromIndex];
  for (var i = fromIndex + 1; i < toIndex; i++) {
    if (input[i] > maxValue) maxValue = input[i];
  }
  return maxValue;
}

function min$1(input) {
  var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  if (!isAnyArray$1(input)) {
    throw new TypeError('input must be an array');
  }
  if (input.length === 0) {
    throw new TypeError('input must not be empty');
  }
  var _options$fromIndex = options.fromIndex,
    fromIndex = _options$fromIndex === void 0 ? 0 : _options$fromIndex,
    _options$toIndex = options.toIndex,
    toIndex = _options$toIndex === void 0 ? input.length : _options$toIndex;
  if (fromIndex < 0 || fromIndex >= input.length || !Number.isInteger(fromIndex)) {
    throw new Error('fromIndex must be a positive integer smaller than length');
  }
  if (toIndex <= fromIndex || toIndex > input.length || !Number.isInteger(toIndex)) {
    throw new Error('toIndex must be an integer greater than fromIndex and at most equal to length');
  }
  var minValue = input[fromIndex];
  for (var i = fromIndex + 1; i < toIndex; i++) {
    if (input[i] < minValue) minValue = input[i];
  }
  return minValue;
}

function rescale$1(input) {
  var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  if (!isAnyArray$1(input)) {
    throw new TypeError('input must be an array');
  } else if (input.length === 0) {
    throw new TypeError('input must not be empty');
  }
  var output;
  if (options.output !== undefined) {
    if (!isAnyArray$1(options.output)) {
      throw new TypeError('output option must be an array if specified');
    }
    output = options.output;
  } else {
    output = new Array(input.length);
  }
  var currentMin = min$1(input);
  var currentMax = max$2(input);
  if (currentMin === currentMax) {
    throw new RangeError('minimum and maximum input values are equal. Cannot rescale a constant array');
  }
  var _options$min = options.min,
    minValue = _options$min === void 0 ? options.autoMinMax ? currentMin : 0 : _options$min,
    _options$max = options.max,
    maxValue = _options$max === void 0 ? options.autoMinMax ? currentMax : 1 : _options$max;
  if (minValue >= maxValue) {
    throw new RangeError('min option must be smaller than max option');
  }
  var factor = (maxValue - minValue) / (currentMax - currentMin);
  for (var i = 0; i < input.length; i++) {
    output[i] = (input[i] - currentMin) * factor + minValue;
  }
  return output;
}

var libEs6 = /*#__PURE__*/Object.freeze({
	__proto__: null,
	default: rescale$1
});

var require$$1 = /*@__PURE__*/getAugmentedNamespace(libEs6);

Object.defineProperty(matrix, '__esModule', {
  value: true
});
var isAnyArray = require$$0;
var rescale = require$$1;
const indent = ' '.repeat(2);
const indentData = ' '.repeat(4);

/**
 * @this {Matrix}
 * @returns {string}
 */
function inspectMatrix() {
  return inspectMatrixWithOptions(this);
}
function inspectMatrixWithOptions(matrix, options = {}) {
  const {
    maxRows = 15,
    maxColumns = 10,
    maxNumSize = 8,
    padMinus = 'auto'
  } = options;
  return `${matrix.constructor.name} {
${indent}[
${indentData}${inspectData(matrix, maxRows, maxColumns, maxNumSize, padMinus)}
${indent}]
${indent}rows: ${matrix.rows}
${indent}columns: ${matrix.columns}
}`;
}
function inspectData(matrix, maxRows, maxColumns, maxNumSize, padMinus) {
  const {
    rows,
    columns
  } = matrix;
  const maxI = Math.min(rows, maxRows);
  const maxJ = Math.min(columns, maxColumns);
  const result = [];
  if (padMinus === 'auto') {
    padMinus = false;
    loop: for (let i = 0; i < maxI; i++) {
      for (let j = 0; j < maxJ; j++) {
        if (matrix.get(i, j) < 0) {
          padMinus = true;
          break loop;
        }
      }
    }
  }
  for (let i = 0; i < maxI; i++) {
    let line = [];
    for (let j = 0; j < maxJ; j++) {
      line.push(formatNumber(matrix.get(i, j), maxNumSize, padMinus));
    }
    result.push(`${line.join(' ')}`);
  }
  if (maxJ !== columns) {
    result[result.length - 1] += ` ... ${columns - maxColumns} more columns`;
  }
  if (maxI !== rows) {
    result.push(`... ${rows - maxRows} more rows`);
  }
  return result.join(`\n${indentData}`);
}
function formatNumber(num, maxNumSize, padMinus) {
  return (num >= 0 && padMinus ? ` ${formatNumber2(num, maxNumSize - 1)}` : formatNumber2(num, maxNumSize)).padEnd(maxNumSize);
}
function formatNumber2(num, len) {
  // small.length numbers should be as is
  let str = num.toString();
  if (str.length <= len) return str;

  // (7)'0.00123' is better then (7)'1.23e-2'
  // (8)'0.000123' is worse then (7)'1.23e-3',
  let fix = num.toFixed(len);
  if (fix.length > len) {
    fix = num.toFixed(Math.max(0, len - (fix.length - len)));
  }
  if (fix.length <= len && !fix.startsWith('0.000') && !fix.startsWith('-0.000')) {
    return fix;
  }

  // well, if it's still too long the user should've used longer numbers
  let exp = num.toExponential(len);
  if (exp.length > len) {
    exp = num.toExponential(Math.max(0, len - (exp.length - len)));
  }
  return exp.slice(0);
}
function installMathOperations(AbstractMatrix, Matrix) {
  AbstractMatrix.prototype.add = function add(value) {
    if (typeof value === 'number') return this.addS(value);
    return this.addM(value);
  };
  AbstractMatrix.prototype.addS = function addS(value) {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) + value);
      }
    }
    return this;
  };
  AbstractMatrix.prototype.addM = function addM(matrix) {
    matrix = Matrix.checkMatrix(matrix);
    if (this.rows !== matrix.rows || this.columns !== matrix.columns) {
      throw new RangeError('Matrices dimensions must be equal');
    }
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) + matrix.get(i, j));
      }
    }
    return this;
  };
  AbstractMatrix.add = function add(matrix, value) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.add(value);
  };
  AbstractMatrix.prototype.sub = function sub(value) {
    if (typeof value === 'number') return this.subS(value);
    return this.subM(value);
  };
  AbstractMatrix.prototype.subS = function subS(value) {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) - value);
      }
    }
    return this;
  };
  AbstractMatrix.prototype.subM = function subM(matrix) {
    matrix = Matrix.checkMatrix(matrix);
    if (this.rows !== matrix.rows || this.columns !== matrix.columns) {
      throw new RangeError('Matrices dimensions must be equal');
    }
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) - matrix.get(i, j));
      }
    }
    return this;
  };
  AbstractMatrix.sub = function sub(matrix, value) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.sub(value);
  };
  AbstractMatrix.prototype.subtract = AbstractMatrix.prototype.sub;
  AbstractMatrix.prototype.subtractS = AbstractMatrix.prototype.subS;
  AbstractMatrix.prototype.subtractM = AbstractMatrix.prototype.subM;
  AbstractMatrix.subtract = AbstractMatrix.sub;
  AbstractMatrix.prototype.mul = function mul(value) {
    if (typeof value === 'number') return this.mulS(value);
    return this.mulM(value);
  };
  AbstractMatrix.prototype.mulS = function mulS(value) {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) * value);
      }
    }
    return this;
  };
  AbstractMatrix.prototype.mulM = function mulM(matrix) {
    matrix = Matrix.checkMatrix(matrix);
    if (this.rows !== matrix.rows || this.columns !== matrix.columns) {
      throw new RangeError('Matrices dimensions must be equal');
    }
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) * matrix.get(i, j));
      }
    }
    return this;
  };
  AbstractMatrix.mul = function mul(matrix, value) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.mul(value);
  };
  AbstractMatrix.prototype.multiply = AbstractMatrix.prototype.mul;
  AbstractMatrix.prototype.multiplyS = AbstractMatrix.prototype.mulS;
  AbstractMatrix.prototype.multiplyM = AbstractMatrix.prototype.mulM;
  AbstractMatrix.multiply = AbstractMatrix.mul;
  AbstractMatrix.prototype.div = function div(value) {
    if (typeof value === 'number') return this.divS(value);
    return this.divM(value);
  };
  AbstractMatrix.prototype.divS = function divS(value) {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) / value);
      }
    }
    return this;
  };
  AbstractMatrix.prototype.divM = function divM(matrix) {
    matrix = Matrix.checkMatrix(matrix);
    if (this.rows !== matrix.rows || this.columns !== matrix.columns) {
      throw new RangeError('Matrices dimensions must be equal');
    }
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) / matrix.get(i, j));
      }
    }
    return this;
  };
  AbstractMatrix.div = function div(matrix, value) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.div(value);
  };
  AbstractMatrix.prototype.divide = AbstractMatrix.prototype.div;
  AbstractMatrix.prototype.divideS = AbstractMatrix.prototype.divS;
  AbstractMatrix.prototype.divideM = AbstractMatrix.prototype.divM;
  AbstractMatrix.divide = AbstractMatrix.div;
  AbstractMatrix.prototype.mod = function mod(value) {
    if (typeof value === 'number') return this.modS(value);
    return this.modM(value);
  };
  AbstractMatrix.prototype.modS = function modS(value) {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) % value);
      }
    }
    return this;
  };
  AbstractMatrix.prototype.modM = function modM(matrix) {
    matrix = Matrix.checkMatrix(matrix);
    if (this.rows !== matrix.rows || this.columns !== matrix.columns) {
      throw new RangeError('Matrices dimensions must be equal');
    }
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) % matrix.get(i, j));
      }
    }
    return this;
  };
  AbstractMatrix.mod = function mod(matrix, value) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.mod(value);
  };
  AbstractMatrix.prototype.modulus = AbstractMatrix.prototype.mod;
  AbstractMatrix.prototype.modulusS = AbstractMatrix.prototype.modS;
  AbstractMatrix.prototype.modulusM = AbstractMatrix.prototype.modM;
  AbstractMatrix.modulus = AbstractMatrix.mod;
  AbstractMatrix.prototype.and = function and(value) {
    if (typeof value === 'number') return this.andS(value);
    return this.andM(value);
  };
  AbstractMatrix.prototype.andS = function andS(value) {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) & value);
      }
    }
    return this;
  };
  AbstractMatrix.prototype.andM = function andM(matrix) {
    matrix = Matrix.checkMatrix(matrix);
    if (this.rows !== matrix.rows || this.columns !== matrix.columns) {
      throw new RangeError('Matrices dimensions must be equal');
    }
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) & matrix.get(i, j));
      }
    }
    return this;
  };
  AbstractMatrix.and = function and(matrix, value) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.and(value);
  };
  AbstractMatrix.prototype.or = function or(value) {
    if (typeof value === 'number') return this.orS(value);
    return this.orM(value);
  };
  AbstractMatrix.prototype.orS = function orS(value) {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) | value);
      }
    }
    return this;
  };
  AbstractMatrix.prototype.orM = function orM(matrix) {
    matrix = Matrix.checkMatrix(matrix);
    if (this.rows !== matrix.rows || this.columns !== matrix.columns) {
      throw new RangeError('Matrices dimensions must be equal');
    }
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) | matrix.get(i, j));
      }
    }
    return this;
  };
  AbstractMatrix.or = function or(matrix, value) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.or(value);
  };
  AbstractMatrix.prototype.xor = function xor(value) {
    if (typeof value === 'number') return this.xorS(value);
    return this.xorM(value);
  };
  AbstractMatrix.prototype.xorS = function xorS(value) {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) ^ value);
      }
    }
    return this;
  };
  AbstractMatrix.prototype.xorM = function xorM(matrix) {
    matrix = Matrix.checkMatrix(matrix);
    if (this.rows !== matrix.rows || this.columns !== matrix.columns) {
      throw new RangeError('Matrices dimensions must be equal');
    }
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) ^ matrix.get(i, j));
      }
    }
    return this;
  };
  AbstractMatrix.xor = function xor(matrix, value) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.xor(value);
  };
  AbstractMatrix.prototype.leftShift = function leftShift(value) {
    if (typeof value === 'number') return this.leftShiftS(value);
    return this.leftShiftM(value);
  };
  AbstractMatrix.prototype.leftShiftS = function leftShiftS(value) {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) << value);
      }
    }
    return this;
  };
  AbstractMatrix.prototype.leftShiftM = function leftShiftM(matrix) {
    matrix = Matrix.checkMatrix(matrix);
    if (this.rows !== matrix.rows || this.columns !== matrix.columns) {
      throw new RangeError('Matrices dimensions must be equal');
    }
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) << matrix.get(i, j));
      }
    }
    return this;
  };
  AbstractMatrix.leftShift = function leftShift(matrix, value) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.leftShift(value);
  };
  AbstractMatrix.prototype.signPropagatingRightShift = function signPropagatingRightShift(value) {
    if (typeof value === 'number') return this.signPropagatingRightShiftS(value);
    return this.signPropagatingRightShiftM(value);
  };
  AbstractMatrix.prototype.signPropagatingRightShiftS = function signPropagatingRightShiftS(value) {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) >> value);
      }
    }
    return this;
  };
  AbstractMatrix.prototype.signPropagatingRightShiftM = function signPropagatingRightShiftM(matrix) {
    matrix = Matrix.checkMatrix(matrix);
    if (this.rows !== matrix.rows || this.columns !== matrix.columns) {
      throw new RangeError('Matrices dimensions must be equal');
    }
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) >> matrix.get(i, j));
      }
    }
    return this;
  };
  AbstractMatrix.signPropagatingRightShift = function signPropagatingRightShift(matrix, value) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.signPropagatingRightShift(value);
  };
  AbstractMatrix.prototype.rightShift = function rightShift(value) {
    if (typeof value === 'number') return this.rightShiftS(value);
    return this.rightShiftM(value);
  };
  AbstractMatrix.prototype.rightShiftS = function rightShiftS(value) {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) >>> value);
      }
    }
    return this;
  };
  AbstractMatrix.prototype.rightShiftM = function rightShiftM(matrix) {
    matrix = Matrix.checkMatrix(matrix);
    if (this.rows !== matrix.rows || this.columns !== matrix.columns) {
      throw new RangeError('Matrices dimensions must be equal');
    }
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) >>> matrix.get(i, j));
      }
    }
    return this;
  };
  AbstractMatrix.rightShift = function rightShift(matrix, value) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.rightShift(value);
  };
  AbstractMatrix.prototype.zeroFillRightShift = AbstractMatrix.prototype.rightShift;
  AbstractMatrix.prototype.zeroFillRightShiftS = AbstractMatrix.prototype.rightShiftS;
  AbstractMatrix.prototype.zeroFillRightShiftM = AbstractMatrix.prototype.rightShiftM;
  AbstractMatrix.zeroFillRightShift = AbstractMatrix.rightShift;
  AbstractMatrix.prototype.not = function not() {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, ~this.get(i, j));
      }
    }
    return this;
  };
  AbstractMatrix.not = function not(matrix) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.not();
  };
  AbstractMatrix.prototype.abs = function abs() {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, Math.abs(this.get(i, j)));
      }
    }
    return this;
  };
  AbstractMatrix.abs = function abs(matrix) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.abs();
  };
  AbstractMatrix.prototype.acos = function acos() {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, Math.acos(this.get(i, j)));
      }
    }
    return this;
  };
  AbstractMatrix.acos = function acos(matrix) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.acos();
  };
  AbstractMatrix.prototype.acosh = function acosh() {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, Math.acosh(this.get(i, j)));
      }
    }
    return this;
  };
  AbstractMatrix.acosh = function acosh(matrix) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.acosh();
  };
  AbstractMatrix.prototype.asin = function asin() {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, Math.asin(this.get(i, j)));
      }
    }
    return this;
  };
  AbstractMatrix.asin = function asin(matrix) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.asin();
  };
  AbstractMatrix.prototype.asinh = function asinh() {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, Math.asinh(this.get(i, j)));
      }
    }
    return this;
  };
  AbstractMatrix.asinh = function asinh(matrix) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.asinh();
  };
  AbstractMatrix.prototype.atan = function atan() {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, Math.atan(this.get(i, j)));
      }
    }
    return this;
  };
  AbstractMatrix.atan = function atan(matrix) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.atan();
  };
  AbstractMatrix.prototype.atanh = function atanh() {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, Math.atanh(this.get(i, j)));
      }
    }
    return this;
  };
  AbstractMatrix.atanh = function atanh(matrix) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.atanh();
  };
  AbstractMatrix.prototype.cbrt = function cbrt() {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, Math.cbrt(this.get(i, j)));
      }
    }
    return this;
  };
  AbstractMatrix.cbrt = function cbrt(matrix) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.cbrt();
  };
  AbstractMatrix.prototype.ceil = function ceil() {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, Math.ceil(this.get(i, j)));
      }
    }
    return this;
  };
  AbstractMatrix.ceil = function ceil(matrix) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.ceil();
  };
  AbstractMatrix.prototype.clz32 = function clz32() {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, Math.clz32(this.get(i, j)));
      }
    }
    return this;
  };
  AbstractMatrix.clz32 = function clz32(matrix) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.clz32();
  };
  AbstractMatrix.prototype.cos = function cos() {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, Math.cos(this.get(i, j)));
      }
    }
    return this;
  };
  AbstractMatrix.cos = function cos(matrix) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.cos();
  };
  AbstractMatrix.prototype.cosh = function cosh() {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, Math.cosh(this.get(i, j)));
      }
    }
    return this;
  };
  AbstractMatrix.cosh = function cosh(matrix) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.cosh();
  };
  AbstractMatrix.prototype.exp = function exp() {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, Math.exp(this.get(i, j)));
      }
    }
    return this;
  };
  AbstractMatrix.exp = function exp(matrix) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.exp();
  };
  AbstractMatrix.prototype.expm1 = function expm1() {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, Math.expm1(this.get(i, j)));
      }
    }
    return this;
  };
  AbstractMatrix.expm1 = function expm1(matrix) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.expm1();
  };
  AbstractMatrix.prototype.floor = function floor() {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, Math.floor(this.get(i, j)));
      }
    }
    return this;
  };
  AbstractMatrix.floor = function floor(matrix) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.floor();
  };
  AbstractMatrix.prototype.fround = function fround() {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, Math.fround(this.get(i, j)));
      }
    }
    return this;
  };
  AbstractMatrix.fround = function fround(matrix) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.fround();
  };
  AbstractMatrix.prototype.log = function log() {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, Math.log(this.get(i, j)));
      }
    }
    return this;
  };
  AbstractMatrix.log = function log(matrix) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.log();
  };
  AbstractMatrix.prototype.log1p = function log1p() {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, Math.log1p(this.get(i, j)));
      }
    }
    return this;
  };
  AbstractMatrix.log1p = function log1p(matrix) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.log1p();
  };
  AbstractMatrix.prototype.log10 = function log10() {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, Math.log10(this.get(i, j)));
      }
    }
    return this;
  };
  AbstractMatrix.log10 = function log10(matrix) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.log10();
  };
  AbstractMatrix.prototype.log2 = function log2() {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, Math.log2(this.get(i, j)));
      }
    }
    return this;
  };
  AbstractMatrix.log2 = function log2(matrix) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.log2();
  };
  AbstractMatrix.prototype.round = function round() {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, Math.round(this.get(i, j)));
      }
    }
    return this;
  };
  AbstractMatrix.round = function round(matrix) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.round();
  };
  AbstractMatrix.prototype.sign = function sign() {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, Math.sign(this.get(i, j)));
      }
    }
    return this;
  };
  AbstractMatrix.sign = function sign(matrix) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.sign();
  };
  AbstractMatrix.prototype.sin = function sin() {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, Math.sin(this.get(i, j)));
      }
    }
    return this;
  };
  AbstractMatrix.sin = function sin(matrix) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.sin();
  };
  AbstractMatrix.prototype.sinh = function sinh() {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, Math.sinh(this.get(i, j)));
      }
    }
    return this;
  };
  AbstractMatrix.sinh = function sinh(matrix) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.sinh();
  };
  AbstractMatrix.prototype.sqrt = function sqrt() {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, Math.sqrt(this.get(i, j)));
      }
    }
    return this;
  };
  AbstractMatrix.sqrt = function sqrt(matrix) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.sqrt();
  };
  AbstractMatrix.prototype.tan = function tan() {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, Math.tan(this.get(i, j)));
      }
    }
    return this;
  };
  AbstractMatrix.tan = function tan(matrix) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.tan();
  };
  AbstractMatrix.prototype.tanh = function tanh() {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, Math.tanh(this.get(i, j)));
      }
    }
    return this;
  };
  AbstractMatrix.tanh = function tanh(matrix) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.tanh();
  };
  AbstractMatrix.prototype.trunc = function trunc() {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, Math.trunc(this.get(i, j)));
      }
    }
    return this;
  };
  AbstractMatrix.trunc = function trunc(matrix) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.trunc();
  };
  AbstractMatrix.pow = function pow(matrix, arg0) {
    const newMatrix = new Matrix(matrix);
    return newMatrix.pow(arg0);
  };
  AbstractMatrix.prototype.pow = function pow(value) {
    if (typeof value === 'number') return this.powS(value);
    return this.powM(value);
  };
  AbstractMatrix.prototype.powS = function powS(value) {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) ** value);
      }
    }
    return this;
  };
  AbstractMatrix.prototype.powM = function powM(matrix) {
    matrix = Matrix.checkMatrix(matrix);
    if (this.rows !== matrix.rows || this.columns !== matrix.columns) {
      throw new RangeError('Matrices dimensions must be equal');
    }
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) ** matrix.get(i, j));
      }
    }
    return this;
  };
}

/**
 * @private
 * Check that a row index is not out of bounds
 * @param {Matrix} matrix
 * @param {number} index
 * @param {boolean} [outer]
 */
function checkRowIndex(matrix, index, outer) {
  let max = outer ? matrix.rows : matrix.rows - 1;
  if (index < 0 || index > max) {
    throw new RangeError('Row index out of range');
  }
}

/**
 * @private
 * Check that a column index is not out of bounds
 * @param {Matrix} matrix
 * @param {number} index
 * @param {boolean} [outer]
 */
function checkColumnIndex(matrix, index, outer) {
  let max = outer ? matrix.columns : matrix.columns - 1;
  if (index < 0 || index > max) {
    throw new RangeError('Column index out of range');
  }
}

/**
 * @private
 * Check that the provided vector is an array with the right length
 * @param {Matrix} matrix
 * @param {Array|Matrix} vector
 * @return {Array}
 * @throws {RangeError}
 */
function checkRowVector(matrix, vector) {
  if (vector.to1DArray) {
    vector = vector.to1DArray();
  }
  if (vector.length !== matrix.columns) {
    throw new RangeError('vector size must be the same as the number of columns');
  }
  return vector;
}

/**
 * @private
 * Check that the provided vector is an array with the right length
 * @param {Matrix} matrix
 * @param {Array|Matrix} vector
 * @return {Array}
 * @throws {RangeError}
 */
function checkColumnVector(matrix, vector) {
  if (vector.to1DArray) {
    vector = vector.to1DArray();
  }
  if (vector.length !== matrix.rows) {
    throw new RangeError('vector size must be the same as the number of rows');
  }
  return vector;
}
function checkRowIndices(matrix, rowIndices) {
  if (!isAnyArray.isAnyArray(rowIndices)) {
    throw new TypeError('row indices must be an array');
  }
  for (let i = 0; i < rowIndices.length; i++) {
    if (rowIndices[i] < 0 || rowIndices[i] >= matrix.rows) {
      throw new RangeError('row indices are out of range');
    }
  }
}
function checkColumnIndices(matrix, columnIndices) {
  if (!isAnyArray.isAnyArray(columnIndices)) {
    throw new TypeError('column indices must be an array');
  }
  for (let i = 0; i < columnIndices.length; i++) {
    if (columnIndices[i] < 0 || columnIndices[i] >= matrix.columns) {
      throw new RangeError('column indices are out of range');
    }
  }
}
function checkRange$1(matrix, startRow, endRow, startColumn, endColumn) {
  if (arguments.length !== 5) {
    throw new RangeError('expected 4 arguments');
  }
  checkNumber('startRow', startRow);
  checkNumber('endRow', endRow);
  checkNumber('startColumn', startColumn);
  checkNumber('endColumn', endColumn);
  if (startRow > endRow || startColumn > endColumn || startRow < 0 || startRow >= matrix.rows || endRow < 0 || endRow >= matrix.rows || startColumn < 0 || startColumn >= matrix.columns || endColumn < 0 || endColumn >= matrix.columns) {
    throw new RangeError('Submatrix indices are out of range');
  }
}
function newArray(length, value = 0) {
  let array = [];
  for (let i = 0; i < length; i++) {
    array.push(value);
  }
  return array;
}
function checkNumber(name, value) {
  if (typeof value !== 'number') {
    throw new TypeError(`${name} must be a number`);
  }
}
function checkNonEmpty(matrix) {
  if (matrix.isEmpty()) {
    throw new Error('Empty matrix has no elements to index');
  }
}
function sumByRow(matrix) {
  let sum = newArray(matrix.rows);
  for (let i = 0; i < matrix.rows; ++i) {
    for (let j = 0; j < matrix.columns; ++j) {
      sum[i] += matrix.get(i, j);
    }
  }
  return sum;
}
function sumByColumn(matrix) {
  let sum = newArray(matrix.columns);
  for (let i = 0; i < matrix.rows; ++i) {
    for (let j = 0; j < matrix.columns; ++j) {
      sum[j] += matrix.get(i, j);
    }
  }
  return sum;
}
function sumAll(matrix) {
  let v = 0;
  for (let i = 0; i < matrix.rows; i++) {
    for (let j = 0; j < matrix.columns; j++) {
      v += matrix.get(i, j);
    }
  }
  return v;
}
function productByRow(matrix) {
  let sum = newArray(matrix.rows, 1);
  for (let i = 0; i < matrix.rows; ++i) {
    for (let j = 0; j < matrix.columns; ++j) {
      sum[i] *= matrix.get(i, j);
    }
  }
  return sum;
}
function productByColumn(matrix) {
  let sum = newArray(matrix.columns, 1);
  for (let i = 0; i < matrix.rows; ++i) {
    for (let j = 0; j < matrix.columns; ++j) {
      sum[j] *= matrix.get(i, j);
    }
  }
  return sum;
}
function productAll(matrix) {
  let v = 1;
  for (let i = 0; i < matrix.rows; i++) {
    for (let j = 0; j < matrix.columns; j++) {
      v *= matrix.get(i, j);
    }
  }
  return v;
}
function varianceByRow(matrix, unbiased, mean) {
  const rows = matrix.rows;
  const cols = matrix.columns;
  const variance = [];
  for (let i = 0; i < rows; i++) {
    let sum1 = 0;
    let sum2 = 0;
    let x = 0;
    for (let j = 0; j < cols; j++) {
      x = matrix.get(i, j) - mean[i];
      sum1 += x;
      sum2 += x * x;
    }
    if (unbiased) {
      variance.push((sum2 - sum1 * sum1 / cols) / (cols - 1));
    } else {
      variance.push((sum2 - sum1 * sum1 / cols) / cols);
    }
  }
  return variance;
}
function varianceByColumn(matrix, unbiased, mean) {
  const rows = matrix.rows;
  const cols = matrix.columns;
  const variance = [];
  for (let j = 0; j < cols; j++) {
    let sum1 = 0;
    let sum2 = 0;
    let x = 0;
    for (let i = 0; i < rows; i++) {
      x = matrix.get(i, j) - mean[j];
      sum1 += x;
      sum2 += x * x;
    }
    if (unbiased) {
      variance.push((sum2 - sum1 * sum1 / rows) / (rows - 1));
    } else {
      variance.push((sum2 - sum1 * sum1 / rows) / rows);
    }
  }
  return variance;
}
function varianceAll(matrix, unbiased, mean) {
  const rows = matrix.rows;
  const cols = matrix.columns;
  const size = rows * cols;
  let sum1 = 0;
  let sum2 = 0;
  let x = 0;
  for (let i = 0; i < rows; i++) {
    for (let j = 0; j < cols; j++) {
      x = matrix.get(i, j) - mean;
      sum1 += x;
      sum2 += x * x;
    }
  }
  if (unbiased) {
    return (sum2 - sum1 * sum1 / size) / (size - 1);
  } else {
    return (sum2 - sum1 * sum1 / size) / size;
  }
}
function centerByRow(matrix, mean) {
  for (let i = 0; i < matrix.rows; i++) {
    for (let j = 0; j < matrix.columns; j++) {
      matrix.set(i, j, matrix.get(i, j) - mean[i]);
    }
  }
}
function centerByColumn(matrix, mean) {
  for (let i = 0; i < matrix.rows; i++) {
    for (let j = 0; j < matrix.columns; j++) {
      matrix.set(i, j, matrix.get(i, j) - mean[j]);
    }
  }
}
function centerAll(matrix, mean) {
  for (let i = 0; i < matrix.rows; i++) {
    for (let j = 0; j < matrix.columns; j++) {
      matrix.set(i, j, matrix.get(i, j) - mean);
    }
  }
}
function getScaleByRow(matrix) {
  const scale = [];
  for (let i = 0; i < matrix.rows; i++) {
    let sum = 0;
    for (let j = 0; j < matrix.columns; j++) {
      sum += matrix.get(i, j) ** 2 / (matrix.columns - 1);
    }
    scale.push(Math.sqrt(sum));
  }
  return scale;
}
function scaleByRow(matrix, scale) {
  for (let i = 0; i < matrix.rows; i++) {
    for (let j = 0; j < matrix.columns; j++) {
      matrix.set(i, j, matrix.get(i, j) / scale[i]);
    }
  }
}
function getScaleByColumn(matrix) {
  const scale = [];
  for (let j = 0; j < matrix.columns; j++) {
    let sum = 0;
    for (let i = 0; i < matrix.rows; i++) {
      sum += matrix.get(i, j) ** 2 / (matrix.rows - 1);
    }
    scale.push(Math.sqrt(sum));
  }
  return scale;
}
function scaleByColumn(matrix, scale) {
  for (let i = 0; i < matrix.rows; i++) {
    for (let j = 0; j < matrix.columns; j++) {
      matrix.set(i, j, matrix.get(i, j) / scale[j]);
    }
  }
}
function getScaleAll(matrix) {
  const divider = matrix.size - 1;
  let sum = 0;
  for (let j = 0; j < matrix.columns; j++) {
    for (let i = 0; i < matrix.rows; i++) {
      sum += matrix.get(i, j) ** 2 / divider;
    }
  }
  return Math.sqrt(sum);
}
function scaleAll(matrix, scale) {
  for (let i = 0; i < matrix.rows; i++) {
    for (let j = 0; j < matrix.columns; j++) {
      matrix.set(i, j, matrix.get(i, j) / scale);
    }
  }
}
class AbstractMatrix {
  static from1DArray(newRows, newColumns, newData) {
    let length = newRows * newColumns;
    if (length !== newData.length) {
      throw new RangeError('data length does not match given dimensions');
    }
    let newMatrix = new Matrix$2(newRows, newColumns);
    for (let row = 0; row < newRows; row++) {
      for (let column = 0; column < newColumns; column++) {
        newMatrix.set(row, column, newData[row * newColumns + column]);
      }
    }
    return newMatrix;
  }
  static rowVector(newData) {
    let vector = new Matrix$2(1, newData.length);
    for (let i = 0; i < newData.length; i++) {
      vector.set(0, i, newData[i]);
    }
    return vector;
  }
  static columnVector(newData) {
    let vector = new Matrix$2(newData.length, 1);
    for (let i = 0; i < newData.length; i++) {
      vector.set(i, 0, newData[i]);
    }
    return vector;
  }
  static zeros(rows, columns) {
    return new Matrix$2(rows, columns);
  }
  static ones(rows, columns) {
    return new Matrix$2(rows, columns).fill(1);
  }
  static rand(rows, columns, options = {}) {
    if (typeof options !== 'object') {
      throw new TypeError('options must be an object');
    }
    const {
      random = Math.random
    } = options;
    let matrix = new Matrix$2(rows, columns);
    for (let i = 0; i < rows; i++) {
      for (let j = 0; j < columns; j++) {
        matrix.set(i, j, random());
      }
    }
    return matrix;
  }
  static randInt(rows, columns, options = {}) {
    if (typeof options !== 'object') {
      throw new TypeError('options must be an object');
    }
    const {
      min = 0,
      max = 1000,
      random = Math.random
    } = options;
    if (!Number.isInteger(min)) throw new TypeError('min must be an integer');
    if (!Number.isInteger(max)) throw new TypeError('max must be an integer');
    if (min >= max) throw new RangeError('min must be smaller than max');
    let interval = max - min;
    let matrix = new Matrix$2(rows, columns);
    for (let i = 0; i < rows; i++) {
      for (let j = 0; j < columns; j++) {
        let value = min + Math.round(random() * interval);
        matrix.set(i, j, value);
      }
    }
    return matrix;
  }
  static eye(rows, columns, value) {
    if (columns === undefined) columns = rows;
    if (value === undefined) value = 1;
    let min = Math.min(rows, columns);
    let matrix = this.zeros(rows, columns);
    for (let i = 0; i < min; i++) {
      matrix.set(i, i, value);
    }
    return matrix;
  }
  static diag(data, rows, columns) {
    let l = data.length;
    if (rows === undefined) rows = l;
    if (columns === undefined) columns = rows;
    let min = Math.min(l, rows, columns);
    let matrix = this.zeros(rows, columns);
    for (let i = 0; i < min; i++) {
      matrix.set(i, i, data[i]);
    }
    return matrix;
  }
  static min(matrix1, matrix2) {
    matrix1 = this.checkMatrix(matrix1);
    matrix2 = this.checkMatrix(matrix2);
    let rows = matrix1.rows;
    let columns = matrix1.columns;
    let result = new Matrix$2(rows, columns);
    for (let i = 0; i < rows; i++) {
      for (let j = 0; j < columns; j++) {
        result.set(i, j, Math.min(matrix1.get(i, j), matrix2.get(i, j)));
      }
    }
    return result;
  }
  static max(matrix1, matrix2) {
    matrix1 = this.checkMatrix(matrix1);
    matrix2 = this.checkMatrix(matrix2);
    let rows = matrix1.rows;
    let columns = matrix1.columns;
    let result = new this(rows, columns);
    for (let i = 0; i < rows; i++) {
      for (let j = 0; j < columns; j++) {
        result.set(i, j, Math.max(matrix1.get(i, j), matrix2.get(i, j)));
      }
    }
    return result;
  }
  static checkMatrix(value) {
    return AbstractMatrix.isMatrix(value) ? value : new Matrix$2(value);
  }
  static isMatrix(value) {
    return value != null && value.klass === 'Matrix';
  }
  get size() {
    return this.rows * this.columns;
  }
  apply(callback) {
    if (typeof callback !== 'function') {
      throw new TypeError('callback must be a function');
    }
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        callback.call(this, i, j);
      }
    }
    return this;
  }
  to1DArray() {
    let array = [];
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        array.push(this.get(i, j));
      }
    }
    return array;
  }
  to2DArray() {
    let copy = [];
    for (let i = 0; i < this.rows; i++) {
      copy.push([]);
      for (let j = 0; j < this.columns; j++) {
        copy[i].push(this.get(i, j));
      }
    }
    return copy;
  }
  toJSON() {
    return this.to2DArray();
  }
  isRowVector() {
    return this.rows === 1;
  }
  isColumnVector() {
    return this.columns === 1;
  }
  isVector() {
    return this.rows === 1 || this.columns === 1;
  }
  isSquare() {
    return this.rows === this.columns;
  }
  isEmpty() {
    return this.rows === 0 || this.columns === 0;
  }
  isSymmetric() {
    if (this.isSquare()) {
      for (let i = 0; i < this.rows; i++) {
        for (let j = 0; j <= i; j++) {
          if (this.get(i, j) !== this.get(j, i)) {
            return false;
          }
        }
      }
      return true;
    }
    return false;
  }
  isDistance() {
    if (!this.isSymmetric()) return false;
    for (let i = 0; i < this.rows; i++) {
      if (this.get(i, i) !== 0) return false;
    }
    return true;
  }
  isEchelonForm() {
    let i = 0;
    let j = 0;
    let previousColumn = -1;
    let isEchelonForm = true;
    let checked = false;
    while (i < this.rows && isEchelonForm) {
      j = 0;
      checked = false;
      while (j < this.columns && checked === false) {
        if (this.get(i, j) === 0) {
          j++;
        } else if (this.get(i, j) === 1 && j > previousColumn) {
          checked = true;
          previousColumn = j;
        } else {
          isEchelonForm = false;
          checked = true;
        }
      }
      i++;
    }
    return isEchelonForm;
  }
  isReducedEchelonForm() {
    let i = 0;
    let j = 0;
    let previousColumn = -1;
    let isReducedEchelonForm = true;
    let checked = false;
    while (i < this.rows && isReducedEchelonForm) {
      j = 0;
      checked = false;
      while (j < this.columns && checked === false) {
        if (this.get(i, j) === 0) {
          j++;
        } else if (this.get(i, j) === 1 && j > previousColumn) {
          checked = true;
          previousColumn = j;
        } else {
          isReducedEchelonForm = false;
          checked = true;
        }
      }
      for (let k = j + 1; k < this.rows; k++) {
        if (this.get(i, k) !== 0) {
          isReducedEchelonForm = false;
        }
      }
      i++;
    }
    return isReducedEchelonForm;
  }
  echelonForm() {
    let result = this.clone();
    let h = 0;
    let k = 0;
    while (h < result.rows && k < result.columns) {
      let iMax = h;
      for (let i = h; i < result.rows; i++) {
        if (result.get(i, k) > result.get(iMax, k)) {
          iMax = i;
        }
      }
      if (result.get(iMax, k) === 0) {
        k++;
      } else {
        result.swapRows(h, iMax);
        let tmp = result.get(h, k);
        for (let j = k; j < result.columns; j++) {
          result.set(h, j, result.get(h, j) / tmp);
        }
        for (let i = h + 1; i < result.rows; i++) {
          let factor = result.get(i, k) / result.get(h, k);
          result.set(i, k, 0);
          for (let j = k + 1; j < result.columns; j++) {
            result.set(i, j, result.get(i, j) - result.get(h, j) * factor);
          }
        }
        h++;
        k++;
      }
    }
    return result;
  }
  reducedEchelonForm() {
    let result = this.echelonForm();
    let m = result.columns;
    let n = result.rows;
    let h = n - 1;
    while (h >= 0) {
      if (result.maxRow(h) === 0) {
        h--;
      } else {
        let p = 0;
        let pivot = false;
        while (p < n && pivot === false) {
          if (result.get(h, p) === 1) {
            pivot = true;
          } else {
            p++;
          }
        }
        for (let i = 0; i < h; i++) {
          let factor = result.get(i, p);
          for (let j = p; j < m; j++) {
            let tmp = result.get(i, j) - factor * result.get(h, j);
            result.set(i, j, tmp);
          }
        }
        h--;
      }
    }
    return result;
  }
  set() {
    throw new Error('set method is unimplemented');
  }
  get() {
    throw new Error('get method is unimplemented');
  }
  repeat(options = {}) {
    if (typeof options !== 'object') {
      throw new TypeError('options must be an object');
    }
    const {
      rows = 1,
      columns = 1
    } = options;
    if (!Number.isInteger(rows) || rows <= 0) {
      throw new TypeError('rows must be a positive integer');
    }
    if (!Number.isInteger(columns) || columns <= 0) {
      throw new TypeError('columns must be a positive integer');
    }
    let matrix = new Matrix$2(this.rows * rows, this.columns * columns);
    for (let i = 0; i < rows; i++) {
      for (let j = 0; j < columns; j++) {
        matrix.setSubMatrix(this, this.rows * i, this.columns * j);
      }
    }
    return matrix;
  }
  fill(value) {
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, value);
      }
    }
    return this;
  }
  neg() {
    return this.mulS(-1);
  }
  getRow(index) {
    checkRowIndex(this, index);
    let row = [];
    for (let i = 0; i < this.columns; i++) {
      row.push(this.get(index, i));
    }
    return row;
  }
  getRowVector(index) {
    return Matrix$2.rowVector(this.getRow(index));
  }
  setRow(index, array) {
    checkRowIndex(this, index);
    array = checkRowVector(this, array);
    for (let i = 0; i < this.columns; i++) {
      this.set(index, i, array[i]);
    }
    return this;
  }
  swapRows(row1, row2) {
    checkRowIndex(this, row1);
    checkRowIndex(this, row2);
    for (let i = 0; i < this.columns; i++) {
      let temp = this.get(row1, i);
      this.set(row1, i, this.get(row2, i));
      this.set(row2, i, temp);
    }
    return this;
  }
  getColumn(index) {
    checkColumnIndex(this, index);
    let column = [];
    for (let i = 0; i < this.rows; i++) {
      column.push(this.get(i, index));
    }
    return column;
  }
  getColumnVector(index) {
    return Matrix$2.columnVector(this.getColumn(index));
  }
  setColumn(index, array) {
    checkColumnIndex(this, index);
    array = checkColumnVector(this, array);
    for (let i = 0; i < this.rows; i++) {
      this.set(i, index, array[i]);
    }
    return this;
  }
  swapColumns(column1, column2) {
    checkColumnIndex(this, column1);
    checkColumnIndex(this, column2);
    for (let i = 0; i < this.rows; i++) {
      let temp = this.get(i, column1);
      this.set(i, column1, this.get(i, column2));
      this.set(i, column2, temp);
    }
    return this;
  }
  addRowVector(vector) {
    vector = checkRowVector(this, vector);
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) + vector[j]);
      }
    }
    return this;
  }
  subRowVector(vector) {
    vector = checkRowVector(this, vector);
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) - vector[j]);
      }
    }
    return this;
  }
  mulRowVector(vector) {
    vector = checkRowVector(this, vector);
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) * vector[j]);
      }
    }
    return this;
  }
  divRowVector(vector) {
    vector = checkRowVector(this, vector);
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) / vector[j]);
      }
    }
    return this;
  }
  addColumnVector(vector) {
    vector = checkColumnVector(this, vector);
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) + vector[i]);
      }
    }
    return this;
  }
  subColumnVector(vector) {
    vector = checkColumnVector(this, vector);
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) - vector[i]);
      }
    }
    return this;
  }
  mulColumnVector(vector) {
    vector = checkColumnVector(this, vector);
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) * vector[i]);
      }
    }
    return this;
  }
  divColumnVector(vector) {
    vector = checkColumnVector(this, vector);
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        this.set(i, j, this.get(i, j) / vector[i]);
      }
    }
    return this;
  }
  mulRow(index, value) {
    checkRowIndex(this, index);
    for (let i = 0; i < this.columns; i++) {
      this.set(index, i, this.get(index, i) * value);
    }
    return this;
  }
  mulColumn(index, value) {
    checkColumnIndex(this, index);
    for (let i = 0; i < this.rows; i++) {
      this.set(i, index, this.get(i, index) * value);
    }
    return this;
  }
  max(by) {
    if (this.isEmpty()) {
      return NaN;
    }
    switch (by) {
      case 'row':
        {
          const max = new Array(this.rows).fill(Number.NEGATIVE_INFINITY);
          for (let row = 0; row < this.rows; row++) {
            for (let column = 0; column < this.columns; column++) {
              if (this.get(row, column) > max[row]) {
                max[row] = this.get(row, column);
              }
            }
          }
          return max;
        }
      case 'column':
        {
          const max = new Array(this.columns).fill(Number.NEGATIVE_INFINITY);
          for (let row = 0; row < this.rows; row++) {
            for (let column = 0; column < this.columns; column++) {
              if (this.get(row, column) > max[column]) {
                max[column] = this.get(row, column);
              }
            }
          }
          return max;
        }
      case undefined:
        {
          let max = this.get(0, 0);
          for (let row = 0; row < this.rows; row++) {
            for (let column = 0; column < this.columns; column++) {
              if (this.get(row, column) > max) {
                max = this.get(row, column);
              }
            }
          }
          return max;
        }
      default:
        throw new Error(`invalid option: ${by}`);
    }
  }
  maxIndex() {
    checkNonEmpty(this);
    let v = this.get(0, 0);
    let idx = [0, 0];
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        if (this.get(i, j) > v) {
          v = this.get(i, j);
          idx[0] = i;
          idx[1] = j;
        }
      }
    }
    return idx;
  }
  min(by) {
    if (this.isEmpty()) {
      return NaN;
    }
    switch (by) {
      case 'row':
        {
          const min = new Array(this.rows).fill(Number.POSITIVE_INFINITY);
          for (let row = 0; row < this.rows; row++) {
            for (let column = 0; column < this.columns; column++) {
              if (this.get(row, column) < min[row]) {
                min[row] = this.get(row, column);
              }
            }
          }
          return min;
        }
      case 'column':
        {
          const min = new Array(this.columns).fill(Number.POSITIVE_INFINITY);
          for (let row = 0; row < this.rows; row++) {
            for (let column = 0; column < this.columns; column++) {
              if (this.get(row, column) < min[column]) {
                min[column] = this.get(row, column);
              }
            }
          }
          return min;
        }
      case undefined:
        {
          let min = this.get(0, 0);
          for (let row = 0; row < this.rows; row++) {
            for (let column = 0; column < this.columns; column++) {
              if (this.get(row, column) < min) {
                min = this.get(row, column);
              }
            }
          }
          return min;
        }
      default:
        throw new Error(`invalid option: ${by}`);
    }
  }
  minIndex() {
    checkNonEmpty(this);
    let v = this.get(0, 0);
    let idx = [0, 0];
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        if (this.get(i, j) < v) {
          v = this.get(i, j);
          idx[0] = i;
          idx[1] = j;
        }
      }
    }
    return idx;
  }
  maxRow(row) {
    checkRowIndex(this, row);
    if (this.isEmpty()) {
      return NaN;
    }
    let v = this.get(row, 0);
    for (let i = 1; i < this.columns; i++) {
      if (this.get(row, i) > v) {
        v = this.get(row, i);
      }
    }
    return v;
  }
  maxRowIndex(row) {
    checkRowIndex(this, row);
    checkNonEmpty(this);
    let v = this.get(row, 0);
    let idx = [row, 0];
    for (let i = 1; i < this.columns; i++) {
      if (this.get(row, i) > v) {
        v = this.get(row, i);
        idx[1] = i;
      }
    }
    return idx;
  }
  minRow(row) {
    checkRowIndex(this, row);
    if (this.isEmpty()) {
      return NaN;
    }
    let v = this.get(row, 0);
    for (let i = 1; i < this.columns; i++) {
      if (this.get(row, i) < v) {
        v = this.get(row, i);
      }
    }
    return v;
  }
  minRowIndex(row) {
    checkRowIndex(this, row);
    checkNonEmpty(this);
    let v = this.get(row, 0);
    let idx = [row, 0];
    for (let i = 1; i < this.columns; i++) {
      if (this.get(row, i) < v) {
        v = this.get(row, i);
        idx[1] = i;
      }
    }
    return idx;
  }
  maxColumn(column) {
    checkColumnIndex(this, column);
    if (this.isEmpty()) {
      return NaN;
    }
    let v = this.get(0, column);
    for (let i = 1; i < this.rows; i++) {
      if (this.get(i, column) > v) {
        v = this.get(i, column);
      }
    }
    return v;
  }
  maxColumnIndex(column) {
    checkColumnIndex(this, column);
    checkNonEmpty(this);
    let v = this.get(0, column);
    let idx = [0, column];
    for (let i = 1; i < this.rows; i++) {
      if (this.get(i, column) > v) {
        v = this.get(i, column);
        idx[0] = i;
      }
    }
    return idx;
  }
  minColumn(column) {
    checkColumnIndex(this, column);
    if (this.isEmpty()) {
      return NaN;
    }
    let v = this.get(0, column);
    for (let i = 1; i < this.rows; i++) {
      if (this.get(i, column) < v) {
        v = this.get(i, column);
      }
    }
    return v;
  }
  minColumnIndex(column) {
    checkColumnIndex(this, column);
    checkNonEmpty(this);
    let v = this.get(0, column);
    let idx = [0, column];
    for (let i = 1; i < this.rows; i++) {
      if (this.get(i, column) < v) {
        v = this.get(i, column);
        idx[0] = i;
      }
    }
    return idx;
  }
  diag() {
    let min = Math.min(this.rows, this.columns);
    let diag = [];
    for (let i = 0; i < min; i++) {
      diag.push(this.get(i, i));
    }
    return diag;
  }
  norm(type = 'frobenius') {
    switch (type) {
      case 'max':
        return this.max();
      case 'frobenius':
        return Math.sqrt(this.dot(this));
      default:
        throw new RangeError(`unknown norm type: ${type}`);
    }
  }
  cumulativeSum() {
    let sum = 0;
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        sum += this.get(i, j);
        this.set(i, j, sum);
      }
    }
    return this;
  }
  dot(vector2) {
    if (AbstractMatrix.isMatrix(vector2)) vector2 = vector2.to1DArray();
    let vector1 = this.to1DArray();
    if (vector1.length !== vector2.length) {
      throw new RangeError('vectors do not have the same size');
    }
    let dot = 0;
    for (let i = 0; i < vector1.length; i++) {
      dot += vector1[i] * vector2[i];
    }
    return dot;
  }
  mmul(other) {
    other = Matrix$2.checkMatrix(other);
    let m = this.rows;
    let n = this.columns;
    let p = other.columns;
    let result = new Matrix$2(m, p);
    let Bcolj = new Float64Array(n);
    for (let j = 0; j < p; j++) {
      for (let k = 0; k < n; k++) {
        Bcolj[k] = other.get(k, j);
      }
      for (let i = 0; i < m; i++) {
        let s = 0;
        for (let k = 0; k < n; k++) {
          s += this.get(i, k) * Bcolj[k];
        }
        result.set(i, j, s);
      }
    }
    return result;
  }
  mpow(scalar) {
    if (!this.isSquare()) {
      throw new RangeError('Matrix must be square');
    }
    if (!Number.isInteger(scalar) || scalar < 0) {
      throw new RangeError('Exponent must be a non-negative integer');
    }
    // Russian Peasant exponentiation, i.e. exponentiation by squaring
    let result = Matrix$2.eye(this.rows);
    let bb = this;
    // Note: Don't bit shift. In JS, that would truncate at 32 bits
    for (let e = scalar; e >= 1; e /= 2) {
      if ((e & 1) !== 0) {
        result = result.mmul(bb);
      }
      bb = bb.mmul(bb);
    }
    return result;
  }
  strassen2x2(other) {
    other = Matrix$2.checkMatrix(other);
    let result = new Matrix$2(2, 2);
    const a11 = this.get(0, 0);
    const b11 = other.get(0, 0);
    const a12 = this.get(0, 1);
    const b12 = other.get(0, 1);
    const a21 = this.get(1, 0);
    const b21 = other.get(1, 0);
    const a22 = this.get(1, 1);
    const b22 = other.get(1, 1);

    // Compute intermediate values.
    const m1 = (a11 + a22) * (b11 + b22);
    const m2 = (a21 + a22) * b11;
    const m3 = a11 * (b12 - b22);
    const m4 = a22 * (b21 - b11);
    const m5 = (a11 + a12) * b22;
    const m6 = (a21 - a11) * (b11 + b12);
    const m7 = (a12 - a22) * (b21 + b22);

    // Combine intermediate values into the output.
    const c00 = m1 + m4 - m5 + m7;
    const c01 = m3 + m5;
    const c10 = m2 + m4;
    const c11 = m1 - m2 + m3 + m6;
    result.set(0, 0, c00);
    result.set(0, 1, c01);
    result.set(1, 0, c10);
    result.set(1, 1, c11);
    return result;
  }
  strassen3x3(other) {
    other = Matrix$2.checkMatrix(other);
    let result = new Matrix$2(3, 3);
    const a00 = this.get(0, 0);
    const a01 = this.get(0, 1);
    const a02 = this.get(0, 2);
    const a10 = this.get(1, 0);
    const a11 = this.get(1, 1);
    const a12 = this.get(1, 2);
    const a20 = this.get(2, 0);
    const a21 = this.get(2, 1);
    const a22 = this.get(2, 2);
    const b00 = other.get(0, 0);
    const b01 = other.get(0, 1);
    const b02 = other.get(0, 2);
    const b10 = other.get(1, 0);
    const b11 = other.get(1, 1);
    const b12 = other.get(1, 2);
    const b20 = other.get(2, 0);
    const b21 = other.get(2, 1);
    const b22 = other.get(2, 2);
    const m1 = (a00 + a01 + a02 - a10 - a11 - a21 - a22) * b11;
    const m2 = (a00 - a10) * (-b01 + b11);
    const m3 = a11 * (-b00 + b01 + b10 - b11 - b12 - b20 + b22);
    const m4 = (-a00 + a10 + a11) * (b00 - b01 + b11);
    const m5 = (a10 + a11) * (-b00 + b01);
    const m6 = a00 * b00;
    const m7 = (-a00 + a20 + a21) * (b00 - b02 + b12);
    const m8 = (-a00 + a20) * (b02 - b12);
    const m9 = (a20 + a21) * (-b00 + b02);
    const m10 = (a00 + a01 + a02 - a11 - a12 - a20 - a21) * b12;
    const m11 = a21 * (-b00 + b02 + b10 - b11 - b12 - b20 + b21);
    const m12 = (-a02 + a21 + a22) * (b11 + b20 - b21);
    const m13 = (a02 - a22) * (b11 - b21);
    const m14 = a02 * b20;
    const m15 = (a21 + a22) * (-b20 + b21);
    const m16 = (-a02 + a11 + a12) * (b12 + b20 - b22);
    const m17 = (a02 - a12) * (b12 - b22);
    const m18 = (a11 + a12) * (-b20 + b22);
    const m19 = a01 * b10;
    const m20 = a12 * b21;
    const m21 = a10 * b02;
    const m22 = a20 * b01;
    const m23 = a22 * b22;
    const c00 = m6 + m14 + m19;
    const c01 = m1 + m4 + m5 + m6 + m12 + m14 + m15;
    const c02 = m6 + m7 + m9 + m10 + m14 + m16 + m18;
    const c10 = m2 + m3 + m4 + m6 + m14 + m16 + m17;
    const c11 = m2 + m4 + m5 + m6 + m20;
    const c12 = m14 + m16 + m17 + m18 + m21;
    const c20 = m6 + m7 + m8 + m11 + m12 + m13 + m14;
    const c21 = m12 + m13 + m14 + m15 + m22;
    const c22 = m6 + m7 + m8 + m9 + m23;
    result.set(0, 0, c00);
    result.set(0, 1, c01);
    result.set(0, 2, c02);
    result.set(1, 0, c10);
    result.set(1, 1, c11);
    result.set(1, 2, c12);
    result.set(2, 0, c20);
    result.set(2, 1, c21);
    result.set(2, 2, c22);
    return result;
  }
  mmulStrassen(y) {
    y = Matrix$2.checkMatrix(y);
    let x = this.clone();
    let r1 = x.rows;
    let c1 = x.columns;
    let r2 = y.rows;
    let c2 = y.columns;
    if (c1 !== r2) {
      // eslint-disable-next-line no-console
      console.warn(`Multiplying ${r1} x ${c1} and ${r2} x ${c2} matrix: dimensions do not match.`);
    }

    // Put a matrix into the top left of a matrix of zeros.
    // `rows` and `cols` are the dimensions of the output matrix.
    function embed(mat, rows, cols) {
      let r = mat.rows;
      let c = mat.columns;
      if (r === rows && c === cols) {
        return mat;
      } else {
        let resultat = AbstractMatrix.zeros(rows, cols);
        resultat = resultat.setSubMatrix(mat, 0, 0);
        return resultat;
      }
    }

    // Make sure both matrices are the same size.
    // This is exclusively for simplicity:
    // this algorithm can be implemented with matrices of different sizes.

    let r = Math.max(r1, r2);
    let c = Math.max(c1, c2);
    x = embed(x, r, c);
    y = embed(y, r, c);

    // Our recursive multiplication function.
    function blockMult(a, b, rows, cols) {
      // For small matrices, resort to naive multiplication.
      if (rows <= 512 || cols <= 512) {
        return a.mmul(b); // a is equivalent to this
      }

      // Apply dynamic padding.
      if (rows % 2 === 1 && cols % 2 === 1) {
        a = embed(a, rows + 1, cols + 1);
        b = embed(b, rows + 1, cols + 1);
      } else if (rows % 2 === 1) {
        a = embed(a, rows + 1, cols);
        b = embed(b, rows + 1, cols);
      } else if (cols % 2 === 1) {
        a = embed(a, rows, cols + 1);
        b = embed(b, rows, cols + 1);
      }
      let halfRows = parseInt(a.rows / 2, 10);
      let halfCols = parseInt(a.columns / 2, 10);
      // Subdivide input matrices.
      let a11 = a.subMatrix(0, halfRows - 1, 0, halfCols - 1);
      let b11 = b.subMatrix(0, halfRows - 1, 0, halfCols - 1);
      let a12 = a.subMatrix(0, halfRows - 1, halfCols, a.columns - 1);
      let b12 = b.subMatrix(0, halfRows - 1, halfCols, b.columns - 1);
      let a21 = a.subMatrix(halfRows, a.rows - 1, 0, halfCols - 1);
      let b21 = b.subMatrix(halfRows, b.rows - 1, 0, halfCols - 1);
      let a22 = a.subMatrix(halfRows, a.rows - 1, halfCols, a.columns - 1);
      let b22 = b.subMatrix(halfRows, b.rows - 1, halfCols, b.columns - 1);

      // Compute intermediate values.
      let m1 = blockMult(AbstractMatrix.add(a11, a22), AbstractMatrix.add(b11, b22), halfRows, halfCols);
      let m2 = blockMult(AbstractMatrix.add(a21, a22), b11, halfRows, halfCols);
      let m3 = blockMult(a11, AbstractMatrix.sub(b12, b22), halfRows, halfCols);
      let m4 = blockMult(a22, AbstractMatrix.sub(b21, b11), halfRows, halfCols);
      let m5 = blockMult(AbstractMatrix.add(a11, a12), b22, halfRows, halfCols);
      let m6 = blockMult(AbstractMatrix.sub(a21, a11), AbstractMatrix.add(b11, b12), halfRows, halfCols);
      let m7 = blockMult(AbstractMatrix.sub(a12, a22), AbstractMatrix.add(b21, b22), halfRows, halfCols);

      // Combine intermediate values into the output.
      let c11 = AbstractMatrix.add(m1, m4);
      c11.sub(m5);
      c11.add(m7);
      let c12 = AbstractMatrix.add(m3, m5);
      let c21 = AbstractMatrix.add(m2, m4);
      let c22 = AbstractMatrix.sub(m1, m2);
      c22.add(m3);
      c22.add(m6);

      // Crop output to the desired size (undo dynamic padding).
      let result = AbstractMatrix.zeros(2 * c11.rows, 2 * c11.columns);
      result = result.setSubMatrix(c11, 0, 0);
      result = result.setSubMatrix(c12, c11.rows, 0);
      result = result.setSubMatrix(c21, 0, c11.columns);
      result = result.setSubMatrix(c22, c11.rows, c11.columns);
      return result.subMatrix(0, rows - 1, 0, cols - 1);
    }
    return blockMult(x, y, r, c);
  }
  scaleRows(options = {}) {
    if (typeof options !== 'object') {
      throw new TypeError('options must be an object');
    }
    const {
      min = 0,
      max = 1
    } = options;
    if (!Number.isFinite(min)) throw new TypeError('min must be a number');
    if (!Number.isFinite(max)) throw new TypeError('max must be a number');
    if (min >= max) throw new RangeError('min must be smaller than max');
    let newMatrix = new Matrix$2(this.rows, this.columns);
    for (let i = 0; i < this.rows; i++) {
      const row = this.getRow(i);
      if (row.length > 0) {
        rescale(row, {
          min,
          max,
          output: row
        });
      }
      newMatrix.setRow(i, row);
    }
    return newMatrix;
  }
  scaleColumns(options = {}) {
    if (typeof options !== 'object') {
      throw new TypeError('options must be an object');
    }
    const {
      min = 0,
      max = 1
    } = options;
    if (!Number.isFinite(min)) throw new TypeError('min must be a number');
    if (!Number.isFinite(max)) throw new TypeError('max must be a number');
    if (min >= max) throw new RangeError('min must be smaller than max');
    let newMatrix = new Matrix$2(this.rows, this.columns);
    for (let i = 0; i < this.columns; i++) {
      const column = this.getColumn(i);
      if (column.length) {
        rescale(column, {
          min,
          max,
          output: column
        });
      }
      newMatrix.setColumn(i, column);
    }
    return newMatrix;
  }
  flipRows() {
    const middle = Math.ceil(this.columns / 2);
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < middle; j++) {
        let first = this.get(i, j);
        let last = this.get(i, this.columns - 1 - j);
        this.set(i, j, last);
        this.set(i, this.columns - 1 - j, first);
      }
    }
    return this;
  }
  flipColumns() {
    const middle = Math.ceil(this.rows / 2);
    for (let j = 0; j < this.columns; j++) {
      for (let i = 0; i < middle; i++) {
        let first = this.get(i, j);
        let last = this.get(this.rows - 1 - i, j);
        this.set(i, j, last);
        this.set(this.rows - 1 - i, j, first);
      }
    }
    return this;
  }
  kroneckerProduct(other) {
    other = Matrix$2.checkMatrix(other);
    let m = this.rows;
    let n = this.columns;
    let p = other.rows;
    let q = other.columns;
    let result = new Matrix$2(m * p, n * q);
    for (let i = 0; i < m; i++) {
      for (let j = 0; j < n; j++) {
        for (let k = 0; k < p; k++) {
          for (let l = 0; l < q; l++) {
            result.set(p * i + k, q * j + l, this.get(i, j) * other.get(k, l));
          }
        }
      }
    }
    return result;
  }
  kroneckerSum(other) {
    other = Matrix$2.checkMatrix(other);
    if (!this.isSquare() || !other.isSquare()) {
      throw new Error('Kronecker Sum needs two Square Matrices');
    }
    let m = this.rows;
    let n = other.rows;
    let AxI = this.kroneckerProduct(Matrix$2.eye(n, n));
    let IxB = Matrix$2.eye(m, m).kroneckerProduct(other);
    return AxI.add(IxB);
  }
  transpose() {
    let result = new Matrix$2(this.columns, this.rows);
    for (let i = 0; i < this.rows; i++) {
      for (let j = 0; j < this.columns; j++) {
        result.set(j, i, this.get(i, j));
      }
    }
    return result;
  }
  sortRows(compareFunction = compareNumbers) {
    for (let i = 0; i < this.rows; i++) {
      this.setRow(i, this.getRow(i).sort(compareFunction));
    }
    return this;
  }
  sortColumns(compareFunction = compareNumbers) {
    for (let i = 0; i < this.columns; i++) {
      this.setColumn(i, this.getColumn(i).sort(compareFunction));
    }
    return this;
  }
  subMatrix(startRow, endRow, startColumn, endColumn) {
    checkRange$1(this, startRow, endRow, startColumn, endColumn);
    let newMatrix = new Matrix$2(endRow - startRow + 1, endColumn - startColumn + 1);
    for (let i = startRow; i <= endRow; i++) {
      for (let j = startColumn; j <= endColumn; j++) {
        newMatrix.set(i - startRow, j - startColumn, this.get(i, j));
      }
    }
    return newMatrix;
  }
  subMatrixRow(indices, startColumn, endColumn) {
    if (startColumn === undefined) startColumn = 0;
    if (endColumn === undefined) endColumn = this.columns - 1;
    if (startColumn > endColumn || startColumn < 0 || startColumn >= this.columns || endColumn < 0 || endColumn >= this.columns) {
      throw new RangeError('Argument out of range');
    }
    let newMatrix = new Matrix$2(indices.length, endColumn - startColumn + 1);
    for (let i = 0; i < indices.length; i++) {
      for (let j = startColumn; j <= endColumn; j++) {
        if (indices[i] < 0 || indices[i] >= this.rows) {
          throw new RangeError(`Row index out of range: ${indices[i]}`);
        }
        newMatrix.set(i, j - startColumn, this.get(indices[i], j));
      }
    }
    return newMatrix;
  }
  subMatrixColumn(indices, startRow, endRow) {
    if (startRow === undefined) startRow = 0;
    if (endRow === undefined) endRow = this.rows - 1;
    if (startRow > endRow || startRow < 0 || startRow >= this.rows || endRow < 0 || endRow >= this.rows) {
      throw new RangeError('Argument out of range');
    }
    let newMatrix = new Matrix$2(endRow - startRow + 1, indices.length);
    for (let i = 0; i < indices.length; i++) {
      for (let j = startRow; j <= endRow; j++) {
        if (indices[i] < 0 || indices[i] >= this.columns) {
          throw new RangeError(`Column index out of range: ${indices[i]}`);
        }
        newMatrix.set(j - startRow, i, this.get(j, indices[i]));
      }
    }
    return newMatrix;
  }
  setSubMatrix(matrix, startRow, startColumn) {
    matrix = Matrix$2.checkMatrix(matrix);
    if (matrix.isEmpty()) {
      return this;
    }
    let endRow = startRow + matrix.rows - 1;
    let endColumn = startColumn + matrix.columns - 1;
    checkRange$1(this, startRow, endRow, startColumn, endColumn);
    for (let i = 0; i < matrix.rows; i++) {
      for (let j = 0; j < matrix.columns; j++) {
        this.set(startRow + i, startColumn + j, matrix.get(i, j));
      }
    }
    return this;
  }
  selection(rowIndices, columnIndices) {
    checkRowIndices(this, rowIndices);
    checkColumnIndices(this, columnIndices);
    let newMatrix = new Matrix$2(rowIndices.length, columnIndices.length);
    for (let i = 0; i < rowIndices.length; i++) {
      let rowIndex = rowIndices[i];
      for (let j = 0; j < columnIndices.length; j++) {
        let columnIndex = columnIndices[j];
        newMatrix.set(i, j, this.get(rowIndex, columnIndex));
      }
    }
    return newMatrix;
  }
  trace() {
    let min = Math.min(this.rows, this.columns);
    let trace = 0;
    for (let i = 0; i < min; i++) {
      trace += this.get(i, i);
    }
    return trace;
  }
  clone() {
    return this.constructor.copy(this, new Matrix$2(this.rows, this.columns));
  }

  /**
   * @template {AbstractMatrix} M
   * @param {AbstractMatrix} from
   * @param {M} to
   * @return {M}
   */
  static copy(from, to) {
    for (const [row, column, value] of from.entries()) {
      to.set(row, column, value);
    }
    return to;
  }
  sum(by) {
    switch (by) {
      case 'row':
        return sumByRow(this);
      case 'column':
        return sumByColumn(this);
      case undefined:
        return sumAll(this);
      default:
        throw new Error(`invalid option: ${by}`);
    }
  }
  product(by) {
    switch (by) {
      case 'row':
        return productByRow(this);
      case 'column':
        return productByColumn(this);
      case undefined:
        return productAll(this);
      default:
        throw new Error(`invalid option: ${by}`);
    }
  }
  mean(by) {
    const sum = this.sum(by);
    switch (by) {
      case 'row':
        {
          for (let i = 0; i < this.rows; i++) {
            sum[i] /= this.columns;
          }
          return sum;
        }
      case 'column':
        {
          for (let i = 0; i < this.columns; i++) {
            sum[i] /= this.rows;
          }
          return sum;
        }
      case undefined:
        return sum / this.size;
      default:
        throw new Error(`invalid option: ${by}`);
    }
  }
  variance(by, options = {}) {
    if (typeof by === 'object') {
      options = by;
      by = undefined;
    }
    if (typeof options !== 'object') {
      throw new TypeError('options must be an object');
    }
    const {
      unbiased = true,
      mean = this.mean(by)
    } = options;
    if (typeof unbiased !== 'boolean') {
      throw new TypeError('unbiased must be a boolean');
    }
    switch (by) {
      case 'row':
        {
          if (!isAnyArray.isAnyArray(mean)) {
            throw new TypeError('mean must be an array');
          }
          return varianceByRow(this, unbiased, mean);
        }
      case 'column':
        {
          if (!isAnyArray.isAnyArray(mean)) {
            throw new TypeError('mean must be an array');
          }
          return varianceByColumn(this, unbiased, mean);
        }
      case undefined:
        {
          if (typeof mean !== 'number') {
            throw new TypeError('mean must be a number');
          }
          return varianceAll(this, unbiased, mean);
        }
      default:
        throw new Error(`invalid option: ${by}`);
    }
  }
  standardDeviation(by, options) {
    if (typeof by === 'object') {
      options = by;
      by = undefined;
    }
    const variance = this.variance(by, options);
    if (by === undefined) {
      return Math.sqrt(variance);
    } else {
      for (let i = 0; i < variance.length; i++) {
        variance[i] = Math.sqrt(variance[i]);
      }
      return variance;
    }
  }
  center(by, options = {}) {
    if (typeof by === 'object') {
      options = by;
      by = undefined;
    }
    if (typeof options !== 'object') {
      throw new TypeError('options must be an object');
    }
    const {
      center = this.mean(by)
    } = options;
    switch (by) {
      case 'row':
        {
          if (!isAnyArray.isAnyArray(center)) {
            throw new TypeError('center must be an array');
          }
          centerByRow(this, center);
          return this;
        }
      case 'column':
        {
          if (!isAnyArray.isAnyArray(center)) {
            throw new TypeError('center must be an array');
          }
          centerByColumn(this, center);
          return this;
        }
      case undefined:
        {
          if (typeof center !== 'number') {
            throw new TypeError('center must be a number');
          }
          centerAll(this, center);
          return this;
        }
      default:
        throw new Error(`invalid option: ${by}`);
    }
  }
  scale(by, options = {}) {
    if (typeof by === 'object') {
      options = by;
      by = undefined;
    }
    if (typeof options !== 'object') {
      throw new TypeError('options must be an object');
    }
    let scale = options.scale;
    switch (by) {
      case 'row':
        {
          if (scale === undefined) {
            scale = getScaleByRow(this);
          } else if (!isAnyArray.isAnyArray(scale)) {
            throw new TypeError('scale must be an array');
          }
          scaleByRow(this, scale);
          return this;
        }
      case 'column':
        {
          if (scale === undefined) {
            scale = getScaleByColumn(this);
          } else if (!isAnyArray.isAnyArray(scale)) {
            throw new TypeError('scale must be an array');
          }
          scaleByColumn(this, scale);
          return this;
        }
      case undefined:
        {
          if (scale === undefined) {
            scale = getScaleAll(this);
          } else if (typeof scale !== 'number') {
            throw new TypeError('scale must be a number');
          }
          scaleAll(this, scale);
          return this;
        }
      default:
        throw new Error(`invalid option: ${by}`);
    }
  }
  toString(options) {
    return inspectMatrixWithOptions(this, options);
  }
  [Symbol.iterator]() {
    return this.entries();
  }

  /**
   * iterator from left to right, from top to bottom
   * yield [row, column, value]
   * @returns {Generator<[number, number, number], void, void>}
   */
  *entries() {
    for (let row = 0; row < this.rows; row++) {
      for (let col = 0; col < this.columns; col++) {
        yield [row, col, this.get(row, col)];
      }
    }
  }

  /**
   * iterator from left to right, from top to bottom
   * yield value
   * @returns {Generator<number, void, void>}
   */
  *values() {
    for (let row = 0; row < this.rows; row++) {
      for (let col = 0; col < this.columns; col++) {
        yield this.get(row, col);
      }
    }
  }
}
AbstractMatrix.prototype.klass = 'Matrix';
if (typeof Symbol !== 'undefined') {
  AbstractMatrix.prototype[Symbol.for('nodejs.util.inspect.custom')] = inspectMatrix;
}
function compareNumbers(a, b) {
  return a - b;
}
function isArrayOfNumbers(array) {
  return array.every(element => {
    return typeof element === 'number';
  });
}

// Synonyms
AbstractMatrix.random = AbstractMatrix.rand;
AbstractMatrix.randomInt = AbstractMatrix.randInt;
AbstractMatrix.diagonal = AbstractMatrix.diag;
AbstractMatrix.prototype.diagonal = AbstractMatrix.prototype.diag;
AbstractMatrix.identity = AbstractMatrix.eye;
AbstractMatrix.prototype.negate = AbstractMatrix.prototype.neg;
AbstractMatrix.prototype.tensorProduct = AbstractMatrix.prototype.kroneckerProduct;
let Matrix$2 = class Matrix extends AbstractMatrix {
  /**
   * @type {Float64Array[]}
   */
  data;

  /**
   * Init an empty matrix
   * @param {number} nRows
   * @param {number} nColumns
   */
  #initData(nRows, nColumns) {
    this.data = [];
    if (Number.isInteger(nColumns) && nColumns >= 0) {
      for (let i = 0; i < nRows; i++) {
        this.data.push(new Float64Array(nColumns));
      }
    } else {
      throw new TypeError('nColumns must be a positive integer');
    }
    this.rows = nRows;
    this.columns = nColumns;
  }
  constructor(nRows, nColumns) {
    super();
    if (Matrix.isMatrix(nRows)) {
      this.#initData(nRows.rows, nRows.columns);
      Matrix.copy(nRows, this);
    } else if (Number.isInteger(nRows) && nRows >= 0) {
      this.#initData(nRows, nColumns);
    } else if (isAnyArray.isAnyArray(nRows)) {
      // Copy the values from the 2D array
      const arrayData = nRows;
      nRows = arrayData.length;
      nColumns = nRows ? arrayData[0].length : 0;
      if (typeof nColumns !== 'number') {
        throw new TypeError('Data must be a 2D array with at least one element');
      }
      this.data = [];
      for (let i = 0; i < nRows; i++) {
        if (arrayData[i].length !== nColumns) {
          throw new RangeError('Inconsistent array dimensions');
        }
        if (!isArrayOfNumbers(arrayData[i])) {
          throw new TypeError('Input data contains non-numeric values');
        }
        this.data.push(Float64Array.from(arrayData[i]));
      }
      this.rows = nRows;
      this.columns = nColumns;
    } else {
      throw new TypeError('First argument must be a positive number or an array');
    }
  }
  set(rowIndex, columnIndex, value) {
    this.data[rowIndex][columnIndex] = value;
    return this;
  }
  get(rowIndex, columnIndex) {
    return this.data[rowIndex][columnIndex];
  }
  removeRow(index) {
    checkRowIndex(this, index);
    this.data.splice(index, 1);
    this.rows -= 1;
    return this;
  }
  addRow(index, array) {
    if (array === undefined) {
      array = index;
      index = this.rows;
    }
    checkRowIndex(this, index, true);
    array = Float64Array.from(checkRowVector(this, array));
    this.data.splice(index, 0, array);
    this.rows += 1;
    return this;
  }
  removeColumn(index) {
    checkColumnIndex(this, index);
    for (let i = 0; i < this.rows; i++) {
      const newRow = new Float64Array(this.columns - 1);
      for (let j = 0; j < index; j++) {
        newRow[j] = this.data[i][j];
      }
      for (let j = index + 1; j < this.columns; j++) {
        newRow[j - 1] = this.data[i][j];
      }
      this.data[i] = newRow;
    }
    this.columns -= 1;
    return this;
  }
  addColumn(index, array) {
    if (typeof array === 'undefined') {
      array = index;
      index = this.columns;
    }
    checkColumnIndex(this, index, true);
    array = checkColumnVector(this, array);
    for (let i = 0; i < this.rows; i++) {
      const newRow = new Float64Array(this.columns + 1);
      let j = 0;
      for (; j < index; j++) {
        newRow[j] = this.data[i][j];
      }
      newRow[j++] = array[i];
      for (; j < this.columns + 1; j++) {
        newRow[j] = this.data[i][j - 1];
      }
      this.data[i] = newRow;
    }
    this.columns += 1;
    return this;
  }
};
installMathOperations(AbstractMatrix, Matrix$2);

/**
 * @typedef {0 | 1 | number | boolean} Mask
 */

class SymmetricMatrix extends AbstractMatrix {
  /** @type {Matrix} */
  #matrix;
  get size() {
    return this.#matrix.size;
  }
  get rows() {
    return this.#matrix.rows;
  }
  get columns() {
    return this.#matrix.columns;
  }
  get diagonalSize() {
    return this.rows;
  }

  /**
   * not the same as matrix.isSymmetric()
   * Here is to check if it's instanceof SymmetricMatrix without bundling issues
   *
   * @param value
   * @returns {boolean}
   */
  static isSymmetricMatrix(value) {
    return Matrix$2.isMatrix(value) && value.klassType === 'SymmetricMatrix';
  }

  /**
   * @param diagonalSize
   * @return {SymmetricMatrix}
   */
  static zeros(diagonalSize) {
    return new this(diagonalSize);
  }

  /**
   * @param diagonalSize
   * @return {SymmetricMatrix}
   */
  static ones(diagonalSize) {
    return new this(diagonalSize).fill(1);
  }

  /**
   * @param {number | AbstractMatrix | ArrayLike<ArrayLike<number>>} diagonalSize
   * @return {this}
   */
  constructor(diagonalSize) {
    super();
    if (Matrix$2.isMatrix(diagonalSize)) {
      if (!diagonalSize.isSymmetric()) {
        throw new TypeError('not symmetric data');
      }
      this.#matrix = Matrix$2.copy(diagonalSize, new Matrix$2(diagonalSize.rows, diagonalSize.rows));
    } else if (Number.isInteger(diagonalSize) && diagonalSize >= 0) {
      this.#matrix = new Matrix$2(diagonalSize, diagonalSize);
    } else {
      this.#matrix = new Matrix$2(diagonalSize);
      if (!this.isSymmetric()) {
        throw new TypeError('not symmetric data');
      }
    }
  }
  clone() {
    const matrix = new SymmetricMatrix(this.diagonalSize);
    for (const [row, col, value] of this.upperRightEntries()) {
      matrix.set(row, col, value);
    }
    return matrix;
  }
  toMatrix() {
    return new Matrix$2(this);
  }
  get(rowIndex, columnIndex) {
    return this.#matrix.get(rowIndex, columnIndex);
  }
  set(rowIndex, columnIndex, value) {
    // symmetric set
    this.#matrix.set(rowIndex, columnIndex, value);
    this.#matrix.set(columnIndex, rowIndex, value);
    return this;
  }
  removeCross(index) {
    // symmetric remove side
    this.#matrix.removeRow(index);
    this.#matrix.removeColumn(index);
    return this;
  }
  addCross(index, array) {
    if (array === undefined) {
      array = index;
      index = this.diagonalSize;
    }
    const row = array.slice();
    row.splice(index, 1);
    this.#matrix.addRow(index, row);
    this.#matrix.addColumn(index, array);
    return this;
  }

  /**
   * @param {Mask[]} mask
   */
  applyMask(mask) {
    if (mask.length !== this.diagonalSize) {
      throw new RangeError('Mask size do not match with matrix size');
    }

    // prepare sides to remove from matrix from mask
    /** @type {number[]} */
    const sidesToRemove = [];
    for (const [index, passthroughs] of mask.entries()) {
      if (passthroughs) continue;
      sidesToRemove.push(index);
    }
    // to remove from highest to lowest for no mutation shifting
    sidesToRemove.reverse();

    // remove sides
    for (const sideIndex of sidesToRemove) {
      this.removeCross(sideIndex);
    }
    return this;
  }

  /**
   * Compact format upper-right corner of matrix
   * iterate from left to right, from top to bottom.
   *
   * ```
   *   A B C D
   * A 1 2 3 4
   * B 2 5 6 7
   * C 3 6 8 9
   * D 4 7 9 10
   * ```
   *
   * will return compact 1D array `[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]`
   *
   * length is S(i=0, n=sideSize) => 10 for a 4 sideSized matrix
   *
   * @returns {number[]}
   */
  toCompact() {
    const {
      diagonalSize
    } = this;

    /** @type {number[]} */
    const compact = new Array(diagonalSize * (diagonalSize + 1) / 2);
    for (let col = 0, row = 0, index = 0; index < compact.length; index++) {
      compact[index] = this.get(row, col);
      if (++col >= diagonalSize) col = ++row;
    }
    return compact;
  }

  /**
   * @param {number[]} compact
   * @return {SymmetricMatrix}
   */
  static fromCompact(compact) {
    const compactSize = compact.length;
    // compactSize = (sideSize * (sideSize + 1)) / 2
    // https://mathsolver.microsoft.com/fr/solve-problem/y%20%3D%20%20x%20%60cdot%20%20%20%60frac%7B%20%20%60left(%20x%2B1%20%20%60right)%20%20%20%20%7D%7B%202%20%20%7D
    // sideSize = (Sqrt(8 × compactSize + 1) - 1) / 2
    const diagonalSize = (Math.sqrt(8 * compactSize + 1) - 1) / 2;
    if (!Number.isInteger(diagonalSize)) {
      throw new TypeError(`This array is not a compact representation of a Symmetric Matrix, ${JSON.stringify(compact)}`);
    }
    const matrix = new SymmetricMatrix(diagonalSize);
    for (let col = 0, row = 0, index = 0; index < compactSize; index++) {
      matrix.set(col, row, compact[index]);
      if (++col >= diagonalSize) col = ++row;
    }
    return matrix;
  }

  /**
   * half iterator upper-right-corner from left to right, from top to bottom
   * yield [row, column, value]
   *
   * @returns {Generator<[number, number, number], void, void>}
   */
  *upperRightEntries() {
    for (let row = 0, col = 0; row < this.diagonalSize; void 0) {
      const value = this.get(row, col);
      yield [row, col, value];

      // at the end of row, move cursor to next row at diagonal position
      if (++col >= this.diagonalSize) col = ++row;
    }
  }

  /**
   * half iterator upper-right-corner from left to right, from top to bottom
   * yield value
   *
   * @returns {Generator<[number, number, number], void, void>}
   */
  *upperRightValues() {
    for (let row = 0, col = 0; row < this.diagonalSize; void 0) {
      const value = this.get(row, col);
      yield value;

      // at the end of row, move cursor to next row at diagonal position
      if (++col >= this.diagonalSize) col = ++row;
    }
  }
}
SymmetricMatrix.prototype.klassType = 'SymmetricMatrix';
class DistanceMatrix extends SymmetricMatrix {
  /**
   * not the same as matrix.isSymmetric()
   * Here is to check if it's instanceof SymmetricMatrix without bundling issues
   *
   * @param value
   * @returns {boolean}
   */
  static isDistanceMatrix(value) {
    return SymmetricMatrix.isSymmetricMatrix(value) && value.klassSubType === 'DistanceMatrix';
  }
  constructor(sideSize) {
    super(sideSize);
    if (!this.isDistance()) {
      throw new TypeError('Provided arguments do no produce a distance matrix');
    }
  }
  set(rowIndex, columnIndex, value) {
    // distance matrix diagonal is 0
    if (rowIndex === columnIndex) value = 0;
    return super.set(rowIndex, columnIndex, value);
  }
  addCross(index, array) {
    if (array === undefined) {
      array = index;
      index = this.diagonalSize;
    }

    // ensure distance
    array = array.slice();
    array[index] = 0;
    return super.addCross(index, array);
  }
  toSymmetricMatrix() {
    return new SymmetricMatrix(this);
  }
  clone() {
    const matrix = new DistanceMatrix(this.diagonalSize);
    for (const [row, col, value] of this.upperRightEntries()) {
      if (row === col) continue;
      matrix.set(row, col, value);
    }
    return matrix;
  }

  /**
   * Compact format upper-right corner of matrix
   * no diagonal (only zeros)
   * iterable from left to right, from top to bottom.
   *
   * ```
   *   A B C D
   * A 0 1 2 3
   * B 1 0 4 5
   * C 2 4 0 6
   * D 3 5 6 0
   * ```
   *
   * will return compact 1D array `[1, 2, 3, 4, 5, 6]`
   *
   * length is S(i=0, n=sideSize-1) => 6 for a 4 side sized matrix
   *
   * @returns {number[]}
   */
  toCompact() {
    const {
      diagonalSize
    } = this;
    const compactLength = (diagonalSize - 1) * diagonalSize / 2;

    /** @type {number[]} */
    const compact = new Array(compactLength);
    for (let col = 1, row = 0, index = 0; index < compact.length; index++) {
      compact[index] = this.get(row, col);
      if (++col >= diagonalSize) col = ++row + 1;
    }
    return compact;
  }

  /**
   * @param {number[]} compact
   */
  static fromCompact(compact) {
    const compactSize = compact.length;
    if (compactSize === 0) {
      return new this(0);
    }

    // compactSize in Natural integer range ]0;∞]
    // compactSize = (sideSize * (sideSize - 1)) / 2
    // sideSize = (Sqrt(8 × compactSize + 1) + 1) / 2
    const diagonalSize = (Math.sqrt(8 * compactSize + 1) + 1) / 2;
    if (!Number.isInteger(diagonalSize)) {
      throw new TypeError(`This array is not a compact representation of a DistanceMatrix, ${JSON.stringify(compact)}`);
    }
    const matrix = new this(diagonalSize);
    for (let col = 1, row = 0, index = 0; index < compactSize; index++) {
      matrix.set(col, row, compact[index]);
      if (++col >= diagonalSize) col = ++row + 1;
    }
    return matrix;
  }
}
DistanceMatrix.prototype.klassSubType = 'DistanceMatrix';
class BaseView extends AbstractMatrix {
  constructor(matrix, rows, columns) {
    super();
    this.matrix = matrix;
    this.rows = rows;
    this.columns = columns;
  }
}
class MatrixColumnView extends BaseView {
  constructor(matrix, column) {
    checkColumnIndex(matrix, column);
    super(matrix, matrix.rows, 1);
    this.column = column;
  }
  set(rowIndex, columnIndex, value) {
    this.matrix.set(rowIndex, this.column, value);
    return this;
  }
  get(rowIndex) {
    return this.matrix.get(rowIndex, this.column);
  }
}
class MatrixColumnSelectionView extends BaseView {
  constructor(matrix, columnIndices) {
    checkColumnIndices(matrix, columnIndices);
    super(matrix, matrix.rows, columnIndices.length);
    this.columnIndices = columnIndices;
  }
  set(rowIndex, columnIndex, value) {
    this.matrix.set(rowIndex, this.columnIndices[columnIndex], value);
    return this;
  }
  get(rowIndex, columnIndex) {
    return this.matrix.get(rowIndex, this.columnIndices[columnIndex]);
  }
}
class MatrixFlipColumnView extends BaseView {
  constructor(matrix) {
    super(matrix, matrix.rows, matrix.columns);
  }
  set(rowIndex, columnIndex, value) {
    this.matrix.set(rowIndex, this.columns - columnIndex - 1, value);
    return this;
  }
  get(rowIndex, columnIndex) {
    return this.matrix.get(rowIndex, this.columns - columnIndex - 1);
  }
}
class MatrixFlipRowView extends BaseView {
  constructor(matrix) {
    super(matrix, matrix.rows, matrix.columns);
  }
  set(rowIndex, columnIndex, value) {
    this.matrix.set(this.rows - rowIndex - 1, columnIndex, value);
    return this;
  }
  get(rowIndex, columnIndex) {
    return this.matrix.get(this.rows - rowIndex - 1, columnIndex);
  }
}
class MatrixRowView extends BaseView {
  constructor(matrix, row) {
    checkRowIndex(matrix, row);
    super(matrix, 1, matrix.columns);
    this.row = row;
  }
  set(rowIndex, columnIndex, value) {
    this.matrix.set(this.row, columnIndex, value);
    return this;
  }
  get(rowIndex, columnIndex) {
    return this.matrix.get(this.row, columnIndex);
  }
}
class MatrixRowSelectionView extends BaseView {
  constructor(matrix, rowIndices) {
    checkRowIndices(matrix, rowIndices);
    super(matrix, rowIndices.length, matrix.columns);
    this.rowIndices = rowIndices;
  }
  set(rowIndex, columnIndex, value) {
    this.matrix.set(this.rowIndices[rowIndex], columnIndex, value);
    return this;
  }
  get(rowIndex, columnIndex) {
    return this.matrix.get(this.rowIndices[rowIndex], columnIndex);
  }
}
class MatrixSelectionView extends BaseView {
  constructor(matrix, rowIndices, columnIndices) {
    checkRowIndices(matrix, rowIndices);
    checkColumnIndices(matrix, columnIndices);
    super(matrix, rowIndices.length, columnIndices.length);
    this.rowIndices = rowIndices;
    this.columnIndices = columnIndices;
  }
  set(rowIndex, columnIndex, value) {
    this.matrix.set(this.rowIndices[rowIndex], this.columnIndices[columnIndex], value);
    return this;
  }
  get(rowIndex, columnIndex) {
    return this.matrix.get(this.rowIndices[rowIndex], this.columnIndices[columnIndex]);
  }
}
class MatrixSubView extends BaseView {
  constructor(matrix, startRow, endRow, startColumn, endColumn) {
    checkRange$1(matrix, startRow, endRow, startColumn, endColumn);
    super(matrix, endRow - startRow + 1, endColumn - startColumn + 1);
    this.startRow = startRow;
    this.startColumn = startColumn;
  }
  set(rowIndex, columnIndex, value) {
    this.matrix.set(this.startRow + rowIndex, this.startColumn + columnIndex, value);
    return this;
  }
  get(rowIndex, columnIndex) {
    return this.matrix.get(this.startRow + rowIndex, this.startColumn + columnIndex);
  }
}
class MatrixTransposeView extends BaseView {
  constructor(matrix) {
    super(matrix, matrix.columns, matrix.rows);
  }
  set(rowIndex, columnIndex, value) {
    this.matrix.set(columnIndex, rowIndex, value);
    return this;
  }
  get(rowIndex, columnIndex) {
    return this.matrix.get(columnIndex, rowIndex);
  }
}
let WrapperMatrix1D$1 = class WrapperMatrix1D extends AbstractMatrix {
  constructor(data, options = {}) {
    const {
      rows = 1
    } = options;
    if (data.length % rows !== 0) {
      throw new Error('the data length is not divisible by the number of rows');
    }
    super();
    this.rows = rows;
    this.columns = data.length / rows;
    this.data = data;
  }
  set(rowIndex, columnIndex, value) {
    let index = this._calculateIndex(rowIndex, columnIndex);
    this.data[index] = value;
    return this;
  }
  get(rowIndex, columnIndex) {
    let index = this._calculateIndex(rowIndex, columnIndex);
    return this.data[index];
  }
  _calculateIndex(row, column) {
    return row * this.columns + column;
  }
};
class WrapperMatrix2D extends AbstractMatrix {
  constructor(data) {
    super();
    this.data = data;
    this.rows = data.length;
    this.columns = data[0].length;
  }
  set(rowIndex, columnIndex, value) {
    this.data[rowIndex][columnIndex] = value;
    return this;
  }
  get(rowIndex, columnIndex) {
    return this.data[rowIndex][columnIndex];
  }
}
function wrap(array, options) {
  if (isAnyArray.isAnyArray(array)) {
    if (array[0] && isAnyArray.isAnyArray(array[0])) {
      return new WrapperMatrix2D(array);
    } else {
      return new WrapperMatrix1D$1(array, options);
    }
  } else {
    throw new Error('the argument is not an array');
  }
}
class LuDecomposition {
  constructor(matrix) {
    matrix = WrapperMatrix2D.checkMatrix(matrix);
    let lu = matrix.clone();
    let rows = lu.rows;
    let columns = lu.columns;
    let pivotVector = new Float64Array(rows);
    let pivotSign = 1;
    let i, j, k, p, s, t, v;
    let LUcolj, kmax;
    for (i = 0; i < rows; i++) {
      pivotVector[i] = i;
    }
    LUcolj = new Float64Array(rows);
    for (j = 0; j < columns; j++) {
      for (i = 0; i < rows; i++) {
        LUcolj[i] = lu.get(i, j);
      }
      for (i = 0; i < rows; i++) {
        kmax = Math.min(i, j);
        s = 0;
        for (k = 0; k < kmax; k++) {
          s += lu.get(i, k) * LUcolj[k];
        }
        LUcolj[i] -= s;
        lu.set(i, j, LUcolj[i]);
      }
      p = j;
      for (i = j + 1; i < rows; i++) {
        if (Math.abs(LUcolj[i]) > Math.abs(LUcolj[p])) {
          p = i;
        }
      }
      if (p !== j) {
        for (k = 0; k < columns; k++) {
          t = lu.get(p, k);
          lu.set(p, k, lu.get(j, k));
          lu.set(j, k, t);
        }
        v = pivotVector[p];
        pivotVector[p] = pivotVector[j];
        pivotVector[j] = v;
        pivotSign = -pivotSign;
      }
      if (j < rows && lu.get(j, j) !== 0) {
        for (i = j + 1; i < rows; i++) {
          lu.set(i, j, lu.get(i, j) / lu.get(j, j));
        }
      }
    }
    this.LU = lu;
    this.pivotVector = pivotVector;
    this.pivotSign = pivotSign;
  }
  isSingular() {
    let data = this.LU;
    let col = data.columns;
    for (let j = 0; j < col; j++) {
      if (data.get(j, j) === 0) {
        return true;
      }
    }
    return false;
  }
  solve(value) {
    value = Matrix$2.checkMatrix(value);
    let lu = this.LU;
    let rows = lu.rows;
    if (rows !== value.rows) {
      throw new Error('Invalid matrix dimensions');
    }
    if (this.isSingular()) {
      throw new Error('LU matrix is singular');
    }
    let count = value.columns;
    let X = value.subMatrixRow(this.pivotVector, 0, count - 1);
    let columns = lu.columns;
    let i, j, k;
    for (k = 0; k < columns; k++) {
      for (i = k + 1; i < columns; i++) {
        for (j = 0; j < count; j++) {
          X.set(i, j, X.get(i, j) - X.get(k, j) * lu.get(i, k));
        }
      }
    }
    for (k = columns - 1; k >= 0; k--) {
      for (j = 0; j < count; j++) {
        X.set(k, j, X.get(k, j) / lu.get(k, k));
      }
      for (i = 0; i < k; i++) {
        for (j = 0; j < count; j++) {
          X.set(i, j, X.get(i, j) - X.get(k, j) * lu.get(i, k));
        }
      }
    }
    return X;
  }
  get determinant() {
    let data = this.LU;
    if (!data.isSquare()) {
      throw new Error('Matrix must be square');
    }
    let determinant = this.pivotSign;
    let col = data.columns;
    for (let j = 0; j < col; j++) {
      determinant *= data.get(j, j);
    }
    return determinant;
  }
  get lowerTriangularMatrix() {
    let data = this.LU;
    let rows = data.rows;
    let columns = data.columns;
    let X = new Matrix$2(rows, columns);
    for (let i = 0; i < rows; i++) {
      for (let j = 0; j < columns; j++) {
        if (i > j) {
          X.set(i, j, data.get(i, j));
        } else if (i === j) {
          X.set(i, j, 1);
        } else {
          X.set(i, j, 0);
        }
      }
    }
    return X;
  }
  get upperTriangularMatrix() {
    let data = this.LU;
    let rows = data.rows;
    let columns = data.columns;
    let X = new Matrix$2(rows, columns);
    for (let i = 0; i < rows; i++) {
      for (let j = 0; j < columns; j++) {
        if (i <= j) {
          X.set(i, j, data.get(i, j));
        } else {
          X.set(i, j, 0);
        }
      }
    }
    return X;
  }
  get pivotPermutationVector() {
    return Array.from(this.pivotVector);
  }
}
function hypotenuse$1(a, b) {
  let r = 0;
  if (Math.abs(a) > Math.abs(b)) {
    r = b / a;
    return Math.abs(a) * Math.sqrt(1 + r * r);
  }
  if (b !== 0) {
    r = a / b;
    return Math.abs(b) * Math.sqrt(1 + r * r);
  }
  return 0;
}
class QrDecomposition {
  constructor(value) {
    value = WrapperMatrix2D.checkMatrix(value);
    let qr = value.clone();
    let m = value.rows;
    let n = value.columns;
    let rdiag = new Float64Array(n);
    let i, j, k, s;
    for (k = 0; k < n; k++) {
      let nrm = 0;
      for (i = k; i < m; i++) {
        nrm = hypotenuse$1(nrm, qr.get(i, k));
      }
      if (nrm !== 0) {
        if (qr.get(k, k) < 0) {
          nrm = -nrm;
        }
        for (i = k; i < m; i++) {
          qr.set(i, k, qr.get(i, k) / nrm);
        }
        qr.set(k, k, qr.get(k, k) + 1);
        for (j = k + 1; j < n; j++) {
          s = 0;
          for (i = k; i < m; i++) {
            s += qr.get(i, k) * qr.get(i, j);
          }
          s = -s / qr.get(k, k);
          for (i = k; i < m; i++) {
            qr.set(i, j, qr.get(i, j) + s * qr.get(i, k));
          }
        }
      }
      rdiag[k] = -nrm;
    }
    this.QR = qr;
    this.Rdiag = rdiag;
  }
  solve(value) {
    value = Matrix$2.checkMatrix(value);
    let qr = this.QR;
    let m = qr.rows;
    if (value.rows !== m) {
      throw new Error('Matrix row dimensions must agree');
    }
    if (!this.isFullRank()) {
      throw new Error('Matrix is rank deficient');
    }
    let count = value.columns;
    let X = value.clone();
    let n = qr.columns;
    let i, j, k, s;
    for (k = 0; k < n; k++) {
      for (j = 0; j < count; j++) {
        s = 0;
        for (i = k; i < m; i++) {
          s += qr.get(i, k) * X.get(i, j);
        }
        s = -s / qr.get(k, k);
        for (i = k; i < m; i++) {
          X.set(i, j, X.get(i, j) + s * qr.get(i, k));
        }
      }
    }
    for (k = n - 1; k >= 0; k--) {
      for (j = 0; j < count; j++) {
        X.set(k, j, X.get(k, j) / this.Rdiag[k]);
      }
      for (i = 0; i < k; i++) {
        for (j = 0; j < count; j++) {
          X.set(i, j, X.get(i, j) - X.get(k, j) * qr.get(i, k));
        }
      }
    }
    return X.subMatrix(0, n - 1, 0, count - 1);
  }
  isFullRank() {
    let columns = this.QR.columns;
    for (let i = 0; i < columns; i++) {
      if (this.Rdiag[i] === 0) {
        return false;
      }
    }
    return true;
  }
  get upperTriangularMatrix() {
    let qr = this.QR;
    let n = qr.columns;
    let X = new Matrix$2(n, n);
    let i, j;
    for (i = 0; i < n; i++) {
      for (j = 0; j < n; j++) {
        if (i < j) {
          X.set(i, j, qr.get(i, j));
        } else if (i === j) {
          X.set(i, j, this.Rdiag[i]);
        } else {
          X.set(i, j, 0);
        }
      }
    }
    return X;
  }
  get orthogonalMatrix() {
    let qr = this.QR;
    let rows = qr.rows;
    let columns = qr.columns;
    let X = new Matrix$2(rows, columns);
    let i, j, k, s;
    for (k = columns - 1; k >= 0; k--) {
      for (i = 0; i < rows; i++) {
        X.set(i, k, 0);
      }
      X.set(k, k, 1);
      for (j = k; j < columns; j++) {
        if (qr.get(k, k) !== 0) {
          s = 0;
          for (i = k; i < rows; i++) {
            s += qr.get(i, k) * X.get(i, j);
          }
          s = -s / qr.get(k, k);
          for (i = k; i < rows; i++) {
            X.set(i, j, X.get(i, j) + s * qr.get(i, k));
          }
        }
      }
    }
    return X;
  }
}
let SingularValueDecomposition$1 = class SingularValueDecomposition {
  constructor(value, options = {}) {
    value = WrapperMatrix2D.checkMatrix(value);
    if (value.isEmpty()) {
      throw new Error('Matrix must be non-empty');
    }
    let m = value.rows;
    let n = value.columns;
    const {
      computeLeftSingularVectors = true,
      computeRightSingularVectors = true,
      autoTranspose = false
    } = options;
    let wantu = Boolean(computeLeftSingularVectors);
    let wantv = Boolean(computeRightSingularVectors);
    let swapped = false;
    let a;
    if (m < n) {
      if (!autoTranspose) {
        a = value.clone();
        // eslint-disable-next-line no-console
        console.warn('Computing SVD on a matrix with more columns than rows. Consider enabling autoTranspose');
      } else {
        a = value.transpose();
        m = a.rows;
        n = a.columns;
        swapped = true;
        let aux = wantu;
        wantu = wantv;
        wantv = aux;
      }
    } else {
      a = value.clone();
    }
    let nu = Math.min(m, n);
    let ni = Math.min(m + 1, n);
    let s = new Float64Array(ni);
    let U = new Matrix$2(m, nu);
    let V = new Matrix$2(n, n);
    let e = new Float64Array(n);
    let work = new Float64Array(m);
    let si = new Float64Array(ni);
    for (let i = 0; i < ni; i++) si[i] = i;
    let nct = Math.min(m - 1, n);
    let nrt = Math.max(0, Math.min(n - 2, m));
    let mrc = Math.max(nct, nrt);
    for (let k = 0; k < mrc; k++) {
      if (k < nct) {
        s[k] = 0;
        for (let i = k; i < m; i++) {
          s[k] = hypotenuse$1(s[k], a.get(i, k));
        }
        if (s[k] !== 0) {
          if (a.get(k, k) < 0) {
            s[k] = -s[k];
          }
          for (let i = k; i < m; i++) {
            a.set(i, k, a.get(i, k) / s[k]);
          }
          a.set(k, k, a.get(k, k) + 1);
        }
        s[k] = -s[k];
      }
      for (let j = k + 1; j < n; j++) {
        if (k < nct && s[k] !== 0) {
          let t = 0;
          for (let i = k; i < m; i++) {
            t += a.get(i, k) * a.get(i, j);
          }
          t = -t / a.get(k, k);
          for (let i = k; i < m; i++) {
            a.set(i, j, a.get(i, j) + t * a.get(i, k));
          }
        }
        e[j] = a.get(k, j);
      }
      if (wantu && k < nct) {
        for (let i = k; i < m; i++) {
          U.set(i, k, a.get(i, k));
        }
      }
      if (k < nrt) {
        e[k] = 0;
        for (let i = k + 1; i < n; i++) {
          e[k] = hypotenuse$1(e[k], e[i]);
        }
        if (e[k] !== 0) {
          if (e[k + 1] < 0) {
            e[k] = 0 - e[k];
          }
          for (let i = k + 1; i < n; i++) {
            e[i] /= e[k];
          }
          e[k + 1] += 1;
        }
        e[k] = -e[k];
        if (k + 1 < m && e[k] !== 0) {
          for (let i = k + 1; i < m; i++) {
            work[i] = 0;
          }
          for (let i = k + 1; i < m; i++) {
            for (let j = k + 1; j < n; j++) {
              work[i] += e[j] * a.get(i, j);
            }
          }
          for (let j = k + 1; j < n; j++) {
            let t = -e[j] / e[k + 1];
            for (let i = k + 1; i < m; i++) {
              a.set(i, j, a.get(i, j) + t * work[i]);
            }
          }
        }
        if (wantv) {
          for (let i = k + 1; i < n; i++) {
            V.set(i, k, e[i]);
          }
        }
      }
    }
    let p = Math.min(n, m + 1);
    if (nct < n) {
      s[nct] = a.get(nct, nct);
    }
    if (m < p) {
      s[p - 1] = 0;
    }
    if (nrt + 1 < p) {
      e[nrt] = a.get(nrt, p - 1);
    }
    e[p - 1] = 0;
    if (wantu) {
      for (let j = nct; j < nu; j++) {
        for (let i = 0; i < m; i++) {
          U.set(i, j, 0);
        }
        U.set(j, j, 1);
      }
      for (let k = nct - 1; k >= 0; k--) {
        if (s[k] !== 0) {
          for (let j = k + 1; j < nu; j++) {
            let t = 0;
            for (let i = k; i < m; i++) {
              t += U.get(i, k) * U.get(i, j);
            }
            t = -t / U.get(k, k);
            for (let i = k; i < m; i++) {
              U.set(i, j, U.get(i, j) + t * U.get(i, k));
            }
          }
          for (let i = k; i < m; i++) {
            U.set(i, k, -U.get(i, k));
          }
          U.set(k, k, 1 + U.get(k, k));
          for (let i = 0; i < k - 1; i++) {
            U.set(i, k, 0);
          }
        } else {
          for (let i = 0; i < m; i++) {
            U.set(i, k, 0);
          }
          U.set(k, k, 1);
        }
      }
    }
    if (wantv) {
      for (let k = n - 1; k >= 0; k--) {
        if (k < nrt && e[k] !== 0) {
          for (let j = k + 1; j < n; j++) {
            let t = 0;
            for (let i = k + 1; i < n; i++) {
              t += V.get(i, k) * V.get(i, j);
            }
            t = -t / V.get(k + 1, k);
            for (let i = k + 1; i < n; i++) {
              V.set(i, j, V.get(i, j) + t * V.get(i, k));
            }
          }
        }
        for (let i = 0; i < n; i++) {
          V.set(i, k, 0);
        }
        V.set(k, k, 1);
      }
    }
    let pp = p - 1;
    let eps = Number.EPSILON;
    while (p > 0) {
      let k, kase;
      for (k = p - 2; k >= -1; k--) {
        if (k === -1) {
          break;
        }
        const alpha = Number.MIN_VALUE + eps * Math.abs(s[k] + Math.abs(s[k + 1]));
        if (Math.abs(e[k]) <= alpha || Number.isNaN(e[k])) {
          e[k] = 0;
          break;
        }
      }
      if (k === p - 2) {
        kase = 4;
      } else {
        let ks;
        for (ks = p - 1; ks >= k; ks--) {
          if (ks === k) {
            break;
          }
          let t = (ks !== p ? Math.abs(e[ks]) : 0) + (ks !== k + 1 ? Math.abs(e[ks - 1]) : 0);
          if (Math.abs(s[ks]) <= eps * t) {
            s[ks] = 0;
            break;
          }
        }
        if (ks === k) {
          kase = 3;
        } else if (ks === p - 1) {
          kase = 1;
        } else {
          kase = 2;
          k = ks;
        }
      }
      k++;
      switch (kase) {
        case 1:
          {
            let f = e[p - 2];
            e[p - 2] = 0;
            for (let j = p - 2; j >= k; j--) {
              let t = hypotenuse$1(s[j], f);
              let cs = s[j] / t;
              let sn = f / t;
              s[j] = t;
              if (j !== k) {
                f = -sn * e[j - 1];
                e[j - 1] = cs * e[j - 1];
              }
              if (wantv) {
                for (let i = 0; i < n; i++) {
                  t = cs * V.get(i, j) + sn * V.get(i, p - 1);
                  V.set(i, p - 1, -sn * V.get(i, j) + cs * V.get(i, p - 1));
                  V.set(i, j, t);
                }
              }
            }
            break;
          }
        case 2:
          {
            let f = e[k - 1];
            e[k - 1] = 0;
            for (let j = k; j < p; j++) {
              let t = hypotenuse$1(s[j], f);
              let cs = s[j] / t;
              let sn = f / t;
              s[j] = t;
              f = -sn * e[j];
              e[j] = cs * e[j];
              if (wantu) {
                for (let i = 0; i < m; i++) {
                  t = cs * U.get(i, j) + sn * U.get(i, k - 1);
                  U.set(i, k - 1, -sn * U.get(i, j) + cs * U.get(i, k - 1));
                  U.set(i, j, t);
                }
              }
            }
            break;
          }
        case 3:
          {
            const scale = Math.max(Math.abs(s[p - 1]), Math.abs(s[p - 2]), Math.abs(e[p - 2]), Math.abs(s[k]), Math.abs(e[k]));
            const sp = s[p - 1] / scale;
            const spm1 = s[p - 2] / scale;
            const epm1 = e[p - 2] / scale;
            const sk = s[k] / scale;
            const ek = e[k] / scale;
            const b = ((spm1 + sp) * (spm1 - sp) + epm1 * epm1) / 2;
            const c = sp * epm1 * (sp * epm1);
            let shift = 0;
            if (b !== 0 || c !== 0) {
              if (b < 0) {
                shift = 0 - Math.sqrt(b * b + c);
              } else {
                shift = Math.sqrt(b * b + c);
              }
              shift = c / (b + shift);
            }
            let f = (sk + sp) * (sk - sp) + shift;
            let g = sk * ek;
            for (let j = k; j < p - 1; j++) {
              let t = hypotenuse$1(f, g);
              if (t === 0) t = Number.MIN_VALUE;
              let cs = f / t;
              let sn = g / t;
              if (j !== k) {
                e[j - 1] = t;
              }
              f = cs * s[j] + sn * e[j];
              e[j] = cs * e[j] - sn * s[j];
              g = sn * s[j + 1];
              s[j + 1] = cs * s[j + 1];
              if (wantv) {
                for (let i = 0; i < n; i++) {
                  t = cs * V.get(i, j) + sn * V.get(i, j + 1);
                  V.set(i, j + 1, -sn * V.get(i, j) + cs * V.get(i, j + 1));
                  V.set(i, j, t);
                }
              }
              t = hypotenuse$1(f, g);
              if (t === 0) t = Number.MIN_VALUE;
              cs = f / t;
              sn = g / t;
              s[j] = t;
              f = cs * e[j] + sn * s[j + 1];
              s[j + 1] = -sn * e[j] + cs * s[j + 1];
              g = sn * e[j + 1];
              e[j + 1] = cs * e[j + 1];
              if (wantu && j < m - 1) {
                for (let i = 0; i < m; i++) {
                  t = cs * U.get(i, j) + sn * U.get(i, j + 1);
                  U.set(i, j + 1, -sn * U.get(i, j) + cs * U.get(i, j + 1));
                  U.set(i, j, t);
                }
              }
            }
            e[p - 2] = f;
            break;
          }
        case 4:
          {
            if (s[k] <= 0) {
              s[k] = s[k] < 0 ? -s[k] : 0;
              if (wantv) {
                for (let i = 0; i <= pp; i++) {
                  V.set(i, k, -V.get(i, k));
                }
              }
            }
            while (k < pp) {
              if (s[k] >= s[k + 1]) {
                break;
              }
              let t = s[k];
              s[k] = s[k + 1];
              s[k + 1] = t;
              if (wantv && k < n - 1) {
                for (let i = 0; i < n; i++) {
                  t = V.get(i, k + 1);
                  V.set(i, k + 1, V.get(i, k));
                  V.set(i, k, t);
                }
              }
              if (wantu && k < m - 1) {
                for (let i = 0; i < m; i++) {
                  t = U.get(i, k + 1);
                  U.set(i, k + 1, U.get(i, k));
                  U.set(i, k, t);
                }
              }
              k++;
            }
            p--;
            break;
          }
        // no default
      }
    }
    if (swapped) {
      let tmp = V;
      V = U;
      U = tmp;
    }
    this.m = m;
    this.n = n;
    this.s = s;
    this.U = U;
    this.V = V;
  }
  solve(value) {
    let Y = value;
    let e = this.threshold;
    let scols = this.s.length;
    let Ls = Matrix$2.zeros(scols, scols);
    for (let i = 0; i < scols; i++) {
      if (Math.abs(this.s[i]) <= e) {
        Ls.set(i, i, 0);
      } else {
        Ls.set(i, i, 1 / this.s[i]);
      }
    }
    let U = this.U;
    let V = this.rightSingularVectors;
    let VL = V.mmul(Ls);
    let vrows = V.rows;
    let urows = U.rows;
    let VLU = Matrix$2.zeros(vrows, urows);
    for (let i = 0; i < vrows; i++) {
      for (let j = 0; j < urows; j++) {
        let sum = 0;
        for (let k = 0; k < scols; k++) {
          sum += VL.get(i, k) * U.get(j, k);
        }
        VLU.set(i, j, sum);
      }
    }
    return VLU.mmul(Y);
  }
  solveForDiagonal(value) {
    return this.solve(Matrix$2.diag(value));
  }
  inverse() {
    let V = this.V;
    let e = this.threshold;
    let vrows = V.rows;
    let vcols = V.columns;
    let X = new Matrix$2(vrows, this.s.length);
    for (let i = 0; i < vrows; i++) {
      for (let j = 0; j < vcols; j++) {
        if (Math.abs(this.s[j]) > e) {
          X.set(i, j, V.get(i, j) / this.s[j]);
        }
      }
    }
    let U = this.U;
    let urows = U.rows;
    let ucols = U.columns;
    let Y = new Matrix$2(vrows, urows);
    for (let i = 0; i < vrows; i++) {
      for (let j = 0; j < urows; j++) {
        let sum = 0;
        for (let k = 0; k < ucols; k++) {
          sum += X.get(i, k) * U.get(j, k);
        }
        Y.set(i, j, sum);
      }
    }
    return Y;
  }
  get condition() {
    return this.s[0] / this.s[Math.min(this.m, this.n) - 1];
  }
  get norm2() {
    return this.s[0];
  }
  get rank() {
    let tol = Math.max(this.m, this.n) * this.s[0] * Number.EPSILON;
    let r = 0;
    let s = this.s;
    for (let i = 0, ii = s.length; i < ii; i++) {
      if (s[i] > tol) {
        r++;
      }
    }
    return r;
  }
  get diagonal() {
    return Array.from(this.s);
  }
  get threshold() {
    return Number.EPSILON / 2 * Math.max(this.m, this.n) * this.s[0];
  }
  get leftSingularVectors() {
    return this.U;
  }
  get rightSingularVectors() {
    return this.V;
  }
  get diagonalMatrix() {
    return Matrix$2.diag(this.s);
  }
};
function inverse$1(matrix, useSVD = false) {
  matrix = WrapperMatrix2D.checkMatrix(matrix);
  if (useSVD) {
    return new SingularValueDecomposition$1(matrix).inverse();
  } else {
    return solve(matrix, Matrix$2.eye(matrix.rows));
  }
}
function solve(leftHandSide, rightHandSide, useSVD = false) {
  leftHandSide = WrapperMatrix2D.checkMatrix(leftHandSide);
  rightHandSide = WrapperMatrix2D.checkMatrix(rightHandSide);
  if (useSVD) {
    return new SingularValueDecomposition$1(leftHandSide).solve(rightHandSide);
  } else {
    return leftHandSide.isSquare() ? new LuDecomposition(leftHandSide).solve(rightHandSide) : new QrDecomposition(leftHandSide).solve(rightHandSide);
  }
}
function determinant$1(matrix) {
  matrix = Matrix$2.checkMatrix(matrix);
  if (matrix.isSquare()) {
    if (matrix.columns === 0) {
      return 1;
    }
    let a, b, c, d;
    if (matrix.columns === 2) {
      // 2 x 2 matrix
      a = matrix.get(0, 0);
      b = matrix.get(0, 1);
      c = matrix.get(1, 0);
      d = matrix.get(1, 1);
      return a * d - b * c;
    } else if (matrix.columns === 3) {
      // 3 x 3 matrix
      let subMatrix0, subMatrix1, subMatrix2;
      subMatrix0 = new MatrixSelectionView(matrix, [1, 2], [1, 2]);
      subMatrix1 = new MatrixSelectionView(matrix, [1, 2], [0, 2]);
      subMatrix2 = new MatrixSelectionView(matrix, [1, 2], [0, 1]);
      a = matrix.get(0, 0);
      b = matrix.get(0, 1);
      c = matrix.get(0, 2);
      return a * determinant$1(subMatrix0) - b * determinant$1(subMatrix1) + c * determinant$1(subMatrix2);
    } else {
      // general purpose determinant using the LU decomposition
      return new LuDecomposition(matrix).determinant;
    }
  } else {
    throw Error('determinant can only be calculated for a square matrix');
  }
}
function xrange(n, exception) {
  let range = [];
  for (let i = 0; i < n; i++) {
    if (i !== exception) {
      range.push(i);
    }
  }
  return range;
}
function dependenciesOneRow(error, matrix, index, thresholdValue = 10e-10, thresholdError = 10e-10) {
  if (error > thresholdError) {
    return new Array(matrix.rows + 1).fill(0);
  } else {
    let returnArray = matrix.addRow(index, [0]);
    for (let i = 0; i < returnArray.rows; i++) {
      if (Math.abs(returnArray.get(i, 0)) < thresholdValue) {
        returnArray.set(i, 0, 0);
      }
    }
    return returnArray.to1DArray();
  }
}
function linearDependencies(matrix, options = {}) {
  const {
    thresholdValue = 10e-10,
    thresholdError = 10e-10
  } = options;
  matrix = Matrix$2.checkMatrix(matrix);
  let n = matrix.rows;
  let results = new Matrix$2(n, n);
  for (let i = 0; i < n; i++) {
    let b = Matrix$2.columnVector(matrix.getRow(i));
    let Abis = matrix.subMatrixRow(xrange(n, i)).transpose();
    let svd = new SingularValueDecomposition$1(Abis);
    let x = svd.solve(b);
    let error = Matrix$2.sub(b, Abis.mmul(x)).abs().max();
    results.setRow(i, dependenciesOneRow(error, x, i, thresholdValue, thresholdError));
  }
  return results;
}
function pseudoInverse$1(matrix, threshold = Number.EPSILON) {
  matrix = Matrix$2.checkMatrix(matrix);
  if (matrix.isEmpty()) {
    // with a zero dimension, the pseudo-inverse is the transpose, since all 0xn and nx0 matrices are singular
    // (0xn)*(nx0)*(0xn) = 0xn
    // (nx0)*(0xn)*(nx0) = nx0
    return matrix.transpose();
  }
  let svdSolution = new SingularValueDecomposition$1(matrix, {
    autoTranspose: true
  });
  let U = svdSolution.leftSingularVectors;
  let V = svdSolution.rightSingularVectors;
  let s = svdSolution.diagonal;
  for (let i = 0; i < s.length; i++) {
    if (Math.abs(s[i]) > threshold) {
      s[i] = 1.0 / s[i];
    } else {
      s[i] = 0.0;
    }
  }
  return V.mmul(Matrix$2.diag(s).mmul(U.transpose()));
}
function covariance(xMatrix, yMatrix = xMatrix, options = {}) {
  xMatrix = new Matrix$2(xMatrix);
  let yIsSame = false;
  if (typeof yMatrix === 'object' && !Matrix$2.isMatrix(yMatrix) && !isAnyArray.isAnyArray(yMatrix)) {
    options = yMatrix;
    yMatrix = xMatrix;
    yIsSame = true;
  } else {
    yMatrix = new Matrix$2(yMatrix);
  }
  if (xMatrix.rows !== yMatrix.rows) {
    throw new TypeError('Both matrices must have the same number of rows');
  }
  const {
    center = true
  } = options;
  if (center) {
    xMatrix = xMatrix.center('column');
    if (!yIsSame) {
      yMatrix = yMatrix.center('column');
    }
  }
  const cov = xMatrix.transpose().mmul(yMatrix);
  for (let i = 0; i < cov.rows; i++) {
    for (let j = 0; j < cov.columns; j++) {
      cov.set(i, j, cov.get(i, j) * (1 / (xMatrix.rows - 1)));
    }
  }
  return cov;
}
function correlation(xMatrix, yMatrix = xMatrix, options = {}) {
  xMatrix = new Matrix$2(xMatrix);
  let yIsSame = false;
  if (typeof yMatrix === 'object' && !Matrix$2.isMatrix(yMatrix) && !isAnyArray.isAnyArray(yMatrix)) {
    options = yMatrix;
    yMatrix = xMatrix;
    yIsSame = true;
  } else {
    yMatrix = new Matrix$2(yMatrix);
  }
  if (xMatrix.rows !== yMatrix.rows) {
    throw new TypeError('Both matrices must have the same number of rows');
  }
  const {
    center = true,
    scale = true
  } = options;
  if (center) {
    xMatrix.center('column');
    if (!yIsSame) {
      yMatrix.center('column');
    }
  }
  if (scale) {
    xMatrix.scale('column');
    if (!yIsSame) {
      yMatrix.scale('column');
    }
  }
  const sdx = xMatrix.standardDeviation('column', {
    unbiased: true
  });
  const sdy = yIsSame ? sdx : yMatrix.standardDeviation('column', {
    unbiased: true
  });
  const corr = xMatrix.transpose().mmul(yMatrix);
  for (let i = 0; i < corr.rows; i++) {
    for (let j = 0; j < corr.columns; j++) {
      corr.set(i, j, corr.get(i, j) * (1 / (sdx[i] * sdy[j])) * (1 / (xMatrix.rows - 1)));
    }
  }
  return corr;
}
let EigenvalueDecomposition$1 = class EigenvalueDecomposition {
  constructor(matrix, options = {}) {
    const {
      assumeSymmetric = false
    } = options;
    matrix = WrapperMatrix2D.checkMatrix(matrix);
    if (!matrix.isSquare()) {
      throw new Error('Matrix is not a square matrix');
    }
    if (matrix.isEmpty()) {
      throw new Error('Matrix must be non-empty');
    }
    let n = matrix.columns;
    let V = new Matrix$2(n, n);
    let d = new Float64Array(n);
    let e = new Float64Array(n);
    let value = matrix;
    let i, j;
    let isSymmetric = false;
    if (assumeSymmetric) {
      isSymmetric = true;
    } else {
      isSymmetric = matrix.isSymmetric();
    }
    if (isSymmetric) {
      for (i = 0; i < n; i++) {
        for (j = 0; j < n; j++) {
          V.set(i, j, value.get(i, j));
        }
      }
      tred2(n, e, d, V);
      tql2(n, e, d, V);
    } else {
      let H = new Matrix$2(n, n);
      let ort = new Float64Array(n);
      for (j = 0; j < n; j++) {
        for (i = 0; i < n; i++) {
          H.set(i, j, value.get(i, j));
        }
      }
      orthes(n, H, ort, V);
      hqr2(n, e, d, V, H);
    }
    this.n = n;
    this.e = e;
    this.d = d;
    this.V = V;
  }
  get realEigenvalues() {
    return Array.from(this.d);
  }
  get imaginaryEigenvalues() {
    return Array.from(this.e);
  }
  get eigenvectorMatrix() {
    return this.V;
  }
  get diagonalMatrix() {
    let n = this.n;
    let e = this.e;
    let d = this.d;
    let X = new Matrix$2(n, n);
    let i, j;
    for (i = 0; i < n; i++) {
      for (j = 0; j < n; j++) {
        X.set(i, j, 0);
      }
      X.set(i, i, d[i]);
      if (e[i] > 0) {
        X.set(i, i + 1, e[i]);
      } else if (e[i] < 0) {
        X.set(i, i - 1, e[i]);
      }
    }
    return X;
  }
};
function tred2(n, e, d, V) {
  let f, g, h, i, j, k, hh, scale;
  for (j = 0; j < n; j++) {
    d[j] = V.get(n - 1, j);
  }
  for (i = n - 1; i > 0; i--) {
    scale = 0;
    h = 0;
    for (k = 0; k < i; k++) {
      scale = scale + Math.abs(d[k]);
    }
    if (scale === 0) {
      e[i] = d[i - 1];
      for (j = 0; j < i; j++) {
        d[j] = V.get(i - 1, j);
        V.set(i, j, 0);
        V.set(j, i, 0);
      }
    } else {
      for (k = 0; k < i; k++) {
        d[k] /= scale;
        h += d[k] * d[k];
      }
      f = d[i - 1];
      g = Math.sqrt(h);
      if (f > 0) {
        g = -g;
      }
      e[i] = scale * g;
      h = h - f * g;
      d[i - 1] = f - g;
      for (j = 0; j < i; j++) {
        e[j] = 0;
      }
      for (j = 0; j < i; j++) {
        f = d[j];
        V.set(j, i, f);
        g = e[j] + V.get(j, j) * f;
        for (k = j + 1; k <= i - 1; k++) {
          g += V.get(k, j) * d[k];
          e[k] += V.get(k, j) * f;
        }
        e[j] = g;
      }
      f = 0;
      for (j = 0; j < i; j++) {
        e[j] /= h;
        f += e[j] * d[j];
      }
      hh = f / (h + h);
      for (j = 0; j < i; j++) {
        e[j] -= hh * d[j];
      }
      for (j = 0; j < i; j++) {
        f = d[j];
        g = e[j];
        for (k = j; k <= i - 1; k++) {
          V.set(k, j, V.get(k, j) - (f * e[k] + g * d[k]));
        }
        d[j] = V.get(i - 1, j);
        V.set(i, j, 0);
      }
    }
    d[i] = h;
  }
  for (i = 0; i < n - 1; i++) {
    V.set(n - 1, i, V.get(i, i));
    V.set(i, i, 1);
    h = d[i + 1];
    if (h !== 0) {
      for (k = 0; k <= i; k++) {
        d[k] = V.get(k, i + 1) / h;
      }
      for (j = 0; j <= i; j++) {
        g = 0;
        for (k = 0; k <= i; k++) {
          g += V.get(k, i + 1) * V.get(k, j);
        }
        for (k = 0; k <= i; k++) {
          V.set(k, j, V.get(k, j) - g * d[k]);
        }
      }
    }
    for (k = 0; k <= i; k++) {
      V.set(k, i + 1, 0);
    }
  }
  for (j = 0; j < n; j++) {
    d[j] = V.get(n - 1, j);
    V.set(n - 1, j, 0);
  }
  V.set(n - 1, n - 1, 1);
  e[0] = 0;
}
function tql2(n, e, d, V) {
  let g, h, i, j, k, l, m, p, r, dl1, c, c2, c3, el1, s, s2;
  for (i = 1; i < n; i++) {
    e[i - 1] = e[i];
  }
  e[n - 1] = 0;
  let f = 0;
  let tst1 = 0;
  let eps = Number.EPSILON;
  for (l = 0; l < n; l++) {
    tst1 = Math.max(tst1, Math.abs(d[l]) + Math.abs(e[l]));
    m = l;
    while (m < n) {
      if (Math.abs(e[m]) <= eps * tst1) {
        break;
      }
      m++;
    }
    if (m > l) {
      do {
        g = d[l];
        p = (d[l + 1] - g) / (2 * e[l]);
        r = hypotenuse$1(p, 1);
        if (p < 0) {
          r = -r;
        }
        d[l] = e[l] / (p + r);
        d[l + 1] = e[l] * (p + r);
        dl1 = d[l + 1];
        h = g - d[l];
        for (i = l + 2; i < n; i++) {
          d[i] -= h;
        }
        f = f + h;
        p = d[m];
        c = 1;
        c2 = c;
        c3 = c;
        el1 = e[l + 1];
        s = 0;
        s2 = 0;
        for (i = m - 1; i >= l; i--) {
          c3 = c2;
          c2 = c;
          s2 = s;
          g = c * e[i];
          h = c * p;
          r = hypotenuse$1(p, e[i]);
          e[i + 1] = s * r;
          s = e[i] / r;
          c = p / r;
          p = c * d[i] - s * g;
          d[i + 1] = h + s * (c * g + s * d[i]);
          for (k = 0; k < n; k++) {
            h = V.get(k, i + 1);
            V.set(k, i + 1, s * V.get(k, i) + c * h);
            V.set(k, i, c * V.get(k, i) - s * h);
          }
        }
        p = -s * s2 * c3 * el1 * e[l] / dl1;
        e[l] = s * p;
        d[l] = c * p;
      } while (Math.abs(e[l]) > eps * tst1);
    }
    d[l] = d[l] + f;
    e[l] = 0;
  }
  for (i = 0; i < n - 1; i++) {
    k = i;
    p = d[i];
    for (j = i + 1; j < n; j++) {
      if (d[j] < p) {
        k = j;
        p = d[j];
      }
    }
    if (k !== i) {
      d[k] = d[i];
      d[i] = p;
      for (j = 0; j < n; j++) {
        p = V.get(j, i);
        V.set(j, i, V.get(j, k));
        V.set(j, k, p);
      }
    }
  }
}
function orthes(n, H, ort, V) {
  let low = 0;
  let high = n - 1;
  let f, g, h, i, j, m;
  let scale;
  for (m = low + 1; m <= high - 1; m++) {
    scale = 0;
    for (i = m; i <= high; i++) {
      scale = scale + Math.abs(H.get(i, m - 1));
    }
    if (scale !== 0) {
      h = 0;
      for (i = high; i >= m; i--) {
        ort[i] = H.get(i, m - 1) / scale;
        h += ort[i] * ort[i];
      }
      g = Math.sqrt(h);
      if (ort[m] > 0) {
        g = -g;
      }
      h = h - ort[m] * g;
      ort[m] = ort[m] - g;
      for (j = m; j < n; j++) {
        f = 0;
        for (i = high; i >= m; i--) {
          f += ort[i] * H.get(i, j);
        }
        f = f / h;
        for (i = m; i <= high; i++) {
          H.set(i, j, H.get(i, j) - f * ort[i]);
        }
      }
      for (i = 0; i <= high; i++) {
        f = 0;
        for (j = high; j >= m; j--) {
          f += ort[j] * H.get(i, j);
        }
        f = f / h;
        for (j = m; j <= high; j++) {
          H.set(i, j, H.get(i, j) - f * ort[j]);
        }
      }
      ort[m] = scale * ort[m];
      H.set(m, m - 1, scale * g);
    }
  }
  for (i = 0; i < n; i++) {
    for (j = 0; j < n; j++) {
      V.set(i, j, i === j ? 1 : 0);
    }
  }
  for (m = high - 1; m >= low + 1; m--) {
    if (H.get(m, m - 1) !== 0) {
      for (i = m + 1; i <= high; i++) {
        ort[i] = H.get(i, m - 1);
      }
      for (j = m; j <= high; j++) {
        g = 0;
        for (i = m; i <= high; i++) {
          g += ort[i] * V.get(i, j);
        }
        g = g / ort[m] / H.get(m, m - 1);
        for (i = m; i <= high; i++) {
          V.set(i, j, V.get(i, j) + g * ort[i]);
        }
      }
    }
  }
}
function hqr2(nn, e, d, V, H) {
  let n = nn - 1;
  let low = 0;
  let high = nn - 1;
  let eps = Number.EPSILON;
  let exshift = 0;
  let norm = 0;
  let p = 0;
  let q = 0;
  let r = 0;
  let s = 0;
  let z = 0;
  let iter = 0;
  let i, j, k, l, m, t, w, x, y;
  let ra, sa, vr, vi;
  let notlast, cdivres;
  for (i = 0; i < nn; i++) {
    if (i < low || i > high) {
      d[i] = H.get(i, i);
      e[i] = 0;
    }
    for (j = Math.max(i - 1, 0); j < nn; j++) {
      norm = norm + Math.abs(H.get(i, j));
    }
  }
  while (n >= low) {
    l = n;
    while (l > low) {
      s = Math.abs(H.get(l - 1, l - 1)) + Math.abs(H.get(l, l));
      if (s === 0) {
        s = norm;
      }
      if (Math.abs(H.get(l, l - 1)) < eps * s) {
        break;
      }
      l--;
    }
    if (l === n) {
      H.set(n, n, H.get(n, n) + exshift);
      d[n] = H.get(n, n);
      e[n] = 0;
      n--;
      iter = 0;
    } else if (l === n - 1) {
      w = H.get(n, n - 1) * H.get(n - 1, n);
      p = (H.get(n - 1, n - 1) - H.get(n, n)) / 2;
      q = p * p + w;
      z = Math.sqrt(Math.abs(q));
      H.set(n, n, H.get(n, n) + exshift);
      H.set(n - 1, n - 1, H.get(n - 1, n - 1) + exshift);
      x = H.get(n, n);
      if (q >= 0) {
        z = p >= 0 ? p + z : p - z;
        d[n - 1] = x + z;
        d[n] = d[n - 1];
        if (z !== 0) {
          d[n] = x - w / z;
        }
        e[n - 1] = 0;
        e[n] = 0;
        x = H.get(n, n - 1);
        s = Math.abs(x) + Math.abs(z);
        p = x / s;
        q = z / s;
        r = Math.sqrt(p * p + q * q);
        p = p / r;
        q = q / r;
        for (j = n - 1; j < nn; j++) {
          z = H.get(n - 1, j);
          H.set(n - 1, j, q * z + p * H.get(n, j));
          H.set(n, j, q * H.get(n, j) - p * z);
        }
        for (i = 0; i <= n; i++) {
          z = H.get(i, n - 1);
          H.set(i, n - 1, q * z + p * H.get(i, n));
          H.set(i, n, q * H.get(i, n) - p * z);
        }
        for (i = low; i <= high; i++) {
          z = V.get(i, n - 1);
          V.set(i, n - 1, q * z + p * V.get(i, n));
          V.set(i, n, q * V.get(i, n) - p * z);
        }
      } else {
        d[n - 1] = x + p;
        d[n] = x + p;
        e[n - 1] = z;
        e[n] = -z;
      }
      n = n - 2;
      iter = 0;
    } else {
      x = H.get(n, n);
      y = 0;
      w = 0;
      if (l < n) {
        y = H.get(n - 1, n - 1);
        w = H.get(n, n - 1) * H.get(n - 1, n);
      }
      if (iter === 10) {
        exshift += x;
        for (i = low; i <= n; i++) {
          H.set(i, i, H.get(i, i) - x);
        }
        s = Math.abs(H.get(n, n - 1)) + Math.abs(H.get(n - 1, n - 2));
        // eslint-disable-next-line no-multi-assign
        x = y = 0.75 * s;
        w = -0.4375 * s * s;
      }
      if (iter === 30) {
        s = (y - x) / 2;
        s = s * s + w;
        if (s > 0) {
          s = Math.sqrt(s);
          if (y < x) {
            s = -s;
          }
          s = x - w / ((y - x) / 2 + s);
          for (i = low; i <= n; i++) {
            H.set(i, i, H.get(i, i) - s);
          }
          exshift += s;
          // eslint-disable-next-line no-multi-assign
          x = y = w = 0.964;
        }
      }
      iter = iter + 1;
      m = n - 2;
      while (m >= l) {
        z = H.get(m, m);
        r = x - z;
        s = y - z;
        p = (r * s - w) / H.get(m + 1, m) + H.get(m, m + 1);
        q = H.get(m + 1, m + 1) - z - r - s;
        r = H.get(m + 2, m + 1);
        s = Math.abs(p) + Math.abs(q) + Math.abs(r);
        p = p / s;
        q = q / s;
        r = r / s;
        if (m === l) {
          break;
        }
        if (Math.abs(H.get(m, m - 1)) * (Math.abs(q) + Math.abs(r)) < eps * (Math.abs(p) * (Math.abs(H.get(m - 1, m - 1)) + Math.abs(z) + Math.abs(H.get(m + 1, m + 1))))) {
          break;
        }
        m--;
      }
      for (i = m + 2; i <= n; i++) {
        H.set(i, i - 2, 0);
        if (i > m + 2) {
          H.set(i, i - 3, 0);
        }
      }
      for (k = m; k <= n - 1; k++) {
        notlast = k !== n - 1;
        if (k !== m) {
          p = H.get(k, k - 1);
          q = H.get(k + 1, k - 1);
          r = notlast ? H.get(k + 2, k - 1) : 0;
          x = Math.abs(p) + Math.abs(q) + Math.abs(r);
          if (x !== 0) {
            p = p / x;
            q = q / x;
            r = r / x;
          }
        }
        if (x === 0) {
          break;
        }
        s = Math.sqrt(p * p + q * q + r * r);
        if (p < 0) {
          s = -s;
        }
        if (s !== 0) {
          if (k !== m) {
            H.set(k, k - 1, -s * x);
          } else if (l !== m) {
            H.set(k, k - 1, -H.get(k, k - 1));
          }
          p = p + s;
          x = p / s;
          y = q / s;
          z = r / s;
          q = q / p;
          r = r / p;
          for (j = k; j < nn; j++) {
            p = H.get(k, j) + q * H.get(k + 1, j);
            if (notlast) {
              p = p + r * H.get(k + 2, j);
              H.set(k + 2, j, H.get(k + 2, j) - p * z);
            }
            H.set(k, j, H.get(k, j) - p * x);
            H.set(k + 1, j, H.get(k + 1, j) - p * y);
          }
          for (i = 0; i <= Math.min(n, k + 3); i++) {
            p = x * H.get(i, k) + y * H.get(i, k + 1);
            if (notlast) {
              p = p + z * H.get(i, k + 2);
              H.set(i, k + 2, H.get(i, k + 2) - p * r);
            }
            H.set(i, k, H.get(i, k) - p);
            H.set(i, k + 1, H.get(i, k + 1) - p * q);
          }
          for (i = low; i <= high; i++) {
            p = x * V.get(i, k) + y * V.get(i, k + 1);
            if (notlast) {
              p = p + z * V.get(i, k + 2);
              V.set(i, k + 2, V.get(i, k + 2) - p * r);
            }
            V.set(i, k, V.get(i, k) - p);
            V.set(i, k + 1, V.get(i, k + 1) - p * q);
          }
        }
      }
    }
  }
  if (norm === 0) {
    return;
  }
  for (n = nn - 1; n >= 0; n--) {
    p = d[n];
    q = e[n];
    if (q === 0) {
      l = n;
      H.set(n, n, 1);
      for (i = n - 1; i >= 0; i--) {
        w = H.get(i, i) - p;
        r = 0;
        for (j = l; j <= n; j++) {
          r = r + H.get(i, j) * H.get(j, n);
        }
        if (e[i] < 0) {
          z = w;
          s = r;
        } else {
          l = i;
          if (e[i] === 0) {
            H.set(i, n, w !== 0 ? -r / w : -r / (eps * norm));
          } else {
            x = H.get(i, i + 1);
            y = H.get(i + 1, i);
            q = (d[i] - p) * (d[i] - p) + e[i] * e[i];
            t = (x * s - z * r) / q;
            H.set(i, n, t);
            H.set(i + 1, n, Math.abs(x) > Math.abs(z) ? (-r - w * t) / x : (-s - y * t) / z);
          }
          t = Math.abs(H.get(i, n));
          if (eps * t * t > 1) {
            for (j = i; j <= n; j++) {
              H.set(j, n, H.get(j, n) / t);
            }
          }
        }
      }
    } else if (q < 0) {
      l = n - 1;
      if (Math.abs(H.get(n, n - 1)) > Math.abs(H.get(n - 1, n))) {
        H.set(n - 1, n - 1, q / H.get(n, n - 1));
        H.set(n - 1, n, -(H.get(n, n) - p) / H.get(n, n - 1));
      } else {
        cdivres = cdiv(0, -H.get(n - 1, n), H.get(n - 1, n - 1) - p, q);
        H.set(n - 1, n - 1, cdivres[0]);
        H.set(n - 1, n, cdivres[1]);
      }
      H.set(n, n - 1, 0);
      H.set(n, n, 1);
      for (i = n - 2; i >= 0; i--) {
        ra = 0;
        sa = 0;
        for (j = l; j <= n; j++) {
          ra = ra + H.get(i, j) * H.get(j, n - 1);
          sa = sa + H.get(i, j) * H.get(j, n);
        }
        w = H.get(i, i) - p;
        if (e[i] < 0) {
          z = w;
          r = ra;
          s = sa;
        } else {
          l = i;
          if (e[i] === 0) {
            cdivres = cdiv(-ra, -sa, w, q);
            H.set(i, n - 1, cdivres[0]);
            H.set(i, n, cdivres[1]);
          } else {
            x = H.get(i, i + 1);
            y = H.get(i + 1, i);
            vr = (d[i] - p) * (d[i] - p) + e[i] * e[i] - q * q;
            vi = (d[i] - p) * 2 * q;
            if (vr === 0 && vi === 0) {
              vr = eps * norm * (Math.abs(w) + Math.abs(q) + Math.abs(x) + Math.abs(y) + Math.abs(z));
            }
            cdivres = cdiv(x * r - z * ra + q * sa, x * s - z * sa - q * ra, vr, vi);
            H.set(i, n - 1, cdivres[0]);
            H.set(i, n, cdivres[1]);
            if (Math.abs(x) > Math.abs(z) + Math.abs(q)) {
              H.set(i + 1, n - 1, (-ra - w * H.get(i, n - 1) + q * H.get(i, n)) / x);
              H.set(i + 1, n, (-sa - w * H.get(i, n) - q * H.get(i, n - 1)) / x);
            } else {
              cdivres = cdiv(-r - y * H.get(i, n - 1), -s - y * H.get(i, n), z, q);
              H.set(i + 1, n - 1, cdivres[0]);
              H.set(i + 1, n, cdivres[1]);
            }
          }
          t = Math.max(Math.abs(H.get(i, n - 1)), Math.abs(H.get(i, n)));
          if (eps * t * t > 1) {
            for (j = i; j <= n; j++) {
              H.set(j, n - 1, H.get(j, n - 1) / t);
              H.set(j, n, H.get(j, n) / t);
            }
          }
        }
      }
    }
  }
  for (i = 0; i < nn; i++) {
    if (i < low || i > high) {
      for (j = i; j < nn; j++) {
        V.set(i, j, H.get(i, j));
      }
    }
  }
  for (j = nn - 1; j >= low; j--) {
    for (i = low; i <= high; i++) {
      z = 0;
      for (k = low; k <= Math.min(j, high); k++) {
        z = z + V.get(i, k) * H.get(k, j);
      }
      V.set(i, j, z);
    }
  }
}
function cdiv(xr, xi, yr, yi) {
  let r, d;
  if (Math.abs(yr) > Math.abs(yi)) {
    r = yi / yr;
    d = yr + r * yi;
    return [(xr + r * xi) / d, (xi - r * xr) / d];
  } else {
    r = yr / yi;
    d = yi + r * yr;
    return [(r * xr + xi) / d, (r * xi - xr) / d];
  }
}
class CholeskyDecomposition {
  constructor(value) {
    value = WrapperMatrix2D.checkMatrix(value);
    if (!value.isSymmetric()) {
      throw new Error('Matrix is not symmetric');
    }
    let a = value;
    let dimension = a.rows;
    let l = new Matrix$2(dimension, dimension);
    let positiveDefinite = true;
    let i, j, k;
    for (j = 0; j < dimension; j++) {
      let d = 0;
      for (k = 0; k < j; k++) {
        let s = 0;
        for (i = 0; i < k; i++) {
          s += l.get(k, i) * l.get(j, i);
        }
        s = (a.get(j, k) - s) / l.get(k, k);
        l.set(j, k, s);
        d = d + s * s;
      }
      d = a.get(j, j) - d;
      positiveDefinite &&= d > 0;
      l.set(j, j, Math.sqrt(Math.max(d, 0)));
      for (k = j + 1; k < dimension; k++) {
        l.set(j, k, 0);
      }
    }
    this.L = l;
    this.positiveDefinite = positiveDefinite;
  }
  isPositiveDefinite() {
    return this.positiveDefinite;
  }
  solve(value) {
    value = WrapperMatrix2D.checkMatrix(value);
    let l = this.L;
    let dimension = l.rows;
    if (value.rows !== dimension) {
      throw new Error('Matrix dimensions do not match');
    }
    if (this.isPositiveDefinite() === false) {
      throw new Error('Matrix is not positive definite');
    }
    let count = value.columns;
    let B = value.clone();
    let i, j, k;
    for (k = 0; k < dimension; k++) {
      for (j = 0; j < count; j++) {
        for (i = 0; i < k; i++) {
          B.set(k, j, B.get(k, j) - B.get(i, j) * l.get(k, i));
        }
        B.set(k, j, B.get(k, j) / l.get(k, k));
      }
    }
    for (k = dimension - 1; k >= 0; k--) {
      for (j = 0; j < count; j++) {
        for (i = k + 1; i < dimension; i++) {
          B.set(k, j, B.get(k, j) - B.get(i, j) * l.get(i, k));
        }
        B.set(k, j, B.get(k, j) / l.get(k, k));
      }
    }
    return B;
  }
  get lowerTriangularMatrix() {
    return this.L;
  }
}
class nipals {
  constructor(X, options = {}) {
    X = WrapperMatrix2D.checkMatrix(X);
    let {
      Y
    } = options;
    const {
      scaleScores = false,
      maxIterations = 1000,
      terminationCriteria = 1e-10
    } = options;
    let u;
    if (Y) {
      if (isAnyArray.isAnyArray(Y) && typeof Y[0] === 'number') {
        Y = Matrix$2.columnVector(Y);
      } else {
        Y = WrapperMatrix2D.checkMatrix(Y);
      }
      if (Y.rows !== X.rows) {
        throw new Error('Y should have the same number of rows as X');
      }
      u = Y.getColumnVector(0);
    } else {
      u = X.getColumnVector(0);
    }
    let diff = 1;
    let t, q, w, tOld;
    for (let counter = 0; counter < maxIterations && diff > terminationCriteria; counter++) {
      w = X.transpose().mmul(u).div(u.transpose().mmul(u).get(0, 0));
      w = w.div(w.norm());
      t = X.mmul(w).div(w.transpose().mmul(w).get(0, 0));
      if (counter > 0) {
        diff = t.clone().sub(tOld).pow(2).sum();
      }
      tOld = t.clone();
      if (Y) {
        q = Y.transpose().mmul(t).div(t.transpose().mmul(t).get(0, 0));
        q = q.div(q.norm());
        u = Y.mmul(q).div(q.transpose().mmul(q).get(0, 0));
      } else {
        u = t;
      }
    }
    if (Y) {
      let p = X.transpose().mmul(t).div(t.transpose().mmul(t).get(0, 0));
      p = p.div(p.norm());
      let xResidual = X.clone().sub(t.clone().mmul(p.transpose()));
      let residual = u.transpose().mmul(t).div(t.transpose().mmul(t).get(0, 0));
      let yResidual = Y.clone().sub(t.clone().mulS(residual.get(0, 0)).mmul(q.transpose()));
      this.t = t;
      this.p = p.transpose();
      this.w = w.transpose();
      this.q = q;
      this.u = u;
      this.s = t.transpose().mmul(t);
      this.xResidual = xResidual;
      this.yResidual = yResidual;
      this.betas = residual;
    } else {
      this.w = w.transpose();
      this.s = t.transpose().mmul(t).sqrt();
      if (scaleScores) {
        this.t = t.clone().div(this.s.get(0, 0));
      } else {
        this.t = t;
      }
      this.xResidual = X.sub(t.mmul(w.transpose()));
    }
  }
}
matrix.AbstractMatrix = AbstractMatrix;
matrix.CHO = CholeskyDecomposition;
matrix.CholeskyDecomposition = CholeskyDecomposition;
matrix.DistanceMatrix = DistanceMatrix;
matrix.EVD = EigenvalueDecomposition$1;
var EigenvalueDecomposition_1 = matrix.EigenvalueDecomposition = EigenvalueDecomposition$1;
matrix.LU = LuDecomposition;
matrix.LuDecomposition = LuDecomposition;
var Matrix_1 = matrix.Matrix = Matrix$2;
matrix.MatrixColumnSelectionView = MatrixColumnSelectionView;
matrix.MatrixColumnView = MatrixColumnView;
matrix.MatrixFlipColumnView = MatrixFlipColumnView;
matrix.MatrixFlipRowView = MatrixFlipRowView;
matrix.MatrixRowSelectionView = MatrixRowSelectionView;
matrix.MatrixRowView = MatrixRowView;
matrix.MatrixSelectionView = MatrixSelectionView;
matrix.MatrixSubView = MatrixSubView;
matrix.MatrixTransposeView = MatrixTransposeView;
matrix.NIPALS = nipals;
matrix.Nipals = nipals;
matrix.QR = QrDecomposition;
matrix.QrDecomposition = QrDecomposition;
var SVD$1 = matrix.SVD = SingularValueDecomposition$1;
var SingularValueDecomposition_1 = matrix.SingularValueDecomposition = SingularValueDecomposition$1;
matrix.SymmetricMatrix = SymmetricMatrix;
var WrapperMatrix1D_1 = matrix.WrapperMatrix1D = WrapperMatrix1D$1;
matrix.WrapperMatrix2D = WrapperMatrix2D;
matrix.correlation = correlation;
matrix.covariance = covariance;
var _default = matrix.default = Matrix$2;
var determinant_1 = matrix.determinant = determinant$1;
var inverse_1 = matrix.inverse = inverse$1;
matrix.linearDependencies = linearDependencies;
var pseudoInverse_1 = matrix.pseudoInverse = pseudoInverse$1;
matrix.solve = solve;
matrix.wrap = wrap;

const EigenvalueDecomposition = EigenvalueDecomposition_1;
const Matrix$1 = Matrix_1;
const SVD = SVD$1;
const SingularValueDecomposition = SingularValueDecomposition_1;
const WrapperMatrix1D = WrapperMatrix1D_1;
var Matrix = _default.Matrix ? _default.Matrix : Matrix_1;
const determinant = determinant_1;
const inverse = inverse_1;
const pseudoInverse = pseudoInverse_1;

/**
 * Compute the centroid of a set of points.
 *
 * @param points - Points to process as a 3xN matrix. Third dimension must be padded with ones.
 * @returns The centroid.
 */
function getCentroid(points) {
  let result = new Matrix(3, 1);
  const nbPoints = points.columns;
  let xSum = 0;
  let ySum = 0;
  for (let i = 0; i < nbPoints; i++) {
    xSum += points.get(0, i);
    ySum += points.get(1, i);
  }
  result.set(0, 0, xSum / nbPoints);
  result.set(1, 0, ySum / nbPoints);
  return result;
}

/**
 * Get best rotation and translation of source points to destination points.
 * Based on {@link https://nghiaho.com/?page_id=671}
 *
 * @param source - Source points as a 3xN matrix. Third dimension must be padded with ones.
 * @param destination - Destination points as a 3xN matrix. Third dimension must be padded with ones.
 * @returns The affine transformation.
 */
function getAffineTransform$1(source, destination) {
  if (source.columns !== destination.columns) {
    throw new Error('Source and destination matrices should have same dimensions (same number of points).');
  }
  if (source.columns < 2) {
    throw new Error('Matrices should contain at least two points for the algorithm to run properly.');
  }
  const sourceCentroid = getCentroid(source);
  const destinationCentroid = getCentroid(destination);
  const translatedSource = source.clone().subColumnVector(sourceCentroid);
  const translatedDestination = destination.clone().subColumnVector(destinationCentroid);
  // computing scale
  let ratioSum = 0;
  const nbPoints = source.columns;
  for (let i = 0; i < nbPoints; i++) {
    const sourcePoint = translatedSource.getColumn(i);
    const destinationPoint = translatedDestination.getColumn(i);
    ratioSum += getDistanceToOrigin(destinationPoint) / getDistanceToOrigin(sourcePoint);
  }
  const scale = ratioSum / nbPoints;
  const scaledSource = Matrix.mul(translatedSource, scale);
  // computing rotation
  const covarianceMatrix = scaledSource.mmul(translatedDestination.transpose());
  const svd = new SingularValueDecomposition(covarianceMatrix);
  const U = svd.leftSingularVectors;
  const V = svd.rightSingularVectors;
  let rotation = V.mmul(U.transpose());
  if (determinant(rotation) < 0) {
    const newV = V.mulColumn(2, -1);
    rotation = newV.mmul(U.transpose());
  }
  let angleDegrees = Math.atan2(rotation.get(1, 0), rotation.get(0, 0)) * 180 / Math.PI;
  if (angleDegrees === -180) {
    angleDegrees = 180;
  }
  // computing translation
  const translation = Matrix.sub(destinationCentroid, Matrix.mul(rotation.mmul(sourceCentroid), scale));
  return {
    translation: {
      x: translation.get(0, 0),
      y: translation.get(1, 0)
    },
    rotation: angleDegrees,
    scale
  };
}
function getDistanceToOrigin(point) {
  return Math.hypot(point[0], point[1]);
}

var medianQuickselect_min = {exports: {}};

(function (module) {
  (function () {
    function a(d) {
      for (var e = 0, f = d.length - 1, g = void 0, h = void 0, i = void 0, j = c(e, f); true;) {
        if (f <= e) return d[j];
        if (f == e + 1) return d[e] > d[f] && b(d, e, f), d[j];
        for (g = c(e, f), d[g] > d[f] && b(d, g, f), d[e] > d[f] && b(d, e, f), d[g] > d[e] && b(d, g, e), b(d, g, e + 1), h = e + 1, i = f; true;) {
          do h++; while (d[e] > d[h]);
          do i--; while (d[i] > d[e]);
          if (i < h) break;
          b(d, h, i);
        }
        b(d, e, i), i <= j && (e = h), i >= j && (f = i - 1);
      }
    }
    var b = function b(d, e, f) {
        var _ref;
        return _ref = [d[f], d[e]], d[e] = _ref[0], d[f] = _ref[1], _ref;
      },
      c = function c(d, e) {
        return ~~((d + e) / 2);
      };
    module.exports ? module.exports = a : window.median = a;
  })();
})(medianQuickselect_min);
var medianQuickselect_minExports = medianQuickselect_min.exports;
var quickMedian = /*@__PURE__*/getDefaultExportFromCjs(medianQuickselect_minExports);

function median$1(input) {
  if (!isAnyArray$1(input)) {
    throw new TypeError('input must be an array');
  }
  if (input.length === 0) {
    throw new TypeError('input must not be empty');
  }
  return quickMedian(input.slice());
}

const LOOP$1 = 8;
const FLOAT_MUL$1 = 1 / 16777216;
const sh1$1 = 15;
const sh2$1 = 18;
const sh3$1 = 11;
function multiply_uint32(n, m) {
  n >>>= 0;
  m >>>= 0;
  const nlo = n & 0xffff;
  const nhi = n - nlo;
  return (nhi * m >>> 0) + nlo * m >>> 0;
}
let XSadd$1 = class XSadd {
  constructor(seed = Date.now()) {
    this.state = new Uint32Array(4);
    this.init(seed);
    this.random = this.getFloat.bind(this);
  }
  /**
   * Returns a 32-bit integer r (0 <= r < 2^32)
   */
  getUint32() {
    this.nextState();
    return this.state[3] + this.state[2] >>> 0;
  }
  /**
   * Returns a floating point number r (0.0 <= r < 1.0)
   */
  getFloat() {
    return (this.getUint32() >>> 8) * FLOAT_MUL$1;
  }
  init(seed) {
    if (!Number.isInteger(seed)) {
      throw new TypeError('seed must be an integer');
    }
    this.state[0] = seed;
    this.state[1] = 0;
    this.state[2] = 0;
    this.state[3] = 0;
    for (let i = 1; i < LOOP$1; i++) {
      this.state[i & 3] ^= i + multiply_uint32(1812433253, this.state[i - 1 & 3] ^ this.state[i - 1 & 3] >>> 30 >>> 0) >>> 0;
    }
    this.periodCertification();
    for (let i = 0; i < LOOP$1; i++) {
      this.nextState();
    }
  }
  periodCertification() {
    if (this.state[0] === 0 && this.state[1] === 0 && this.state[2] === 0 && this.state[3] === 0) {
      this.state[0] = 88; // X
      this.state[1] = 83; // S
      this.state[2] = 65; // A
      this.state[3] = 68; // D
    }
  }
  nextState() {
    let t = this.state[0];
    t ^= t << sh1$1;
    t ^= t >>> sh2$1;
    t ^= this.state[3] << sh3$1;
    this.state[0] = this.state[1];
    this.state[1] = this.state[2];
    this.state[2] = this.state[3];
    this.state[3] = t;
  }
};

const PROB_TOLERANCE = 0.00000001;
function randomChoice(values, options = {}, random = Math.random) {
  const {
    size = 1,
    replace = false,
    probabilities
  } = options;
  let valuesArr;
  let cumSum;
  if (typeof values === 'number') {
    valuesArr = getArray(values);
  } else {
    valuesArr = values.slice();
  }
  if (probabilities) {
    if (!replace) {
      throw new Error('choice with probabilities and no replacement is not implemented');
    }
    // check input is sane
    if (probabilities.length !== valuesArr.length) {
      throw new Error('the length of probabilities option should be equal to the number of choices');
    }
    cumSum = [probabilities[0]];
    for (let i = 1; i < probabilities.length; i++) {
      cumSum[i] = cumSum[i - 1] + probabilities[i];
    }
    if (Math.abs(1 - cumSum[cumSum.length - 1]) > PROB_TOLERANCE) {
      throw new Error(`probabilities should sum to 1, but instead sums to ${cumSum[cumSum.length - 1]}`);
    }
  }
  if (replace === false && size > valuesArr.length) {
    throw new Error('size option is too large');
  }
  const result = [];
  for (let i = 0; i < size; i++) {
    const index = randomIndex(valuesArr.length, random, cumSum);
    result.push(valuesArr[index]);
    if (!replace) {
      valuesArr.splice(index, 1);
    }
  }
  return result;
}
function getArray(n) {
  const arr = [];
  for (let i = 0; i < n; i++) {
    arr.push(i);
  }
  return arr;
}
function randomIndex(n, random, cumSum) {
  const rand = random();
  if (!cumSum) {
    return Math.floor(rand * n);
  } else {
    let idx = 0;
    while (rand > cumSum[idx]) {
      idx++;
    }
    return idx;
  }
}

// tslint:disable-next-line
/**
 * @classdesc Random class
 */
class Random {
  /**
   * @param [seedOrRandom=Math.random] - Control the random number generator used by the Random class instance. Pass a random number generator function with a uniform distribution over the half-open interval [0, 1[. If seed will pass it to ml-xsadd to create a seeded random number generator. If undefined will use Math.random.
   */
  constructor(seedOrRandom = Math.random) {
    if (typeof seedOrRandom === 'number') {
      const xsadd = new XSadd$1(seedOrRandom);
      this.randomGenerator = xsadd.random;
    } else {
      this.randomGenerator = seedOrRandom;
    }
  }
  choice(values, options) {
    if (typeof values === 'number') {
      return randomChoice(values, options, this.randomGenerator);
    }
    return randomChoice(values, options, this.randomGenerator);
  }
  /**
   * Draw a random number from a uniform distribution on [0,1)
   * @return The random number
   */
  random() {
    return this.randomGenerator();
  }
  /**
   * Draw a random integer from a uniform distribution on [low, high). If only low is specified, the number is drawn on [0, low)
   * @param low - The lower bound of the uniform distribution interval.
   * @param high - The higher bound of the uniform distribution interval.
   */
  randInt(low, high) {
    if (high === undefined) {
      high = low;
      low = 0;
    }
    return low + Math.floor(this.randomGenerator() * (high - low));
  }
  /**
   * Draw several random number from a uniform distribution on [0, 1)
   * @param size - The number of number to draw
   * @return - The list of drawn numbers.
   */
  randomSample(size) {
    const result = [];
    for (let i = 0; i < size; i++) {
      result.push(this.random());
    }
    return result;
  }
}

/**
 * Get the minimal number of iterations of the RANSAC algorithm
 * required to have the given probability of having found the best model.
 *
 * @param probability - Desired probability (between 0 and 1).
 * @param outliersFraction - The estimated fraction of the data that is outliers (from 0 to 1).
 * @param sampleSize - The sample size for the RANSAC algoritm (number of values used for each random test).
 * @returns The minimal number of iterations.
 */
function getNbIterations(probability, outliersFraction, sampleSize) {
  const value = Math.log10(1 - probability) / Math.log10(1 - (1 - outliersFraction) ** sampleSize);
  return Math.ceil(value);
}

/**
 * RANdom SAmple Consensus algorithm: find the best model matching the data and ignoring outliers.
 *
 * @see https://en.wikipedia.org/wiki/Random_sample_consensus
 * @param source - The source data.
 * @param destination - The destination data.
 * @param options - RANSAC options.
 * @returns The model parameters and the corresponding inliers.
 */
function ransac(source, destination, options) {
  let minNbInliers = 0;
  if (options.minNbInliers) {
    minNbInliers = getNbValues(options.minNbInliers, source.length);
  } else {
    minNbInliers = source.length;
  }
  const {
    sampleSize = 2,
    threshold = 1,
    fitFunction,
    distanceFunction,
    modelFunction,
    seed = undefined
  } = options;
  if (source.length !== destination.length) {
    throw new Error('source and destination data should have the same length');
  }
  let maxNbIterations;
  if ('outliersFraction' in options) {
    const {
      stopProbabilty = 0.99
    } = options;
    maxNbIterations = getNbIterations(stopProbabilty, options.outliersFraction, sampleSize);
  } else {
    maxNbIterations = options.maxNbIterations ? options.maxNbIterations : 100;
  }
  let iteration = 0;
  let bestNbInliers = 0;
  let bestInliers = [];
  let bestModelParameters = [];
  let bestError = 0;
  let seeds = [];
  if (seed !== undefined) {
    seeds = new Random(seed).choice(maxNbIterations, {
      size: maxNbIterations
    });
  }
  while (iteration < maxNbIterations) {
    iteration++;
    let indices;
    if (seed !== undefined) {
      indices = new Random(seeds[iteration]).choice(source.length, {
        size: sampleSize
      });
    } else {
      indices = new Random().choice(source.length, {
        size: sampleSize
      });
    }
    const srcSubset = [];
    const dstSubset = [];
    for (let i of indices) {
      srcSubset.push(source[i]);
      dstSubset.push(destination[i]);
    }
    const modelParameters = fitFunction(srcSubset, dstSubset);
    const model = modelFunction(modelParameters);
    let predictedDestination = [];
    for (let value of source) {
      predictedDestination.push(model(value));
    }
    let nbInliers = 0;
    let inliers = [];
    let distances = [];
    let error = 0;
    for (let i = 0; i < destination.length; i++) {
      if (indices.includes(i)) {
        nbInliers++;
        inliers.push(i);
        continue;
      }
      const distance = distanceFunction(destination[i], predictedDestination[i]);
      distances.push(distance);
      if (distance < threshold) {
        nbInliers++;
        inliers.push(i);
      }
    }
    error = median$1(distances);
    if (nbInliers > bestNbInliers) {
      bestNbInliers = nbInliers;
      bestInliers = inliers; // potential bug with pointers?
      bestModelParameters = modelParameters;
      bestError = error;
      if (nbInliers >= minNbInliers) {
        return {
          modelParameters,
          inliers,
          nbIterations: iteration,
          error
        };
      }
    }
  }
  return {
    modelParameters: bestModelParameters,
    inliers: bestInliers,
    nbIterations: maxNbIterations,
    error: bestError
  };
}
function getNbValues(value, size) {
  if (Number.isInteger(value)) {
    return value;
  } else {
    return Math.ceil(value * size);
  }
}

/**
 * Compute the squared distance from each keypoint to the other ones.
 * @param keypoints - Keypoints to process.
 * @returns Distance matrix.
 */
function getDistanceMatrix(keypoints) {
  const size = keypoints.length;
  const matrix = new Array(size);
  for (let i = 0; i < size; i++) {
    matrix[i] = new Float64Array(size).fill(0);
  }
  for (let i = 0; i < size; i++) {
    const point1 = keypoints[i].origin;
    for (let j = i; j < size; j++) {
      if (i === j) {
        matrix[i][j] = 0;
      }
      const point2 = keypoints[j].origin;
      const squaredDistance = (point1.row - point2.row) ** 2 + (point1.column - point2.column) ** 2;
      matrix[i][j] = squaredDistance;
      matrix[j][i] = squaredDistance;
    }
  }
  return matrix;
}

/**
 * Find all keypoints within radius from the current keypoint.
 * @param keypoints - Keypoints to process.
 * @param radius - Radius in which the surrounding keypoints should be.
 * @returns Array of keypoints within radius for each of the keypoints.
 */
function getKeypointsInRadius(keypoints, radius) {
  const size = keypoints.length;
  const matrix = getDistanceMatrix(keypoints);
  const squaredRadius = radius ** 2;
  const result = [];
  for (let i = 0; i < size; i++) {
    const currentIndices = [];
    for (let j = 0; j < size; j++) {
      if (i === j) continue;
      if (matrix[i][j] <= squaredRadius) {
        currentIndices.push(j);
      }
    }
    result.push(currentIndices);
  }
  return result;
}

/**
 * Return the best keypoints within the given radius in pixels.
 * @param keypoints - Keypoints to process.
 * @param radius - Minimum distance in pixels between two keypoints.
 * @returns The filtered keypoints.
 */
function getBestKeypointsInRadius(keypoints, radius = 5) {
  const size = keypoints.length;
  const keypointsInRadius = getKeypointsInRadius(keypoints, radius);
  const toIgnore = new Uint8Array(size).fill(0);
  for (let i = 0; i < size; i++) {
    const keypoint = keypoints[i];
    for (const secondKeypointIndex of keypointsInRadius[i]) {
      const secondKeypoint = keypoints[secondKeypointIndex];
      if (keypoint.score < secondKeypoint.score) {
        toIgnore[i] = 1;
        continue;
      }
    }
  }
  const result = [];
  for (let i = 0; i < size; i++) {
    if (!toIgnore[i]) {
      result.push(keypoints[i]);
    }
  }
  return result;
}

/**
 * Calculates a new point that is the difference p1 - p2.
 * @param p1 - First point.
 * @param p2 - Second Point.
 * @returns Difference between the two points.
 */
function difference(p1, p2) {
  return {
    column: p1.column - p2.column,
    row: p1.row - p2.row
  };
}
/**
 * Calculates a new point that is the sum p1 + p2.
 * @param p1 - First point.
 * @param p2 - Second Point.
 * @returns Sum of the two points.
 */
function sum$1(p1, p2) {
  return {
    column: p1.column + p2.column,
    row: p1.row + p2.row
  };
}
/**
 * Normalize a point (more precisely the vector from the origin to the point).
 * @param point - Point to normalize.
 * @returns - Normalized point.
 */
function normalize(point) {
  const length = Math.hypot(point.column, point.row);
  return {
    column: point.column / length,
    row: point.row / length
  };
}
/**
 * Rotate an array of points by an angle in radians.
 * The rotation is clockwise and the reference is (0,0).
 * @param radians - Angle in radians.
 * @param points - Source points.
 * @returns The points after rotation.
 */
function rotate$1(radians, points) {
  const results = [];
  const cos = Math.cos(radians);
  const sin = Math.sin(radians);
  for (const point of points) {
    results.push({
      column: cos * point.column - sin * point.row,
      row: sin * point.column + cos * point.row
    });
  }
  return results;
}
/**
 * Sort an array of points by column then row.
 * @param points - Array of points to sort.
 * @returns Sorted points.
 */
function sortByColumnRow(points) {
  const sortedPoints = points.slice();
  sortedPoints.sort((point1, point2) => {
    if (point1.column < point2.column) return -1;
    if (point1.column > point2.column) return 1;
    return point1.row - point2.row;
  });
  return sortedPoints;
}

/**
 * The angle in radians of a vector relatively to the x axis.
 * The angle is positive in the clockwise direction.
 * This is an optimized version because it assumes that one of
 * the points is on the line y = 0.
 * @param p1 - First point.
 * @param p2 - Second point.
 * @returns Rotation angle in radians to make the line horizontal. -π <= angle <= π.
 */
function getAngle(p1, p2) {
  const diff = difference(p2, p1);
  const vector = normalize(diff);
  const angle = Math.acos(vector.column);
  if (vector.row < 0) return -angle;
  return angle;
}
/**
 * Compute the clockwise angle in radians between the x-axis and the segment p1-p2.
 * @param p1 - First point.
 * @param p2 - Second point.
 * @returns Clockwise angle between x-axis and the segment.
 */
function getClockwiseAngle(p1, p2) {
  const diff = difference(p2, p1);
  const vector = normalize(diff);
  const atan = -Math.atan(vector.row / vector.column);
  if (vector.column < 0) {
    if (vector.row < 0) {
      return atan - Math.PI;
    } else {
      return atan + Math.PI;
    }
  } else {
    return atan;
  }
}

/**
 * Convert radians to degrees.
 * @param radians - Angle in radians.
 * @returns  Angle in degrees.
 */
function toDegrees(radians) {
  return radians * 180 / Math.PI;
}

/**
 * Compute the radius of the circle of given size.
 * @param size - Size of the circle.
 * @returns The radius.
 */
function getRadius(size) {
  if (size % 2 !== 1 || size < 0) {
    throw new RangeError('size must be positive and odd');
  }
  return (size - 1) / 2;
}

/**
 * Check that a point is not too close to the border of the image.
 * @param image - Image to process.
 * @param point - The interest point.
 * @param distance - The minimum distance to the border required.
 * @returns Whether the point is far enough from the border.
 */
function checkBorderDistance(image, point, distance) {
  return point.column >= distance && point.row >= distance && image.width - point.column > distance && image.height - point.row > distance;
}

const t$2 = Symbol.for("@ts-pattern/matcher"),
  e$2 = Symbol.for("@ts-pattern/isVariadic"),
  n$2 = "@ts-pattern/anonymous-select-key",
  r$2 = t => Boolean(t && "object" == typeof t),
  i$3 = e => e && !!e[t$2],
  o$2 = (n, s, c) => {
    if (i$3(n)) {
      const e = n[t$2](),
        {
          matched: r,
          selections: i
        } = e.match(s);
      return r && i && Object.keys(i).forEach(t => c(t, i[t])), r;
    }
    if (r$2(n)) {
      if (!r$2(s)) return false;
      if (Array.isArray(n)) {
        if (!Array.isArray(s)) return false;
        let t = [],
          r = [],
          u = [];
        for (const o of n.keys()) {
          const s = n[o];
          i$3(s) && s[e$2] ? u.push(s) : u.length ? r.push(s) : t.push(s);
        }
        if (u.length) {
          if (u.length > 1) throw new Error("Pattern error: Using `...P.array(...)` several times in a single pattern is not allowed.");
          if (s.length < t.length + r.length) return false;
          const e = s.slice(0, t.length),
            n = 0 === r.length ? [] : s.slice(-r.length),
            i = s.slice(t.length, 0 === r.length ? Infinity : -r.length);
          return t.every((t, n) => o$2(t, e[n], c)) && r.every((t, e) => o$2(t, n[e], c)) && (0 === u.length || o$2(u[0], i, c));
        }
        return n.length === s.length && n.every((t, e) => o$2(t, s[e], c));
      }
      return Reflect.ownKeys(n).every(e => {
        const r = n[e];
        return (e in s || i$3(u = r) && "optional" === u[t$2]().matcherType) && o$2(r, s[e], c);
        var u;
      });
    }
    return Object.is(s, n);
  },
  s$1 = e => {
    var n, o, u;
    return r$2(e) ? i$3(e) ? null != (n = null == (o = (u = e[t$2]()).getSelectionKeys) ? void 0 : o.call(u)) ? n : [] : Array.isArray(e) ? c$1(e, s$1) : c$1(Object.values(e), s$1) : [];
  },
  c$1 = (t, e) => t.reduce((t, n) => t.concat(e(n)), []);
function u$2(...t) {
  if (1 === t.length) {
    const [e] = t;
    return t => o$2(e, t, () => {});
  }
  if (2 === t.length) {
    const [e, n] = t;
    return o$2(e, n, () => {});
  }
  throw new Error(`isMatching wasn't given the right number of arguments: expected 1 or 2, received ${t.length}.`);
}
function a$2(t) {
  return Object.assign(t, {
    optional: () => h$2(t),
    and: e => d$1(t, e),
    or: e => y$1(t, e),
    select: e => void 0 === e ? v$1(t) : v$1(e, t)
  });
}
function l$2(t) {
  return Object.assign((t => Object.assign(t, {
    [Symbol.iterator]() {
      let n = 0;
      const r = [{
        value: Object.assign(t, {
          [e$2]: true
        }),
        done: false
      }, {
        done: true,
        value: void 0
      }];
      return {
        next: () => {
          var t;
          return null != (t = r[n++]) ? t : r.at(-1);
        }
      };
    }
  }))(t), {
    optional: () => l$2(h$2(t)),
    select: e => l$2(void 0 === e ? v$1(t) : v$1(e, t))
  });
}
function h$2(e) {
  return a$2({
    [t$2]: () => ({
      match: t => {
        let n = {};
        const r = (t, e) => {
          n[t] = e;
        };
        return void 0 === t ? (s$1(e).forEach(t => r(t, void 0)), {
          matched: true,
          selections: n
        }) : {
          matched: o$2(e, t, r),
          selections: n
        };
      },
      getSelectionKeys: () => s$1(e),
      matcherType: "optional"
    })
  });
}
const f$1 = (t, e) => {
    for (const n of t) if (!e(n)) return false;
    return true;
  },
  g$1 = (t, e) => {
    for (const [n, r] of t.entries()) if (!e(r, n)) return false;
    return true;
  },
  m$1 = (t, e) => {
    const n = Reflect.ownKeys(t);
    for (const r of n) if (!e(r, t[r])) return false;
    return true;
  };
function d$1(...e) {
  return a$2({
    [t$2]: () => ({
      match: t => {
        let n = {};
        const r = (t, e) => {
          n[t] = e;
        };
        return {
          matched: e.every(e => o$2(e, t, r)),
          selections: n
        };
      },
      getSelectionKeys: () => c$1(e, s$1),
      matcherType: "and"
    })
  });
}
function y$1(...e) {
  return a$2({
    [t$2]: () => ({
      match: t => {
        let n = {};
        const r = (t, e) => {
          n[t] = e;
        };
        return c$1(e, s$1).forEach(t => r(t, void 0)), {
          matched: e.some(e => o$2(e, t, r)),
          selections: n
        };
      },
      getSelectionKeys: () => c$1(e, s$1),
      matcherType: "or"
    })
  });
}
function p$2(e) {
  return {
    [t$2]: () => ({
      match: t => ({
        matched: Boolean(e(t))
      })
    })
  };
}
function v$1(...e) {
  const r = "string" == typeof e[0] ? e[0] : void 0,
    i = 2 === e.length ? e[1] : "string" == typeof e[0] ? void 0 : e[0];
  return a$2({
    [t$2]: () => ({
      match: t => {
        let e = {
          [null != r ? r : n$2]: t
        };
        return {
          matched: void 0 === i || o$2(i, t, (t, n) => {
            e[t] = n;
          }),
          selections: e
        };
      },
      getSelectionKeys: () => [null != r ? r : n$2].concat(void 0 === i ? [] : s$1(i))
    })
  });
}
function b$2(t) {
  return true;
}
function w$2(t) {
  return "number" == typeof t;
}
function S$1(t) {
  return "string" == typeof t;
}
function j$1(t) {
  return "bigint" == typeof t;
}
const K = a$2(p$2(b$2)),
  O = a$2(p$2(b$2)),
  E = K,
  x$2 = t => Object.assign(a$2(t), {
    startsWith: e => {
      return x$2(d$1(t, (n = e, p$2(t => S$1(t) && t.startsWith(n)))));
      var n;
    },
    endsWith: e => {
      return x$2(d$1(t, (n = e, p$2(t => S$1(t) && t.endsWith(n)))));
      var n;
    },
    minLength: e => x$2(d$1(t, (t => p$2(e => S$1(e) && e.length >= t))(e))),
    length: e => x$2(d$1(t, (t => p$2(e => S$1(e) && e.length === t))(e))),
    maxLength: e => x$2(d$1(t, (t => p$2(e => S$1(e) && e.length <= t))(e))),
    includes: e => {
      return x$2(d$1(t, (n = e, p$2(t => S$1(t) && t.includes(n)))));
      var n;
    },
    regex: e => {
      return x$2(d$1(t, (n = e, p$2(t => S$1(t) && Boolean(t.match(n))))));
      var n;
    }
  }),
  A = x$2(p$2(S$1)),
  N$1 = t => Object.assign(a$2(t), {
    between: (e, n) => N$1(d$1(t, ((t, e) => p$2(n => w$2(n) && t <= n && e >= n))(e, n))),
    lt: e => N$1(d$1(t, (t => p$2(e => w$2(e) && e < t))(e))),
    gt: e => N$1(d$1(t, (t => p$2(e => w$2(e) && e > t))(e))),
    lte: e => N$1(d$1(t, (t => p$2(e => w$2(e) && e <= t))(e))),
    gte: e => N$1(d$1(t, (t => p$2(e => w$2(e) && e >= t))(e))),
    int: () => N$1(d$1(t, p$2(t => w$2(t) && Number.isInteger(t)))),
    finite: () => N$1(d$1(t, p$2(t => w$2(t) && Number.isFinite(t)))),
    positive: () => N$1(d$1(t, p$2(t => w$2(t) && t > 0))),
    negative: () => N$1(d$1(t, p$2(t => w$2(t) && t < 0)))
  }),
  P = N$1(p$2(w$2)),
  k$1 = t => Object.assign(a$2(t), {
    between: (e, n) => k$1(d$1(t, ((t, e) => p$2(n => j$1(n) && t <= n && e >= n))(e, n))),
    lt: e => k$1(d$1(t, (t => p$2(e => j$1(e) && e < t))(e))),
    gt: e => k$1(d$1(t, (t => p$2(e => j$1(e) && e > t))(e))),
    lte: e => k$1(d$1(t, (t => p$2(e => j$1(e) && e <= t))(e))),
    gte: e => k$1(d$1(t, (t => p$2(e => j$1(e) && e >= t))(e))),
    positive: () => k$1(d$1(t, p$2(t => j$1(t) && t > 0))),
    negative: () => k$1(d$1(t, p$2(t => j$1(t) && t < 0)))
  }),
  T = k$1(p$2(j$1)),
  B = a$2(p$2(function (t) {
    return "boolean" == typeof t;
  })),
  _ = a$2(p$2(function (t) {
    return "symbol" == typeof t;
  })),
  W = a$2(p$2(function (t) {
    return null == t;
  })),
  $$1 = a$2(p$2(function (t) {
    return null != t;
  }));
var z = {
  __proto__: null,
  matcher: t$2,
  optional: h$2,
  array: function (...e) {
    return l$2({
      [t$2]: () => ({
        match: t => {
          if (!Array.isArray(t)) return {
            matched: false
          };
          if (0 === e.length) return {
            matched: true
          };
          const n = e[0];
          let r = {};
          if (0 === t.length) return s$1(n).forEach(t => {
            r[t] = [];
          }), {
            matched: true,
            selections: r
          };
          const i = (t, e) => {
            r[t] = (r[t] || []).concat([e]);
          };
          return {
            matched: t.every(t => o$2(n, t, i)),
            selections: r
          };
        },
        getSelectionKeys: () => 0 === e.length ? [] : s$1(e[0])
      })
    });
  },
  set: function (...e) {
    return a$2({
      [t$2]: () => ({
        match: t => {
          if (!(t instanceof Set)) return {
            matched: false
          };
          let n = {};
          if (0 === t.size) return {
            matched: true,
            selections: n
          };
          if (0 === e.length) return {
            matched: true
          };
          const r = (t, e) => {
              n[t] = (n[t] || []).concat([e]);
            },
            i = e[0];
          return {
            matched: f$1(t, t => o$2(i, t, r)),
            selections: n
          };
        },
        getSelectionKeys: () => 0 === e.length ? [] : s$1(e[0])
      })
    });
  },
  map: function (...e) {
    return a$2({
      [t$2]: () => ({
        match: t => {
          if (!(t instanceof Map)) return {
            matched: false
          };
          let n = {};
          if (0 === t.size) return {
            matched: true,
            selections: n
          };
          const r = (t, e) => {
            n[t] = (n[t] || []).concat([e]);
          };
          if (0 === e.length) return {
            matched: true
          };
          var i;
          if (1 === e.length) throw new Error(`\`P.map\` wasn't given enough arguments. Expected (key, value), received ${null == (i = e[0]) ? void 0 : i.toString()}`);
          const [s, c] = e;
          return {
            matched: g$1(t, (t, e) => {
              const n = o$2(s, e, r),
                i = o$2(c, t, r);
              return n && i;
            }),
            selections: n
          };
        },
        getSelectionKeys: () => 0 === e.length ? [] : [...s$1(e[0]), ...s$1(e[1])]
      })
    });
  },
  record: function (...e) {
    return a$2({
      [t$2]: () => ({
        match: t => {
          if (null === t || "object" != typeof t || Array.isArray(t)) return {
            matched: false
          };
          var n;
          if (0 === e.length) throw new Error(`\`P.record\` wasn't given enough arguments. Expected (value) or (key, value), received ${null == (n = e[0]) ? void 0 : n.toString()}`);
          let r = {};
          const i = (t, e) => {
              r[t] = (r[t] || []).concat([e]);
            },
            [s, c] = 1 === e.length ? [A, e[0]] : e;
          return {
            matched: m$1(t, (t, e) => {
              const n = "string" != typeof t || Number.isNaN(Number(t)) ? null : Number(t),
                r = null !== n && o$2(s, n, i),
                u = o$2(s, t, i),
                a = o$2(c, e, i);
              return (u || r) && a;
            }),
            selections: r
          };
        },
        getSelectionKeys: () => 0 === e.length ? [] : [...s$1(e[0]), ...s$1(e[1])]
      })
    });
  },
  intersection: d$1,
  union: y$1,
  not: function (e) {
    return a$2({
      [t$2]: () => ({
        match: t => ({
          matched: !o$2(e, t, () => {})
        }),
        getSelectionKeys: () => [],
        matcherType: "not"
      })
    });
  },
  when: p$2,
  select: v$1,
  any: K,
  unknown: O,
  _: E,
  string: A,
  number: P,
  bigint: T,
  boolean: B,
  symbol: _,
  nullish: W,
  nonNullable: $$1,
  instanceOf: function (t) {
    return a$2(p$2(function (t) {
      return e => e instanceof t;
    }(t)));
  },
  shape: function (t) {
    return a$2(p$2(u$2(t)));
  }
};
class I extends Error {
  constructor(t) {
    let e;
    try {
      e = JSON.stringify(t);
    } catch (n) {
      e = t;
    }
    super(`Pattern matching error: no pattern matches value ${e}`), this.input = void 0, this.input = t;
  }
}
const L = {
  matched: false,
  value: void 0
};
function M$2(t) {
  return new R(t, L);
}
class R {
  constructor(t, e) {
    this.input = void 0, this.state = void 0, this.input = t, this.state = e;
  }
  with(...t) {
    if (this.state.matched) return this;
    const e = t[t.length - 1],
      r = [t[0]];
    let i;
    3 === t.length && "function" == typeof t[1] ? i = t[1] : t.length > 2 && r.push(...t.slice(1, t.length - 1));
    let s = false,
      c = {};
    const u = (t, e) => {
        s = true, c[t] = e;
      },
      a = !r.some(t => o$2(t, this.input, u)) || i && !Boolean(i(this.input)) ? L : {
        matched: true,
        value: e(s ? n$2 in c ? c[n$2] : c : this.input, this.input)
      };
    return new R(this.input, a);
  }
  when(t, e) {
    if (this.state.matched) return this;
    const n = Boolean(t(this.input));
    return new R(this.input, n ? {
      matched: true,
      value: e(this.input, this.input)
    } : L);
  }
  otherwise(t) {
    return this.state.matched ? this.state.value : t(this.input);
  }
  exhaustive(t = F) {
    return this.state.matched ? this.state.value : t(this.input);
  }
  run() {
    return this.exhaustive();
  }
  returnType() {
    return this;
  }
  narrow() {
    return this;
  }
}
function F(t) {
  throw new I(t);
}

var index_umd$1 = {exports: {}};

var index_umd = index_umd$1.exports;
(function (module, exports$1) {
  (function (N, J) {
    J(exports$1) ;
  })(index_umd, function (N) {

    function J(f, a, o, t, e) {
      const h = Math.abs(o - f),
        r = f < o ? 1 : -1,
        l = -Math.abs(t - a),
        M = a < t ? 1 : -1;
      let i = h + l,
        n;
      for (;;) {
        if (e(f, a), n = 2 * i, n >= l) {
          if (f === o) break;
          i += l, f += r;
        }
        if (n <= h) {
          if (a === t) break;
          i += h, a += M;
        }
      }
    }
    function U(f, a, o, t, e) {
      const h = f < o ? 1 : -1,
        r = a < t ? 1 : -1;
      let l,
        M = Math.abs(o - f),
        i = Math.abs(t - a),
        n = M * M + i * i,
        c = n === 0 ? 1 : 1 / Math.sqrt(n);
      for (M *= c, i *= c, n = M - i;;) {
        if (e(f, a, Math.abs(n - (M + i)) >> 16), c = n, l = f, 2 * c >= -M) {
          if (f === o) break;
          c + i < 16711680 && e(f, a + r, c + i >> 16), n -= i, f += h;
        }
        if (2 * c <= i) {
          if (a === t) break;
          M - c < 16711680 && e(l + h, a, M - c >> 16), n += M, a += r;
        }
      }
    }
    function w(f, a, o, t, e, h) {
      let r = Math.abs(o - f),
        l = f < o ? 1 : -1,
        M = Math.abs(t - a),
        i = a < t ? 1 : -1,
        n = r - M,
        c,
        q,
        d,
        b = r + M == 0 ? 1 : Math.sqrt(r * r + M * M);
      for (e = (e + 1) / 2;;) {
        if (h(f, a, Math.max(0, 255 * (Math.abs(n - r + M) / b - e + 1))), c = n, q = f, 2 * c >= -r) {
          for (c += M, d = a; c < b * e && (t != d || r > M); c += r) h(f, d += i, Math.max(0, 255 * (Math.abs(c) / b - e + 1)));
          if (f == o) break;
          c = n, n -= M, f += l;
        }
        if (2 * c <= M) {
          for (c = r - c; c < b * e && (o != q || r < M); c += M) h(q += l, a, Math.max(0, 255 * (Math.abs(c) / b - e + 1)));
          if (a == t) break;
          n += r, a += i;
        }
      }
    }
    function I(f, a = "assert error") {
      if (!f) throw new Error(a);
    }
    function P(f, a, o, t, e, h, r, l) {
      var M = f - 2 * o + e,
        i = a - 2 * t + h,
        n = f - o,
        c = a - t,
        q,
        d,
        b;
      I(r >= 0, "width is negative"), n * (e - o) > 0 && (c * (h - t) > 0 && Math.abs(n * i) > Math.abs(c * M) && (f = e, e = n + o, a = h, h = c + t), f == e || r == 1 ? d = (f - o) / M : (b = Math.sqrt(4 * r * r * (f - o) * (e - o) + (e - f) * (e - f)), o < f && (b = -b), d = (2 * r * (f - o) - f + e + b) / (2 * (1 - r) * (e - f))), b = 1 / (2 * d * (1 - d) * (r - 1) + 1), n = (d * d * (f - 2 * r * o + e) + 2 * d * (r * o - f) + f) * b, c = (d * d * (a - 2 * r * t + h) + 2 * d * (r * t - a) + a) * b, q = d * (r - 1) + 1, q *= q * b, r = ((1 - d) * (r - 1) + 1) * Math.sqrt(b), M = Math.floor(n + .5), i = Math.floor(c + .5), c = (n - f) * (t - a) / (o - f) + a, H(f, a, M, Math.floor(c + .5), M, i, q, l), c = (n - e) * (t - h) / (o - e) + h, t = Math.floor(c + .5), f = o = M, a = i), (a - t) * (h - t) > 0 && (a == h || r == 1 ? d = (a - t) / (a - 2 * t + h) : (b = Math.sqrt(4 * r * r * (a - t) * (h - t) + (h - a) * (h - a)), t < a && (b = -b), d = (2 * r * (a - t) - a + h + b) / (2 * (1 - r) * (h - a))), b = 1 / (2 * d * (1 - d) * (r - 1) + 1), n = (d * d * (f - 2 * r * o + e) + 2 * d * (r * o - f) + f) * b, c = (d * d * (a - 2 * r * t + h) + 2 * d * (r * t - a) + a) * b, q = d * (r - 1) + 1, q *= q * b, r = ((1 - d) * (r - 1) + 1) * Math.sqrt(b), M = Math.floor(n + .5), i = Math.floor(c + .5), n = (o - f) * (c - a) / (t - a) + f, H(f, a, Math.floor(n + .5), i, M, i, q, l), n = (o - e) * (c - h) / (t - h) + e, o = Math.floor(n + .5), f = M, a = t = i), H(f, a, o, t, e, h, r * r, l);
    }
    function H(f, a, o, t, e, h, r, l) {
      var M = e - o,
        i = h - t,
        n = f - e,
        c = a - h,
        q = f - o,
        d = a - t,
        b = q * i + d * M,
        s = q * i - d * M,
        u;
      if (I(q * M <= 0 && d * i <= 0, "sign of gradient must not change"), s != 0 && r > 0) {
        if (M * M + i * i > q * q + d * d && (e = f, f -= n, h = a, a -= c, s = -s), q = 2 * (4 * r * M * q + n * n), d = 2 * (4 * r * i * d + c * c), M = f < e ? 1 : -1, i = a < h ? 1 : -1, b = -2 * M * i * (2 * r * b + n * c), s * M * i < 0 && (q = -q, d = -d, b = -b, s = -s), n = 4 * r * (o - f) * i * s + q / 2 + b, c = 4 * r * (a - t) * M * s + d / 2 + b, r < .5 && (c > b || n < b)) {
          s = (r + 1) / 2, r = Math.sqrt(r), b = 1 / (r + 1), M = Math.floor((f + 2 * r * o + e) * b / 2 + .5), i = Math.floor((a + 2 * r * t + h) * b / 2 + .5), n = Math.floor((r * o + f) * b + .5), c = Math.floor((t * r + a) * b + .5), H(f, a, n, c, M, i, s, l), n = Math.floor((r * o + e) * b + .5), c = Math.floor((t * r + h) * b + .5), H(M, i, n, c, e, h, s, l);
          return;
        }
        u = n + c - b;
        do {
          if (l(f, a), f == e && a == h) return;
          o = 2 * u > c ? 1 : 0, t = 2 * (u + d) < -c ? 1 : 0, (2 * u < n || t) && (a += i, c += b, u += n += q), (2 * u > n || o) && (f += M, n += b, u += c += d);
        } while (c <= b && n >= b);
      }
      J(f, a, e, h, l);
    }
    function V(f, a, o, t, e, h, r, l) {
      var M = e - o,
        i = h - t,
        n = f - e,
        c = a - h,
        q = f - o,
        d = a - t,
        b = q * i + d * M,
        s = q * i - d * M,
        u,
        z,
        j;
      if (I(q * M <= 0 && d * i <= 0), s != 0 && r > 0) {
        if (M * M + i * i > q * q + d * d && (e = f, f -= n, h = a, a -= c, s = -s), q = 2 * (4 * r * M * q + n * n), d = 2 * (4 * r * i * d + c * c), M = f < e ? 1 : -1, i = a < h ? 1 : -1, b = -2 * M * i * (2 * r * b + n * c), s * M * i < 0 && (q = -q, d = -d, s = -s, b = -b), n = 4 * r * (o - f) * i * s + q / 2 + b, c = 4 * r * (a - t) * M * s + d / 2 + b, r < .5 && c > n) return s = (r + 1) / 2, r = Math.sqrt(r), b = 1 / (r + 1), M = Math.floor((f + 2 * r * o + e) * b / 2 + .5), i = Math.floor((a + 2 * r * t + h) * b / 2 + .5), n = Math.floor((r * o + f) * b + .5), c = Math.floor((t * r + a) * b + .5), V(f, a, n, c, M, i, s, l), n = Math.floor((r * o + e) * b + .5), c = Math.floor((t * r + h) * b + .5), V(M, i, n, c, e, h, s, l);
        u = n + c - b;
        do {
          if (s = Math.min(n - b, b - c), z = Math.max(n - b, b - c), z += 2 * z * s * s / (4 * z * z + s * s), o = 255 * Math.abs(u - n - c + b) / z, o < 256 && l(f, a, o), j = 2 * u + c < 0) {
            if (a == h) return;
            n - u < z && l(f + M, a, 255 * Math.abs(n - u) / z);
          }
          if (2 * u + n > 0) {
            if (f == e) return;
            u - c < z && l(f, a + i, 255 * Math.abs(u - c) / z), f += M, n += b, u += c += d;
          }
          j && (a += i, c += b, u += n += q);
        } while (c < n);
      }
      U(f, a, e, h, l);
    }
    function y(f, a, o, t, e) {
      let h = -o,
        r = 0,
        l = t * t,
        M = h * (2 * l + h) + l;
      do e(f - h, a + r), e(f + h, a + r), e(f + h, a - r), e(f - h, a - r), l = 2 * M, l >= (h * 2 + 1) * t * t && (M += (++h * 2 + 1) * t * t), l <= (r * 2 + 1) * o * o && (M += (++r * 2 + 1) * o * o); while (h <= 0);
      for (; r++ < t;) e(f, a + r), e(f, a - r);
    }
    function x(f, a, o, t, e, h) {
      let r = o * o,
        l = t * t;
      const M = Math.sin(e);
      let i = (r - l) * M;
      r = Math.sqrt(r - i * M), l = Math.sqrt(l + i * M), o = r + .5, t = l + .5, i = i * o * t / (r * l), Y(f - o, a - t, f + o, a + t, 4 * i * Math.cos(e), h);
    }
    function Y(f, a, o, t, e, h) {
      let r = o - f,
        l = t - a,
        M = r * l;
      if (e === 0) return Z(f, a, o, t, h);
      M !== 0 && (M = (M - e) / (M + M)), I(M <= 1 && M >= 0, "limit angle to |zd|<=xd*yd"), r = Math.floor(r * M + .5), l = Math.floor(l * M + .5), H(f, a + l, f, a, f + r, a, 1 - M, h), H(f, a + l, f, t, o - r, t, M, h), H(o, t - l, o, t, o - r, t, 1 - M, h), H(o, t - l, o, a, f + r, a, M, h);
    }
    function Z(f, a, o, t, e) {
      let h = Math.abs(o - f),
        r = Math.abs(t - a),
        l = r & 1,
        M = 4 * (1 - h) * r * r,
        i = 4 * (l + 1) * h * h,
        n = M + i + l * h * h,
        c;
      f > o && (f = o, o += h), a > t && (a = t), a += (r + 1) / 2, t = a - l, h = 8 * h * h, l = 8 * r * r;
      do e(o, a), e(f, a), e(f, t), e(o, t), c = 2 * n, c <= i && (a++, t--, n += i += h), (c >= M || 2 * n > i) && (f++, o--, n += M += l); while (f <= o);
      for (; a - t <= r;) e(f - 1, a), e(o + 1, a++), e(f - 1, t), e(o + 1, t--);
    }
    function aa(f, a, o, t) {
      var e = -o,
        h = 0,
        r = 2 - 2 * o;
      do t(f - e, a + h), t(f - h, a - e), t(f + e, a - h), t(f + h, a + e), o = r, o <= h && (r += ++h * 2 + 1), (o > e || r > h) && (r += ++e * 2 + 1); while (e < 0);
    }
    function fa(f, a, o, t) {
      var e = -o,
        h = 0,
        r,
        l,
        M,
        i = 2 - 2 * o;
      o = 1 - i;
      do r = 255 * Math.abs(i - 2 * (e + h) - 2) / o, t(f - e, a + h, r), t(f - h, a - e, r), t(f + e, a - h, r), t(f + h, a + e, r), M = i, l = e, i + h > 0 && (r = 255 * (i - 2 * e - 1) / o, r < 256 && (t(f - e, a + h + 1, r), t(f - h - 1, a - e, r), t(f + e, a - h - 1, r), t(f + h + 1, a + e, r)), i += ++e * 2 + 1), M + l <= 0 && (r = 255 * (2 * h + 3 - M) / o, r < 256 && (t(f - l - 1, a + h, r), t(f - h, a - l - 1, r), t(f + l + 1, a - h, r), t(f + h, a + l + 1, r)), i += ++h * 2 + 1); while (e < 0);
    }
    function ta(f, a, o, t, e, h, r) {
      var l = f - o,
        M = a - t,
        i = f - 2 * o + e,
        n;
      l * (e - o) > 0 && (M * (h - t) > 0 && Math.abs((a - 2 * t + h) / i * l) > Math.abs(M) && (f = e, e = l + o, a = h, h = M + t), i = (f - o) / i, n = (1 - i) * ((1 - i) * a + 2 * i * t) + i * i * h, i = (f * e - o * o) * i / (f - o), l = Math.floor(i + .5), M = Math.floor(n + .5), n = (t - a) * (i - f) / (o - f) + a, L(f, a, l, Math.floor(n + .5), l, M, r), n = (t - h) * (i - e) / (o - e) + h, f = o = l, a = M, t = Math.floor(n + .5)), (a - t) * (h - t) > 0 && (i = a - 2 * t + h, i = (a - t) / i, n = (1 - i) * ((1 - i) * f + 2 * i * o) + i * i * e, i = (a * h - t * t) * i / (a - t), l = Math.floor(n + .5), M = Math.floor(i + .5), n = (o - f) * (i - a) / (t - a) + f, L(f, a, Math.floor(n + .5), M, l, M, r), n = (o - e) * (i - h) / (t - h) + e, f = l, o = Math.floor(n + .5), a = t = M), L(f, a, o, t, e, h, r);
    }
    function L(f, a, o, t, e, h, r) {
      var l = e - o,
        M = h - t,
        i = f - o,
        n = a - t,
        c,
        q,
        d,
        b,
        s = i * M - n * l;
      if (I(i * l <= 0 && n * M <= 0, "sign of gradient must not change"), l * l + M * M > i * i + n * n && (e = f, f = l + o, h = a, a = M + t, s = -s), s != 0) {
        i += l, i *= l = f < e ? 1 : -1, n += M, n *= M = a < h ? 1 : -1, c = 2 * i * n, i *= i, n *= n, s * l * M < 0 && (i = -i, n = -n, c = -c, s = -s), q = 4 * M * s * (o - f) + i - c, d = 4 * l * s * (a - t) + n - c, i += i, n += n, b = q + d + c;
        do {
          if (r(f, a), f == e && a == h) return;
          t = +(2 * b < q), 2 * b > d && (f += l, q -= c, b += d += n), t && (a += M, d -= c, b += q += i);
        } while (d < 0 && q > 0);
      }
      J(f, a, e, h, r);
    }
    function ia(f, a, o, t, e, h, r) {
      var l = f - o,
        M = a - t,
        i = f - 2 * o + e,
        n;
      l * (e - o) > 0 && (M * (h - t) > 0 && Math.abs((a - 2 * t + h) / i * l) > Math.abs(M) && (f = e, e = l + o, a = h, h = M + t), i = (f - o) / i, n = (1 - i) * ((1 - i) * a + 2 * i * t) + i * i * h, i = (f * e - o * o) * i / (f - o), l = Math.floor(i + .5), M = Math.floor(n + .5), n = (t - a) * (i - f) / (o - f) + a, Q(f, a, l, Math.floor(n + .5), l, M, r), n = (t - h) * (i - e) / (o - e) + h, f = o = l, a = M, t = Math.floor(n + .5)), (a - t) * (h - t) > 0 && (i = a - 2 * t + h, i = (a - t) / i, n = (1 - i) * ((1 - i) * f + 2 * i * o) + i * i * e, i = (a * h - t * t) * i / (a - t), l = Math.floor(n + .5), M = Math.floor(i + .5), n = (o - f) * (i - a) / (t - a) + f, Q(f, a, Math.floor(n + .5), M, l, M, r), n = (o - e) * (i - h) / (t - h) + e, f = l, o = Math.floor(n + .5), a = t = M), Q(f, a, o, t, e, h, r);
    }
    function Q(f, a, o, t, e, h, r) {
      var l = e - o,
        M = h - t,
        i = f - o,
        n = a - t,
        c,
        q,
        d,
        b,
        s,
        u = i * M - n * l;
      if (l * l + M * M > i * i + n * n && (e = f, f = l + o, h = a, a = M + t, u = -u), u != 0) {
        i += l, i *= l = f < e ? 1 : -1, n += M, n *= M = a < h ? 1 : -1, c = 2 * i * n, i *= i, n *= n, u * l * M < 0 && (i = -i, n = -n, c = -c, u = -u), q = 4 * M * (o - f) * u + i - c, d = 4 * l * (a - t) * u + n - c, i += i, n += n, b = q + d + c;
        do {
          if (u = Math.min(q + c, -c - d), s = Math.max(q + c, -c - d), s += 2 * s * u * u / (4 * s * s + u * u), r(f, a, 255 * Math.abs(b - q - d - c) / s), f == e || a == h) break;
          o = f, u = q - b, t = +(2 * b + d < 0), 2 * b + q > 0 && (b - d < s && r(f, a + M, 255 * Math.abs(b - d) / s), f += l, q -= c, b += d += n), t && (u < s && r(o + l, a, 255 * Math.abs(u) / s), a += M, d -= c, b += q += i);
        } while (d < q);
      }
      U(f, a, e, h, r);
    }
    function _(f, a, o, t, e, h, r, l, M) {
      var i,
        n,
        c,
        q = 1;
      let d = f < r ? 1 : -1,
        b = a < l ? 1 : -1,
        s = -Math.abs(f + o - e - r),
        u = s - 4 * d * (o - e),
        z = d * (f - o - e + r),
        j = -Math.abs(a + t - h - l),
        B = j - 4 * b * (t - h),
        R = b * (a - t - h + l),
        p,
        S,
        W,
        T,
        G,
        E,
        O,
        v,
        g,
        k,
        F,
        D = .01;
      if (I((o - f) * (e - r) < D && ((r - f) * (o - e) < D || z * z < u * s + D), "slope change"), I((t - a) * (h - l) < D && ((l - a) * (t - h) < D || R * R < B * j + D), "slope change"), u == 0 && B == 0) return d = Math.floor((3 * o - f + 1) / 2), b = Math.floor((3 * t - a + 1) / 2), L(f, a, d, b, r, l, M);
      o = (o - f) * (o - f) + (t - a) * (t - a) + 1, e = (e - r) * (e - r) + (h - l) * (h - l) + 1;
      do {
        p = u * R - z * B, S = u * j - s * B, W = z * j - s * R, k = p * (p + S - 3 * W) + S * S, i = k > 0 ? 1 : Math.sqrt(1 + 1024 / o), p *= i, S *= i, W *= i, k *= i * i, E = 9 * (p + S + W) / 8, T = 8 * (u - B), v = 27 * (8 * p * (R * R - B * j) + k * (B + 2 * R + j)) / 64 - B * B * (E - B), g = 27 * (8 * p * (z * z - u * s) - k * (u + 2 * z + s)) / 64 - u * u * (E + u), G = 3 * (3 * p * (3 * R * R - B * B - 2 * B * j) - B * (3 * S * (B + R) + B * T)) / 4, O = 3 * (3 * p * (3 * z * z - u * u - 2 * u * s) - u * (3 * S * (u + z) + u * T)) / 4, E = u * B * (6 * p + 6 * S - 3 * W + T), S = B * B, T = u * u, E = 3 * (E + 9 * i * (T * R * j - z * s * S) - 18 * z * R * p) / 8, k < 0 && (v = -v, g = -g, G = -G, O = -O, E = -E, S = -S, T = -T), p = 6 * B * S, S = -6 * u * S, W = 6 * B * T, T = -6 * u * T, v += E, k = v + g, g += E;
        a: for (F = E, n = c = i; f != r && a != l;) {
          M(f, a);
          do {
            if (v > F || g < F) break a;
            t = 2 * k - g, 2 * k >= v && (n--, k += v += G, g += E += S, O += W, G += p), t <= 0 && (c--, k += g += O, v += E += W, G += S, O += T);
          } while (n > 0 && c > 0);
          2 * n <= i && (f += d, n += i), 2 * c <= i && (a += b, c += i), F == E && v < 0 && g > 0 && (F = D);
        }
        G = f, f = r, r = G, d = -d, z = -z, O = a, a = l, l = O, b = -b, R = -R, o = e;
      } while (q--);
      J(f, a, r, l, M);
    }
    function $(f, a, o, t, e, h, r, l, M) {
      let i,
        n,
        c,
        q = 1,
        d = f < r ? 1 : -1,
        b = a < l ? 1 : -1,
        s = -Math.abs(f + o - e - r),
        u = s - 4 * d * (o - e),
        z = d * (f - o - e + r),
        j = -Math.abs(a + t - h - l),
        B = j - 4 * b * (t - h),
        R = b * (a - t - h + l),
        p,
        S,
        W,
        T,
        G,
        E,
        O,
        v,
        g,
        k,
        F,
        D,
        C,
        A;
      const K = .01;
      if (I((o - f) * (e - r) < K && ((r - f) * (o - e) < K || z * z < u * s + K)), I((t - a) * (h - l) < K && ((l - a) * (t - h) < K || R * R < B * j + K)), u === 0 && B === 0) return d = Math.floor((3 * o - f + 1) / 2), b = Math.floor((3 * t - a + 1) / 2), Q(f, a, d, b, r, l, M);
      o = (o - f) * (o - f) + (t - a) * (t - a) + 1, e = (e - r) * (e - r) + (h - l) * (h - l) + 1;
      do {
        p = u * R - z * B, S = u * j - s * B, W = z * j - s * R, A = 4 * p * W - S * S, k = p * (p + S - 3 * W) + S * S, i = k > 0 ? 1 : Math.sqrt(1 + 1024 / o), p *= i, S *= i, W *= i, k *= i * i, E = 9 * (p + S + W) / 8, T = 8 * (u - B), v = 27 * (8 * p * (R * R - B * j) + k * (B + 2 * R + j)) / 64 - B * B * (E - B), g = 27 * (8 * p * (z * z - u * s) - k * (u + 2 * z + s)) / 64 - u * u * (E + u), G = 3 * (3 * p * (3 * R * R - B * B - 2 * B * j) - B * (3 * S * (B + R) + B * T)) / 4, O = 3 * (3 * p * (3 * z * z - u * u - 2 * u * s) - u * (3 * S * (u + z) + u * T)) / 4, E = u * B * (6 * p + 6 * S - 3 * W + T), S = B * B, T = u * u, E = 3 * (E + 9 * i * (T * R * j - z * s * S) - 18 * z * R * p) / 8, k < 0 && (v = -v, g = -g, G = -G, O = -O, E = -E, S = -S, T = -T), p = 6 * B * S, S = -6 * u * S, W = 6 * B * T, T = -6 * u * T, v += E, k = v + g, g += E;
        let X = false;
        a: for (n = c = i; f !== r && a !== l;) {
          t = Math.min(Math.abs(E - v), Math.abs(g - E)), C = Math.max(Math.abs(E - v), Math.abs(g - E)), C = i * (C + 2 * C * t * t / (4 * C * C + t * t)), t = 255 * Math.abs(k - (i - n + 1) * v - (i - c + 1) * g + i * E) / C, t < 256 && M(f, a, t), F = Math.abs(k - (i - n + 1) * v + (c - 1) * g), D = Math.abs(k + (n - 1) * v - (i - c + 1) * g), h = a;
          do {
            if (A >= -K && (v + G > E || g + O < E)) {
              X = true;
              break a;
            }
            if (t = 2 * k + v, 2 * k + g > 0) n--, k += v += G, g += E += S, O += W, G += p;else if (t > 0) {
              X = true;
              break a;
            }
            t <= 0 && (c--, k += g += O, v += E += W, G += S, O += T);
          } while (n > 0 && c > 0);
          2 * c <= i && (D < C && M(f + d, a, 255 * D / C), a += b, c += i), 2 * n <= i && (F < C && M(f, h + b, 255 * F / C), f += d, n += i);
        }
        X && (2 * k < g && 2 * c <= i + 2 && (D < C && M(f + d, a, 255 * D / C), a += b), 2 * k > v && 2 * n <= i + 2 && (F < C && M(f, h + b, 255 * F / C), f += d), G = f, f = r, r = G, d = -d, z = -z, O = a, a = l, l = O, b = -b, R = -R, o = e);
        break;
      } while (q--);
      U(Math.floor(f), Math.floor(a), Math.floor(r), Math.floor(l), M);
    }
    function m(f, a, o, t, e, h, r, l, M, i) {
      let n = 0,
        c = 0,
        q = f + o - e - r,
        d = q - 4 * (o - e),
        b = f - o - e + r,
        s = b + 4 * (o + e),
        u = a + t - h - l,
        z = u - 4 * (t - h),
        j = a - t - h + l,
        B = j + 4 * (t + h);
      var R = f,
        p,
        S,
        W,
        T = a,
        G,
        E,
        O;
      let v = b * b - d * q,
        g;
      const k = [0, 0, 0, 0, 0];
      for (d == 0 ? Math.abs(q) < 2 * Math.abs(b) && (k[n++] = q / (2 * b)) : v > 0 && (g = Math.sqrt(v), v = (b - g) / d, Math.abs(v) < 1 && (k[n++] = v), v = (b + g) / d, Math.abs(v) < 1 && (k[n++] = v)), v = j * j - z * u, z == 0 ? Math.abs(u) < 2 * Math.abs(j) && (k[n++] = u / (2 * j)) : v > 0 && (g = Math.sqrt(v), v = (j - g) / z, Math.abs(v) < 1 && (k[n++] = v), v = (j + g) / z, Math.abs(v) < 1 && (k[n++] = v)), c = 1; c < n; c++) (v = k[c - 1]) > k[c] && (k[c - 1] = k[c], k[c] = v, c = 0);
      for (v = -1, k[n] = 1, c = 0; c <= n; c++) g = k[c], p = (v * (v * b - 2 * q) - g * (v * (v * d - 2 * b) + q) + s) / 8 - R, G = (v * (v * j - 2 * u) - g * (v * (v * z - 2 * j) + u) + B) / 8 - T, S = (g * (g * b - 2 * q) - v * (g * (g * d - 2 * b) + q) + s) / 8 - R, E = (g * (g * j - 2 * u) - v * (g * (g * z - 2 * j) + u) + B) / 8 - T, R -= W = (g * (g * (3 * b - g * d) - 3 * q) + s) / 8, T -= O = (g * (g * (3 * j - g * z) - 3 * u) + B) / 8, r = Math.floor(W + .5), l = Math.floor(O + .5), R != 0 && (p *= R = (f - r) / R, S *= R), T != 0 && (G *= T = (a - l) / T, E *= T), (f != r || a != l) && M(f, a, f + p, a + G, f + S, a + E, r, l, i), f = r, a = l, R = W, T = O, v = g;
    }
    function ra(f, a, o, t, e, h, r, l, M) {
      m(f, a, o, t, e, h, r, l, _, M);
    }
    function oa(f, a, o, t, e, h, r, l, M) {
      m(f, a, o, t, e, h, r, l, $, M);
    }
    N.circle = aa, N.circleAA = fa, N.cubicBezier = ra, N.cubicBezierAA = oa, N.cubicBezierSegment = _, N.cubicBezierSegmentAA = $, N.ellipse = y, N.ellipseRect = Z, N.line = J, N.lineAA = U, N.lineWidth = w, N.quadBezier = ta, N.quadBezierAA = ia, N.quadBezierSegment = L, N.quadBezierSegmentAA = Q, N.quadRationalBezier = P, N.quadRationalBezierSegment = H, N.quadRationalBezierSegmentAA = V, N.rotatedEllipse = x, N.rotatedEllipseRect = Y, Object.defineProperty(N, Symbol.toStringTag, {
      value: "Module"
    });
  });
})(index_umd$1, index_umd$1.exports);
var index_umdExports = index_umd$1.exports;

/**
 * Remove duplicate points from array.
 * @param points - Polygon points array.
 * @returns Cleaned polygon points array.
 */
function deleteDuplicates(points) {
  const finalPoints = [];
  for (let i = 0; i < points.length; i++) {
    if (points[i].column === points[(i + 1) % points.length].column && points[i].row === points[(i + 1) % points.length].row) {
      continue;
    } else {
      finalPoints.push(points[i]);
    }
  }
  return finalPoints;
}

/**
 * Get the coordinates of the points on a circle. The reference is the center of the circle.
 * The first point is the right one and they are then sorted clockwise.
 * @param radius - Radius of the circle.
 * @returns The coordinates of the points on a circle of given diameter.
 */
function getCirclePoints(radius) {
  const circlePoints = [];
  index_umdExports.circle(radius, radius, radius, (column, row) => {
    circlePoints.push({
      row: row - radius,
      column: column - radius
    });
  });
  const firstQuarter = [];
  const secondQuarter = [];
  const thirdQuarter = [];
  const fourthQuarter = [];
  for (let i = 0; i < circlePoints.length; i = i + 4) {
    firstQuarter.push(circlePoints[i % circlePoints.length]);
    secondQuarter.push(circlePoints[(i + 1) % circlePoints.length]);
    thirdQuarter.push(circlePoints[(i + 2) % circlePoints.length]);
    fourthQuarter.push(circlePoints[(i + 3) % circlePoints.length]);
  }
  return firstQuarter.concat(secondQuarter, thirdQuarter, fourthQuarter);
}
const zeroPoint = {
  row: 0,
  column: 0
};
/**
 * Get the coordinates of the points in a circle of given radius. The points are sorted by column then row.
 * @param radius - Radius of the circle.
 * @param center - Center of the circle.
 * @returns The coordinates of the points in a circle of given radius.
 */
function getFilledCirclePoints(radius, center = zeroPoint) {
  const circlePoints = [];
  if (radius === 0) {
    return [center];
  }
  if (radius === 1) {
    circlePoints.push(center);
  }
  index_umdExports.circle(center.column, center.row, radius, (column, row) => {
    circlePoints.push({
      row,
      column
    });
    if (column - 1 > center.column) {
      circlePoints.push(...getLinePoints({
        row,
        column: column - 1
      }, {
        row,
        column: center.column
      }));
    } else if (column + 1 < center.column) {
      circlePoints.push(...getLinePoints({
        row,
        column: column + 1
      }, {
        row,
        column: center.column
      }));
    }
  });
  const sorted = sortByColumnRow(circlePoints);
  return deleteDuplicates(sorted);
}
/**
 * Get the coordinates of the points on a line.
 * @param from - Starting point.
 * @param to - End point.
 * @returns The coordinates of the points on the line.
 */
function getLinePoints(from, to) {
  const linePoints = [];
  index_umdExports.line(from.column, from.row, to.column, to.row, (column, row) => {
    linePoints.push({
      row,
      column
    });
  });
  return linePoints;
}
/**
 * Get the coordinates of the points that are on right, bottom, left and top at a given radius. The reference is the origin of the circle.
 * First point is the most on the right, then points are in clockwise order.
 * @param radius - Radius of the circle.
 * @returns The coordinates of the compass points.
 */
function getCompassPoints(radius) {
  index_umdExports.circle(radius, radius, radius, (column, row) => {
  });
  return [{
    row: 0,
    column: radius
  }, {
    row: radius,
    column: 0
  }, {
    row: 0,
    column: -radius
  }, {
    row: -radius,
    column: 0
  }];
}

/**
 * Compute the current pixel index based on the value coordinates.
 * @param column - Column of the value.
 * @param row - Row of the value.
 * @param image - The image that is being processed.
 * @param channel - Value channel.
 * @returns The value index.
 */
function getIndex(column, row, image, channel = 0) {
  return (row * image.width + column) * image.channels + channel;
}

/**
 * Coordinates of the surrounding pixels relative to the current pixel.
 * First pixel is the one on the right, then they are in clockwise order.
 */
const surroundingPixels = [{
  row: 0,
  column: 1
}, {
  row: 1,
  column: 1
}, {
  row: 1,
  column: 0
}, {
  row: 1,
  column: -1
}, {
  row: 0,
  column: -1
}, {
  row: -1,
  column: -1
}, {
  row: -1,
  column: 0
}, {
  row: -1,
  column: 1
}];

const formatter = new Intl.ListFormat('en', {
  type: 'disjunction'
});
/**
 * This method checks if a process can be applied on the current image.
 * @param image - Image for which compatibility has to be checked.
 * @param options - Check processable options.
 */
function checkProcessable$1(image, options = {}) {
  let {
    bitDepth,
    alpha,
    colorModel,
    components,
    channels
  } = options;
  if (bitDepth) {
    if (!Array.isArray(bitDepth)) {
      bitDepth = [bitDepth];
    }
    if (!bitDepth.includes(image.bitDepth)) {
      throw new RangeError(`image bitDepth must be ${format(bitDepth)} to apply this algorithm`);
    }
  }
  if (alpha) {
    if (!Array.isArray(alpha)) {
      alpha = [alpha];
    }
    if (!alpha.includes(image.alpha)) {
      throw new RangeError(`image alpha must be ${format(alpha)} to apply this algorithm`);
    }
  }
  if (colorModel) {
    if (!Array.isArray(colorModel)) {
      colorModel = [colorModel];
    }
    if (!colorModel.includes(image.colorModel)) {
      throw new RangeError(`image colorModel must be ${format(colorModel)} to apply this algorithm`);
    }
  }
  if (components) {
    if (!Array.isArray(components)) {
      components = [components];
    }
    if (!components.includes(image.components)) {
      const errorMessage = `image components must be ${format(components)} to apply this algorithm`;
      if (components.length === 1 && components[0] === 1) {
        throw new RangeError(`${errorMessage}. The image can be converted using "image.grey()"`);
      } else {
        throw new RangeError(errorMessage);
      }
    }
  }
  if (channels) {
    if (!Array.isArray(channels)) {
      channels = [channels];
    }
    if (!channels.includes(image.channels)) {
      throw new RangeError(`image channels must be ${format(channels)} to apply this algorithm`);
    }
  }
}
/**
 * Format array to a string.
 * @param array - Array to format.
 * @returns The formatted string.
 */
function format(array) {
  return formatter.format(array.map(String));
}

/**
 * Compute the score of a keypoint using the function described in the FAST article.
 * DOI: https://doi.org/10.1007/11744023_34.
 * @param image - Image to process.
 * @param origin - Keypoint coordinates.
 * @param threshold - FAST threshold.
 * @param circlePoints - Coordinates of the points on the circle.
 * @returns Score of the corner.
 */
function getFastScore(image, origin, threshold, circlePoints) {
  const currentIntensity = image.getValueByPoint(origin, 0);
  let brighterSum = 0;
  let darkerSum = 0;
  for (const point of circlePoints) {
    const pointIntensity = image.getValue(origin.column + point.column, origin.row + point.row, 0);
    if (pointIntensity >= currentIntensity + threshold) {
      brighterSum += Math.abs(pointIntensity - currentIntensity) - threshold; // circle point is lighter
    } else if (pointIntensity <= currentIntensity - threshold) {
      darkerSum += Math.abs(currentIntensity - pointIntensity) - threshold; // circle point is darker
    }
  }
  return Math.max(brighterSum, darkerSum);
}

const SOBEL_X = [[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]];
const SOBEL_Y = [[-1, -2, -1], [0, 0, 0], [1, 2, 1]];
const SCHARR_X = [[3, 0, -3], [10, 0, -10], [3, 0, -3]];
const SCHARR_Y = [[3, 10, 3], [0, 0, 0], [-3, -10, -3]];
const PREWITT_X = [[1, 0, -1], [1, 0, -1], [1, 0, -1]];
const PREWITT_Y = [[1, 1, 1], [0, 0, 0], [-1, -1, -1]];

/**
 * A function that calculates eigenvalues to calculate feature score for Harris and Shi-Tomasi algorithms.
 * @param image - Image take data from.
 * @param origin - Center of the window, where the corner should be.
 * @param windowSize - Size of the window, where data should be scanned.
 * @returns Array of two eigenvalues.
 */
function getEigenvaluesForScore(image, origin, windowSize = 7) {
  if (!(windowSize % 2)) {
    throw new TypeError('windowSize must be an odd integer');
  }
  const cropOrigin = {
    row: origin.row - (windowSize - 1) / 2,
    column: origin.column - (windowSize - 1) / 2
  };
  const window = image.crop({
    origin: cropOrigin,
    width: windowSize,
    height: windowSize
  });
  const xDerivative = window.gradientFilter({
    kernelX: SOBEL_X
  });
  const yDerivative = window.gradientFilter({
    kernelY: SOBEL_Y
  });
  const xMatrix = new WrapperMatrix1D(xDerivative.getRawImage().data, {
    rows: xDerivative.height
  });
  const yMatrix = new WrapperMatrix1D(yDerivative.getRawImage().data, {
    rows: yDerivative.height
  });
  const xx = xMatrix.mmul(xMatrix);
  const xy = yMatrix.mmul(xMatrix);
  const yy = yMatrix.mmul(yMatrix);
  const xxSum = xx.sum();
  const xySum = xy.sum();
  const yySum = yy.sum();
  const structureTensor = new Matrix$1([[xxSum, xySum], [xySum, yySum]]);
  return new EigenvalueDecomposition(structureTensor).realEigenvalues;
}

/**
 * Get the Harris score of a corner. The idea behind the algorithm is that a
 * slight shift of a window around a corner along x and y should result in
 * a very different image.
 *
 * We distinguish 3 cases:
 * - the score is highly negative: you have an edge
 * - the absolute value of the score is small: the region is flat
 * - the score is highly positive: you have a corner.
 * @see {@link https://en.wikipedia.org/wiki/Harris_corner_detector}
 * @param image - Image to which the corner belongs. It must be a greyscale image with only one channel.
 * @param origin - Center of the window, where the corner should be.
 * @param options - Get Harris score options.
 * @returns The Harris score.
 */
function getHarrisScore(image, origin, options = {}) {
  const {
    harrisConstant = 0.04,
    windowSize
  } = options;
  const eigenValues = getEigenvaluesForScore(image, origin, windowSize);
  return eigenValues[0] * eigenValues[1] - harrisConstant * (eigenValues[0] + eigenValues[1]) ** 2;
}

/**
 * Get the Shi-Tomasi score of a corner. The idea is similar to Harris score, but it removes constant to calculate the score and just takes the minimum from two eigenvalues.
 * We distinguish 3 cases:
 * - the score is highly negative: you have an edge
 * - the absolute value of the score is small: the region is flat
 * - the score is highly positive: you have a corner.
 * @param image - Image to which the corner belongs. It must be a greyscale image with only one channel.
 * @param origin - Center of the window, where the corner should be.
 * @param options  - Get Shi-Tomasi score options.
 * @returns The Shi-Tomasi score.
 */
function getShiTomasiScore(image, origin, options = {}) {
  const {
    windowSize = 7
  } = options;
  const eigenValues = getEigenvaluesForScore(image, origin, windowSize);
  return Math.min(eigenValues[0], eigenValues[1]);
}

/**
 * Determine wether a pixel in an image is a corner according to the FAST algorithm.
 * @param origin - Pixel to process.
 * @param image - Image to process.
 * @param circlePoints - Coordinates of the points on the circle.
 * @param compassPoints - Compass points for quick test.
 * @param options - Is FAST keypoint options.
 * @returns Whether the current pixel is a corner or not.
 */
function isFastKeypoint(origin, image, circlePoints, compassPoints, options = {}) {
  const {
    nbContiguousPixels = 12,
    threshold = 20
  } = options;
  const currentIntensity = image.getValueByPoint(origin, 0);
  let brighter = 0;
  let darker = 0;
  // quick test to exlude non corners
  if (nbContiguousPixels >= 12) {
    for (const point of compassPoints) {
      const pointIntensity = image.getValue(origin.column + point.column, origin.row + point.row, 0);
      if (currentIntensity - pointIntensity > threshold) {
        darker++;
      } else if (pointIntensity - currentIntensity > threshold) {
        brighter++;
      }
    }
    if (darker < 3 && brighter < 3) return false;
  }
  // determine whether points on circle are darker or brighter
  const comparisonArray = [];
  for (const point of circlePoints) {
    const pointIntensity = image.getValue(origin.column + point.column, origin.row + point.row, 0);
    if (currentIntensity + threshold <= pointIntensity) {
      comparisonArray.push(-1); // circle point is lighter
    } else if (pointIntensity <= currentIntensity - threshold) {
      comparisonArray.push(1); // circle point is darker
    } else {
      comparisonArray.push(0); // circle point is similar
    }
  }
  // compute number of repeating and touching values
  let currentLength = 1;
  const counterArray = [];
  for (let i = 0; i < comparisonArray.length; i++) {
    const currentValue = comparisonArray[i];
    const nextValue = comparisonArray[(i + 1) % comparisonArray.length];
    if (currentValue === nextValue) {
      if (i === comparisonArray.length - 1) {
        if (counterArray.length === 0) {
          counterArray.push(currentLength);
        } else {
          counterArray[0] += currentLength;
        }
      } else {
        currentLength++;
      }
    } else {
      counterArray.push(currentLength);
      currentLength = 1;
    }
  }
  if (Math.max(...counterArray) >= nbContiguousPixels) {
    return true;
  } else {
    return false;
  }
}

/**
 * Find the features in a GREY image according to the FAST (Features from Accelerated Segment Test) algorithm.
 * Based on the paper Machine Learning for High-Speed Corner Detection.
 * DOI: https://doi.org/10.1007/11744023_34.
 * @param image - The image to process.
 * @param options - Get FAST keypoints options.
 * @returns The FAST keypoints.
 */
function getFastKeypoints(image, options = {}) {
  const {
    fastRadius = 3,
    scoreAlgorithm = 'FAST',
    scoreOptions
  } = options;
  const circlePoints = getCirclePoints(fastRadius);
  const compassPoints = getCompassPoints(fastRadius);
  const {
    maxNbFeatures = 500,
    nbContiguousPixels = 3 / 4 * circlePoints.length,
    threshold = 20,
    nonMaxSuppression = true
  } = options;
  checkProcessable$1(image, {
    channels: [1],
    alpha: false
  });
  function harrisScore(image, corner) {
    return getHarrisScore(image, corner, scoreOptions);
  }
  function fastScore(image, corner) {
    return getFastScore(image, corner, threshold, circlePoints);
  }
  function tomasiScore(image, corner) {
    return getShiTomasiScore(image, corner, scoreOptions);
  }
  const getScore = M$2(scoreAlgorithm).with('HARRIS', () => harrisScore).with('FAST', () => fastScore).with('TOMASI', () => tomasiScore).exhaustive();
  const allKeypoints = [];
  const scoreArray = new Float64Array(image.size).fill(Number.NEGATIVE_INFINITY);
  for (let row = 0; row < image.height; row++) {
    for (let column = 0; column < image.width; column++) {
      const corner = {
        row,
        column
      };
      if (isFastKeypoint(corner, image, circlePoints, compassPoints, {
        nbContiguousPixels,
        threshold
      })) {
        const score = getScore(image, corner);
        scoreArray[getIndex(corner.column, corner.row, image, 0)] = score;
        allKeypoints.push({
          origin: corner,
          score
        });
      }
    }
  }
  let keypoints = [];
  if (!nonMaxSuppression) {
    keypoints = allKeypoints;
  } else {
    // Non-Maximal Suppression
    for (const keypoint of allKeypoints) {
      const currentScore = scoreArray[getIndex(keypoint.origin.column, keypoint.origin.row, image, 0)];
      for (let i = 0; i < surroundingPixels.length; i++) {
        const neighbour = surroundingPixels[i];
        const neighbourScore = scoreArray[getIndex(keypoint.origin.column + neighbour.column, keypoint.origin.row + neighbour.row, image, 0)];
        if (neighbourScore > currentScore) break;
        if (i === surroundingPixels.length - 1) {
          keypoints.push(keypoint);
        }
      }
    }
  }
  keypoints.sort((a, b) => b.score - a.score);
  return keypoints.slice(0, maxNbFeatures);
}

/**
 * Compute the pq order intensity moment of the circular patch with given radius in the image,
 * relatively to the origin defined in the options.
 * Original article: {@link https://doi.org/10.1006/cviu.1998.0719}.
 * @see {@link https://en.wikipedia.org/wiki/Image_moment}
 * @param image - Image to process.
 * @param p - Order along x.
 * @param q - Order along y.
 * @param options - Get intensity moment options.
 * @returns The intensity moment of order pq of the circular window relative to the center.
 */
function getPatchIntensityMoment(image, p, q, options = {}) {
  const {
    center: origin = image.getCoordinates('center'),
    radius = 3
  } = options;
  if (!checkBorderDistance(image, origin, radius)) {
    throw new RangeError(`desired patch is too close to image border`);
  }
  const moment = new Array(image.channels).fill(0);
  const relativeCirclePoints = getFilledCirclePoints(radius);
  for (const point of relativeCirclePoints) {
    for (let channel = 0; channel < image.channels; channel++) {
      const intensity = image.getValue(point.column + origin.column, point.row + origin.row, channel);
      moment[channel] += point.column ** p * point.row ** q * intensity;
    }
  }
  return moment;
}

/**
 * Compute the intensity centroid of the circular patch in an image for each channel relatively to the center of the image.
 * Original article: {@link https://doi.org/10.1006/cviu.1998.0719}.
 * @see {@link https://en.wikipedia.org/wiki/Image_moment}
 * @param image - Image to process.
 * @param options - Patch intensity centroid options.
 * @returns The intensity centroid of each channel of the image.
 */
function getPatchIntensityCentroid(image, options = {}) {
  const moment10 = getPatchIntensityMoment(image, 1, 0, options);
  const moment01 = getPatchIntensityMoment(image, 0, 1, options);
  const moment00 = getPatchIntensityMoment(image, 0, 0, options);
  const centroid = [];
  for (let channel = 0; channel < image.channels; channel++) {
    if (moment00[channel] === 0) {
      centroid.push({
        column: 0,
        row: 0
      });
    } else {
      centroid.push({
        column: moment10[channel] / moment00[channel],
        row: moment01[channel] / moment00[channel]
      });
    }
  }
  return centroid;
}

/**
 * Find the oriented FAST features in a GREY image.
 * How to add orientation to FAST is described in: http://www.gwylab.com/download/ORB_2012.pdf
 * Basically, the intensity centroid of the window around the corner is computed and the
 * orientation is given by the vector from the center to the intensity centroid.
 * @param image - The image to process.
 * @param options - Get oriented FAST keypoints options.
 * @returns The oriented FAST keypoints.
 */
function getOrientedFastKeypoints(image, options = {}) {
  const {
    centroidPatchDiameter: windowSize = 7
  } = options;
  const fastKeypoints = getFastKeypoints(image, options);
  const radius = getRadius(windowSize);
  // handle edge cases: remove keypoints too close to border
  const keypoints = [];
  for (const keypoint of fastKeypoints) {
    if (checkBorderDistance(image, keypoint.origin, radius)) {
      keypoints.push(keypoint);
    }
  }
  const orientedFastKeypoints = [];
  for (const keypoint of keypoints) {
    const centroid = getPatchIntensityCentroid(image, {
      center: keypoint.origin,
      radius
    })[0];
    const angle = toDegrees(getClockwiseAngle({
      column: 0,
      row: 0
    }, centroid));
    orientedFastKeypoints.push({
      ...keypoint,
      angle
    });
  }
  return orientedFastKeypoints;
}

/**
 * Compare the intensity of two pixels of a GREY image.
 * @param image - Source image of the pixels.
 * @param p1 - First point.
 * @param p2 - Second point.
 * @param options - Options.
 * @returns Wether p1 is darker that p2.
 */
function compareIntensity(image, p1, p2, options = {}) {
  const {
    origin = image.getCoordinates('center')
  } = options;
  const absoluteP1 = sum$1(p1, origin);
  const absoluteP2 = sum$1(p2, origin);
  const intensity1 = image.getValueByPoint(absoluteP1, 0);
  const intensity2 = image.getValueByPoint(absoluteP2, 0);
  return intensity1 < intensity2;
}

/**
 * Calculates the median of an array.
 * @param input - Array containing values
 * @param options
 * @returns - median
 */
function xMedian(input, options = {}) {
  if (!isAnyArray$1(input)) {
    throw new TypeError('input must be an array');
  }
  if (input.length === 0) {
    throw new TypeError('input must not be empty');
  }
  const {
    exact = false
  } = options || {};
  const array = input.slice();
  const middleIndex = calcMiddle(0, array.length - 1);
  const median = quickSelect(array, middleIndex);
  if (array.length % 2 === 1 || !exact) {
    return median;
  }
  const medianNext = quickSelect(array, middleIndex + 1);
  return (median + medianNext) / 2;
}
function quickSelect(array, middleIndex) {
  let low = 0;
  let high = array.length - 1;
  let middle = 0;
  let currentLow = 0;
  let currentHigh = 0;
  while (true) {
    if (high <= low) {
      return array[middleIndex];
    }
    if (high === low + 1) {
      if (array[low] > array[high]) {
        swap(array, low, high);
      }
      return array[middleIndex];
    }
    // Find median of low, middle and high items; swap into position low
    middle = calcMiddle(low, high);
    if (array[middle] > array[high]) swap(array, middle, high);
    if (array[low] > array[high]) swap(array, low, high);
    if (array[middle] > array[low]) swap(array, middle, low);
    // Swap low item (now in position middle) into position (low+1)
    swap(array, middle, low + 1);
    // Nibble from each end towards middle, swapping items when stuck
    currentLow = low + 1;
    currentHigh = high;
    while (true) {
      do currentLow++; while (array[low] > array[currentLow]);
      do currentHigh--; while (array[currentHigh] > array[low]);
      if (currentHigh < currentLow) {
        break;
      }
      swap(array, currentLow, currentHigh);
    }
    // Swap middle item (in position low) back into correct position
    swap(array, low, currentHigh);
    // Re-set active partition
    if (currentHigh <= middleIndex) {
      low = currentLow;
    }
    if (currentHigh >= middleIndex) {
      high = currentHigh - 1;
    }
  }
}
function swap(array, i, j) {
  const temp = array[j];
  array[j] = array[i];
  array[i] = temp;
}
function calcMiddle(i, j) {
  return Math.floor((i + j) / 2);
}

/**
 * Checks if the input is a non-empty array of numbers.
 * Only checks the first element.
 * @param input - Array to check.
 * @param options - Additional checks.
 */
function xCheck(input, options = {}) {
  const {
    minLength
  } = options;
  if (!isAnyArray$1(input)) {
    throw new TypeError('input must be an array');
  }
  if (input.length === 0) {
    throw new TypeError('input must not be empty');
  }
  if (typeof input[0] !== 'number') {
    throw new TypeError('input must contain numbers');
  }
  if (minLength && input.length < minLength) {
    throw new Error(`input must have a length of at least ${minLength}`);
  }
}

/**
 * Returns the closest index of a `target`
 * @param array - array of numbers
 * @param target - target
 * @param options
 * @returns - closest index
 */
function xFindClosestIndex(array, target, options = {}) {
  const {
    sorted = true
  } = options;
  if (sorted) {
    let low = 0;
    let high = array.length - 1;
    let middle = 0;
    while (high - low > 1) {
      middle = low + (high - low >> 1);
      if (array[middle] < target) {
        low = middle;
      } else if (array[middle] > target) {
        high = middle;
      } else {
        return middle;
      }
    }
    if (low < array.length - 1) {
      if (Math.abs(target - array[low]) < Math.abs(array[low + 1] - target)) {
        return low;
      } else {
        return low + 1;
      }
    } else {
      return low;
    }
  } else {
    let index = 0;
    let diff = Number.POSITIVE_INFINITY;
    for (let i = 0; i < array.length; i++) {
      const currentDiff = Math.abs(array[i] - target);
      if (currentDiff < diff) {
        diff = currentDiff;
        index = i;
      }
    }
    return index;
  }
}

/**
 * Returns an object with {fromIndex, toIndex} for a specific from / to
 * @param x - array of numbers
 * @param options - Options
 */
function xGetFromToIndex(x, options = {}) {
  let {
    fromIndex,
    toIndex
  } = options;
  const {
    from,
    to
  } = options;
  if (fromIndex === undefined) {
    if (from !== undefined) {
      fromIndex = xFindClosestIndex(x, from);
    } else {
      fromIndex = 0;
    }
  }
  if (toIndex === undefined) {
    if (to !== undefined) {
      toIndex = xFindClosestIndex(x, to);
    } else {
      toIndex = x.length - 1;
    }
  }
  if (fromIndex < 0) fromIndex = 0;
  if (toIndex < 0) toIndex = 0;
  if (fromIndex >= x.length) fromIndex = x.length - 1;
  if (toIndex >= x.length) toIndex = x.length - 1;
  if (fromIndex > toIndex) [fromIndex, toIndex] = [toIndex, fromIndex];
  return {
    fromIndex,
    toIndex
  };
}

/**
 * Computes the mean value of an array of values.
 * @param array - array of numbers
 * @param options - options
 */
function xMean(array, options = {}) {
  xCheck(array);
  const {
    fromIndex,
    toIndex
  } = xGetFromToIndex(array, options);
  let sumValue = array[fromIndex];
  for (let i = fromIndex + 1; i <= toIndex; i++) {
    sumValue += array[i];
  }
  return sumValue / (toIndex - fromIndex + 1);
}

/**
 * Finds the variance of the data
 * @param values - the values of the array
 * @param options - options
 * @returns variance
 */
function xVariance(values, options = {}) {
  if (!isAnyArray$1(values)) {
    throw new TypeError('input must be an array');
  }
  const {
    unbiased = true,
    mean = xMean(values)
  } = options;
  let sqrError = 0;
  for (const value of values) {
    const x = value - mean;
    sqrError += x * x;
  }
  if (unbiased) {
    return sqrError / (values.length - 1);
  } else {
    return sqrError / values.length;
  }
}

function FFT(size) {
  this.size = size | 0;
  if (this.size <= 1 || (this.size & this.size - 1) !== 0) throw new Error('FFT size must be a power of two and bigger than 1');
  this._csize = size << 1;

  // NOTE: Use of `var` is intentional for old V8 versions
  var table = new Array(this.size * 2);
  for (var i = 0; i < table.length; i += 2) {
    const angle = Math.PI * i / this.size;
    table[i] = Math.cos(angle);
    table[i + 1] = -Math.sin(angle);
  }
  this.table = table;

  // Find size's power of two
  var power = 0;
  for (var t = 1; this.size > t; t <<= 1) power++;

  // Calculate initial step's width:
  //   * If we are full radix-4 - it is 2x smaller to give inital len=8
  //   * Otherwise it is the same as `power` to give len=4
  this._width = power % 2 === 0 ? power - 1 : power;

  // Pre-compute bit-reversal patterns
  this._bitrev = new Array(1 << this._width);
  for (var j = 0; j < this._bitrev.length; j++) {
    this._bitrev[j] = 0;
    for (var shift = 0; shift < this._width; shift += 2) {
      var revShift = this._width - shift - 2;
      this._bitrev[j] |= (j >>> shift & 3) << revShift;
    }
  }
  this._out = null;
  this._data = null;
  this._inv = 0;
}
FFT.prototype.fromComplexArray = function fromComplexArray(complex, storage) {
  var res = storage || new Array(complex.length >>> 1);
  for (var i = 0; i < complex.length; i += 2) res[i >>> 1] = complex[i];
  return res;
};
FFT.prototype.createComplexArray = function createComplexArray() {
  const res = new Array(this._csize);
  for (var i = 0; i < res.length; i++) res[i] = 0;
  return res;
};
FFT.prototype.toComplexArray = function toComplexArray(input, storage) {
  var res = storage || this.createComplexArray();
  for (var i = 0; i < res.length; i += 2) {
    res[i] = input[i >>> 1];
    res[i + 1] = 0;
  }
  return res;
};
FFT.prototype.completeSpectrum = function completeSpectrum(spectrum) {
  var size = this._csize;
  var half = size >>> 1;
  for (var i = 2; i < half; i += 2) {
    spectrum[size - i] = spectrum[i];
    spectrum[size - i + 1] = -spectrum[i + 1];
  }
};
FFT.prototype.transform = function transform(out, data) {
  if (out === data) throw new Error('Input and output buffers must be different');
  this._out = out;
  this._data = data;
  this._inv = 0;
  this._transform4();
  this._out = null;
  this._data = null;
};
FFT.prototype.realTransform = function realTransform(out, data) {
  if (out === data) throw new Error('Input and output buffers must be different');
  this._out = out;
  this._data = data;
  this._inv = 0;
  this._realTransform4();
  this._out = null;
  this._data = null;
};
FFT.prototype.inverseTransform = function inverseTransform(out, data) {
  if (out === data) throw new Error('Input and output buffers must be different');
  this._out = out;
  this._data = data;
  this._inv = 1;
  this._transform4();
  for (var i = 0; i < out.length; i++) out[i] /= this.size;
  this._out = null;
  this._data = null;
};

// radix-4 implementation
//
// NOTE: Uses of `var` are intentional for older V8 version that do not
// support both `let compound assignments` and `const phi`
FFT.prototype._transform4 = function _transform4() {
  var out = this._out;
  var size = this._csize;

  // Initial step (permute and transform)
  var width = this._width;
  var step = 1 << width;
  var len = size / step << 1;
  var outOff;
  var t;
  var bitrev = this._bitrev;
  if (len === 4) {
    for (outOff = 0, t = 0; outOff < size; outOff += len, t++) {
      const off = bitrev[t];
      this._singleTransform2(outOff, off, step);
    }
  } else {
    // len === 8
    for (outOff = 0, t = 0; outOff < size; outOff += len, t++) {
      const off = bitrev[t];
      this._singleTransform4(outOff, off, step);
    }
  }

  // Loop through steps in decreasing order
  var inv = this._inv ? -1 : 1;
  var table = this.table;
  for (step >>= 2; step >= 2; step >>= 2) {
    len = size / step << 1;
    var quarterLen = len >>> 2;

    // Loop through offsets in the data
    for (outOff = 0; outOff < size; outOff += len) {
      // Full case
      var limit = outOff + quarterLen;
      for (var i = outOff, k = 0; i < limit; i += 2, k += step) {
        const A = i;
        const B = A + quarterLen;
        const C = B + quarterLen;
        const D = C + quarterLen;

        // Original values
        const Ar = out[A];
        const Ai = out[A + 1];
        const Br = out[B];
        const Bi = out[B + 1];
        const Cr = out[C];
        const Ci = out[C + 1];
        const Dr = out[D];
        const Di = out[D + 1];

        // Middle values
        const MAr = Ar;
        const MAi = Ai;
        const tableBr = table[k];
        const tableBi = inv * table[k + 1];
        const MBr = Br * tableBr - Bi * tableBi;
        const MBi = Br * tableBi + Bi * tableBr;
        const tableCr = table[2 * k];
        const tableCi = inv * table[2 * k + 1];
        const MCr = Cr * tableCr - Ci * tableCi;
        const MCi = Cr * tableCi + Ci * tableCr;
        const tableDr = table[3 * k];
        const tableDi = inv * table[3 * k + 1];
        const MDr = Dr * tableDr - Di * tableDi;
        const MDi = Dr * tableDi + Di * tableDr;

        // Pre-Final values
        const T0r = MAr + MCr;
        const T0i = MAi + MCi;
        const T1r = MAr - MCr;
        const T1i = MAi - MCi;
        const T2r = MBr + MDr;
        const T2i = MBi + MDi;
        const T3r = inv * (MBr - MDr);
        const T3i = inv * (MBi - MDi);

        // Final values
        const FAr = T0r + T2r;
        const FAi = T0i + T2i;
        const FCr = T0r - T2r;
        const FCi = T0i - T2i;
        const FBr = T1r + T3i;
        const FBi = T1i - T3r;
        const FDr = T1r - T3i;
        const FDi = T1i + T3r;
        out[A] = FAr;
        out[A + 1] = FAi;
        out[B] = FBr;
        out[B + 1] = FBi;
        out[C] = FCr;
        out[C + 1] = FCi;
        out[D] = FDr;
        out[D + 1] = FDi;
      }
    }
  }
};

// radix-2 implementation
//
// NOTE: Only called for len=4
FFT.prototype._singleTransform2 = function _singleTransform2(outOff, off, step) {
  const out = this._out;
  const data = this._data;
  const evenR = data[off];
  const evenI = data[off + 1];
  const oddR = data[off + step];
  const oddI = data[off + step + 1];
  const leftR = evenR + oddR;
  const leftI = evenI + oddI;
  const rightR = evenR - oddR;
  const rightI = evenI - oddI;
  out[outOff] = leftR;
  out[outOff + 1] = leftI;
  out[outOff + 2] = rightR;
  out[outOff + 3] = rightI;
};

// radix-4
//
// NOTE: Only called for len=8
FFT.prototype._singleTransform4 = function _singleTransform4(outOff, off, step) {
  const out = this._out;
  const data = this._data;
  const inv = this._inv ? -1 : 1;
  const step2 = step * 2;
  const step3 = step * 3;

  // Original values
  const Ar = data[off];
  const Ai = data[off + 1];
  const Br = data[off + step];
  const Bi = data[off + step + 1];
  const Cr = data[off + step2];
  const Ci = data[off + step2 + 1];
  const Dr = data[off + step3];
  const Di = data[off + step3 + 1];

  // Pre-Final values
  const T0r = Ar + Cr;
  const T0i = Ai + Ci;
  const T1r = Ar - Cr;
  const T1i = Ai - Ci;
  const T2r = Br + Dr;
  const T2i = Bi + Di;
  const T3r = inv * (Br - Dr);
  const T3i = inv * (Bi - Di);

  // Final values
  const FAr = T0r + T2r;
  const FAi = T0i + T2i;
  const FBr = T1r + T3i;
  const FBi = T1i - T3r;
  const FCr = T0r - T2r;
  const FCi = T0i - T2i;
  const FDr = T1r - T3i;
  const FDi = T1i + T3r;
  out[outOff] = FAr;
  out[outOff + 1] = FAi;
  out[outOff + 2] = FBr;
  out[outOff + 3] = FBi;
  out[outOff + 4] = FCr;
  out[outOff + 5] = FCi;
  out[outOff + 6] = FDr;
  out[outOff + 7] = FDi;
};

// Real input radix-4 implementation
FFT.prototype._realTransform4 = function _realTransform4() {
  var out = this._out;
  var size = this._csize;

  // Initial step (permute and transform)
  var width = this._width;
  var step = 1 << width;
  var len = size / step << 1;
  var outOff;
  var t;
  var bitrev = this._bitrev;
  if (len === 4) {
    for (outOff = 0, t = 0; outOff < size; outOff += len, t++) {
      const off = bitrev[t];
      this._singleRealTransform2(outOff, off >>> 1, step >>> 1);
    }
  } else {
    // len === 8
    for (outOff = 0, t = 0; outOff < size; outOff += len, t++) {
      const off = bitrev[t];
      this._singleRealTransform4(outOff, off >>> 1, step >>> 1);
    }
  }

  // Loop through steps in decreasing order
  var inv = this._inv ? -1 : 1;
  var table = this.table;
  for (step >>= 2; step >= 2; step >>= 2) {
    len = size / step << 1;
    var halfLen = len >>> 1;
    var quarterLen = halfLen >>> 1;
    var hquarterLen = quarterLen >>> 1;

    // Loop through offsets in the data
    for (outOff = 0; outOff < size; outOff += len) {
      for (var i = 0, k = 0; i <= hquarterLen; i += 2, k += step) {
        var A = outOff + i;
        var B = A + quarterLen;
        var C = B + quarterLen;
        var D = C + quarterLen;

        // Original values
        var Ar = out[A];
        var Ai = out[A + 1];
        var Br = out[B];
        var Bi = out[B + 1];
        var Cr = out[C];
        var Ci = out[C + 1];
        var Dr = out[D];
        var Di = out[D + 1];

        // Middle values
        var MAr = Ar;
        var MAi = Ai;
        var tableBr = table[k];
        var tableBi = inv * table[k + 1];
        var MBr = Br * tableBr - Bi * tableBi;
        var MBi = Br * tableBi + Bi * tableBr;
        var tableCr = table[2 * k];
        var tableCi = inv * table[2 * k + 1];
        var MCr = Cr * tableCr - Ci * tableCi;
        var MCi = Cr * tableCi + Ci * tableCr;
        var tableDr = table[3 * k];
        var tableDi = inv * table[3 * k + 1];
        var MDr = Dr * tableDr - Di * tableDi;
        var MDi = Dr * tableDi + Di * tableDr;

        // Pre-Final values
        var T0r = MAr + MCr;
        var T0i = MAi + MCi;
        var T1r = MAr - MCr;
        var T1i = MAi - MCi;
        var T2r = MBr + MDr;
        var T2i = MBi + MDi;
        var T3r = inv * (MBr - MDr);
        var T3i = inv * (MBi - MDi);

        // Final values
        var FAr = T0r + T2r;
        var FAi = T0i + T2i;
        var FBr = T1r + T3i;
        var FBi = T1i - T3r;
        out[A] = FAr;
        out[A + 1] = FAi;
        out[B] = FBr;
        out[B + 1] = FBi;

        // Output final middle point
        if (i === 0) {
          var FCr = T0r - T2r;
          var FCi = T0i - T2i;
          out[C] = FCr;
          out[C + 1] = FCi;
          continue;
        }

        // Do not overwrite ourselves
        if (i === hquarterLen) continue;

        // In the flipped case:
        // MAi = -MAi
        // MBr=-MBi, MBi=-MBr
        // MCr=-MCr
        // MDr=MDi, MDi=MDr
        var ST0r = T1r;
        var ST0i = -T1i;
        var ST1r = T0r;
        var ST1i = -T0i;
        var ST2r = -inv * T3i;
        var ST2i = -inv * T3r;
        var ST3r = -inv * T2i;
        var ST3i = -inv * T2r;
        var SFAr = ST0r + ST2r;
        var SFAi = ST0i + ST2i;
        var SFBr = ST1r + ST3i;
        var SFBi = ST1i - ST3r;
        var SA = outOff + quarterLen - i;
        var SB = outOff + halfLen - i;
        out[SA] = SFAr;
        out[SA + 1] = SFAi;
        out[SB] = SFBr;
        out[SB + 1] = SFBi;
      }
    }
  }
};

// radix-2 implementation
//
// NOTE: Only called for len=4
FFT.prototype._singleRealTransform2 = function _singleRealTransform2(outOff, off, step) {
  const out = this._out;
  const data = this._data;
  const evenR = data[off];
  const oddR = data[off + step];
  const leftR = evenR + oddR;
  const rightR = evenR - oddR;
  out[outOff] = leftR;
  out[outOff + 1] = 0;
  out[outOff + 2] = rightR;
  out[outOff + 3] = 0;
};

// radix-4
//
// NOTE: Only called for len=8
FFT.prototype._singleRealTransform4 = function _singleRealTransform4(outOff, off, step) {
  const out = this._out;
  const data = this._data;
  const inv = this._inv ? -1 : 1;
  const step2 = step * 2;
  const step3 = step * 3;

  // Original values
  const Ar = data[off];
  const Br = data[off + step];
  const Cr = data[off + step2];
  const Dr = data[off + step3];

  // Pre-Final values
  const T0r = Ar + Cr;
  const T1r = Ar - Cr;
  const T2r = Br + Dr;
  const T3r = inv * (Br - Dr);

  // Final values
  const FAr = T0r + T2r;
  const FBr = T1r;
  const FBi = -T3r;
  const FCr = T0r - T2r;
  const FDr = T1r;
  const FDi = T3r;
  out[outOff] = FAr;
  out[outOff + 1] = 0;
  out[outOff + 2] = FBr;
  out[outOff + 3] = FBi;
  out[outOff + 4] = FCr;
  out[outOff + 5] = 0;
  out[outOff + 6] = FDr;
  out[outOff + 7] = FDi;
};

const LOOP = 8;
const FLOAT_MUL = 1 / 16777216;
const sh1 = 15;
const sh2 = 18;
const sh3 = 11;
function multiplyUint32(n, m) {
  n >>>= 0;
  m >>>= 0;
  const nlo = n & 0xffff;
  const nhi = n - nlo;
  return (nhi * m >>> 0) + nlo * m >>> 0;
}
class XSadd {
  random;
  state;
  /**
   * create an instance of XSadd with the specified seed
   * @param [seed=Date.now()]
   */
  constructor(seed = Date.now()) {
    this.state = new Uint32Array(4);
    this.init(seed);
    this.random = this.getFloat.bind(this);
  }
  /**
   * Returns a 32-bit integer r (0 <= r < 2^32)
   */
  getUint32() {
    this.nextState();
    return this.state[3] + this.state[2] >>> 0;
  }
  /**
   * Returns a floating point number r (0.0 <= r < 1.0)
   */
  getFloat() {
    return (this.getUint32() >>> 8) * FLOAT_MUL;
  }
  init(seed) {
    if (!Number.isInteger(seed)) {
      throw new TypeError("seed must be an integer");
    }
    this.state[0] = seed;
    this.state[1] = 0;
    this.state[2] = 0;
    this.state[3] = 0;
    for (let i = 1; i < LOOP; i++) {
      this.state[i & 3] ^= i + multiplyUint32(1812433253, this.state[i - 1 & 3] ^ this.state[i - 1 & 3] >>> 30 >>> 0) >>> 0;
    }
    this.periodCertification();
    for (let i = 0; i < LOOP; i++) {
      this.nextState();
    }
  }
  periodCertification() {
    if (this.state[0] === 0 && this.state[1] === 0 && this.state[2] === 0 && this.state[3] === 0) {
      this.state[0] = 88; // X
      this.state[1] = 83; // S
      this.state[2] = 65; // A
      this.state[3] = 68; // D
    }
  }
  nextState() {
    let t = this.state[0];
    t ^= t << sh1;
    t ^= t >>> sh2;
    t ^= this.state[3] << sh3;
    this.state[0] = this.state[1];
    this.state[1] = this.state[2];
    this.state[2] = this.state[3];
    this.state[3] = t;
  }
}

/**
 * Create a random array of numbers of a specific length.
 * @param options
 * @returns - array of random floats normally distributed
 */
function createRandomArray(options = {}) {
  const {
    mean = 0,
    standardDeviation = 1,
    length = 1000,
    range = 1,
    seed,
    distribution = 'normal'
  } = options;
  const generator = new XSadd(seed);
  const returnArray = new Float64Array(length);
  switch (distribution) {
    case 'normal':
      {
        const gaussianGenerator = new GaussianGenerator(mean, standardDeviation, generator);
        for (let i = 0; i < length; i++) {
          returnArray[i] = gaussianGenerator.generateGaussian();
        }
        break;
      }
    case 'uniform':
      {
        for (let i = 0; i < length; i++) {
          returnArray[i] = (generator.random() - 0.5) * range + mean;
        }
        break;
      }
    default:
      {
        throw new Error(`unknown distribution: ${String(distribution)}`);
      }
  }
  return returnArray;
}
class GaussianGenerator {
  #spare = 0;
  #hasSpare = false;
  #mean;
  #standardDeviation;
  #generator;
  constructor(mean, standardDeviation, generator) {
    this.#mean = mean;
    this.#standardDeviation = standardDeviation;
    this.#generator = generator;
  }
  generateGaussian() {
    let val, u, v, s;
    if (this.#hasSpare) {
      this.#hasSpare = false;
      val = this.#spare * this.#standardDeviation + this.#mean;
    } else {
      do {
        u = this.#generator.random() * 2 - 1;
        v = this.#generator.random() * 2 - 1;
        s = u * u + v * v;
      } while (s >= 1 || s === 0);
      s = Math.sqrt(-2 * Math.log(s) / s);
      this.#spare = v * s;
      this.#hasSpare = true;
      val = this.#mean + this.#standardDeviation * u * s;
    }
    return val;
  }
}

/**
 * Finds the covariance of the points.
 * @param data
 * @param options
 * @returns the covariance
 */
function xyCovariance(data, options = {}) {
  const {
    x,
    y
  } = data;
  const {
    unbiased = true
  } = options;
  const meanX = xMean(x);
  const meanY = xMean(y);
  let error = 0;
  for (let i = 0; i < x.length; i++) {
    error += (x[i] - meanX) * (y[i] - meanY);
  }
  if (unbiased) {
    return error / (x.length - 1);
  } else {
    return error / x.length;
  }
}

/**
 * Asserts that value is truthy.
 * @param value - Value to check.
 * @param message - Optional error message to throw.
 */
function assert(value, message) {
  if (!value) {
    throw new Error(message || 'unreachable');
  }
}
/**
 * Makes sure that all cases are handled
 * @param x - cases of value to check
 */
function assertUnreachable(x) {
  throw new Error(`unreachable: ${String(x)}`);
}

/**
 * Get the clamp function for an image (depends on the image bit depth).
 * @param image - The image for which the clamp function is needed.
 * @returns The clamp function.
 */
function getClamp(image) {
  if (image.maxValue === 255) {
    return clamp255;
  } else {
    assert(image.maxValue === 65535);
    return clamp65535;
  }
}
/**
 * Clamp value for 8-bit images.
 * @param value - Value to clamp.
 * @returns The clamped value.
 */
function clamp255(value) {
  return Math.min(Math.max(value, 0), 255);
}
/**
 * Clamp value for 16-bit images.
 * @param value - Value to clamp.
 * @returns The clamped value.
 */
function clamp65535(value) {
  return Math.min(Math.max(value, 0), 65535);
}
/**
 * Get a function that clamps a value to a given range.
 * @param min - Lower threshold.
 * @param max - Upper threshold.
 * @returns The clamping function.
 */
function getClampFromTo(min, max) {
  return function clamp(value) {
    return Math.max(Math.min(value, max), min);
  };
}

/**
 * Get the coordinates of random points inside of the given dimensions, spread with a
 * gaussian distribution around the center of the dimensions.
 * The reference point with coordinates (0,0) is the center of the patch.
 * @param width - Width in which the points should be.
 * @param height - Height in which the points should be.
 * @param options - Get gaussian points options.
 * @returns An array of random points with a gaussian distribution.
 */
function getGaussianPoints(width, height, options = {}) {
  const {
    nbPoints = 1024,
    xSeed = 0,
    ySeed = 1,
    sigma
  } = options;
  const xCoordinates = getGaussianValues(width, xSeed, nbPoints, sigma);
  const yCoordinates = getGaussianValues(height, ySeed, nbPoints, sigma);
  const points = [];
  for (let i = 0; i < nbPoints; i++) {
    points.push({
      column: xCoordinates[i],
      row: yCoordinates[i]
    });
  }
  return points;
}
/**
 * Generate an array of values
 * that follow a gaussian distribution with a mean value of zero.
 * @param size - Specifies the width of the gaussian distribution.
 * @param seed - Seed for the random generator.
 * @param nbValues - Number of values wanted.
 * @param sigma - The standard deviation. The default value is the optimal SD for BRIEF.
 * @returns Array of values with gaussian distribution.
 */
function getGaussianValues(size, seed, nbValues, sigma = size / 5) {
  const width = (size - 1) / 2;
  const array = createRandomArray({
    distribution: 'normal',
    seed,
    length: nbValues,
    standardDeviation: sigma,
    mean: 0
  });
  const clamp = getClampFromTo(-width, width);
  return array.map(value => {
    const rounded = Math.round(value);
    return clamp(rounded);
  });
}

/**
 * Crop the source image to given dimensions around the origin.
 * @param image - Source image.
 * @param origin - Center point for the crop.
 * @param patchSize - Size of the returned image.
 * @returns The square image around the origin extracted from the source image.
 */
function extractSquareImage(image, origin, patchSize) {
  const cropOffset = (patchSize - 1) / 2;
  const cropOrigin = {
    column: origin.column - cropOffset,
    row: origin.row - cropOffset
  };
  return image.crop({
    origin: cropOrigin,
    width: patchSize,
    height: patchSize
  });
}

/**
 * Get the patch around the keypoint with given size.
 * @param image - Image from which to extract the patch.
 * @param keypoint - Keypoint around which to extract the patch.
 * @param options - Get keypoint patch options.
 * @returns The patch around the keypoint.
 */
function getKeypointPatch(image, keypoint, options = {}) {
  const {
    patchSize = 31
  } = options;
  // crop smallest square surrounding the tilted patch of the keypoint
  // we have to handle the fact that this square can have even dimensions
  const radAngle = keypoint.angle * Math.PI / 180;
  const rawWidth = Math.floor(patchSize * (Math.abs(Math.cos(radAngle)) + Math.abs(Math.sin(radAngle))));
  const cropWidth = rawWidth % 2 ? rawWidth : rawWidth + 1;
  // we are not allowing keypoints that are too close to the border of the image
  const borderDistance = getRadius(cropWidth);
  if (!checkBorderDistance(image, keypoint.origin, borderDistance)) {
    throw new RangeError('keypoint is too close to border for given patch size');
  }
  const cropped = extractSquareImage(image, keypoint.origin, cropWidth);
  const rotated = cropped.transformRotate(-keypoint.angle, {
    center: 'center',
    interpolationType: 'nearest'
  });
  const cropOrigin = rotated.getCoordinates('center');
  const result = extractSquareImage(rotated, cropOrigin, patchSize);
  return result;
}

/**
 * Generate the rBRIEF descriptors for the desired keypoints of an image.
 * The rBRIEF descriptors are presented in these articles:
 * - ORB article: DOI: 10.1109/ICCV.2011.6126544
 * - rBRIEF article: DOI: 10.1007/978-3-642-15561-1_56.
 * @param image - Source image of the keypoints.
 * @param keypoints - Keypoints for which the descriptors are wanted.
 * @param options - Get rotated BRIEF descriptors options.
 * @returns The descriptors for the given keypoints.
 */
function getBriefDescriptors(image, keypoints, options = {}) {
  const {
    patchSize = 31,
    descriptorLength = 256,
    smoothingOptions = {
      sigma: Math.sqrt(2),
      size: Math.min(image.height, image.width, 9)
    },
    pointsDistributionOptions
  } = options;
  checkProcessable$1(image, {
    alpha: false,
    colorModel: 'GREY'
  });
  if (!(patchSize % 2)) {
    throw new TypeError('patchSize must be an odd integer');
  }
  if (Math.min(image.width, image.height) < patchSize) {
    throw new RangeError(`image is too small for patchSize = ${patchSize}`);
  }
  const gaussianPoints = getGaussianPoints(patchSize, patchSize, {
    ...pointsDistributionOptions,
    nbPoints: descriptorLength * 2
  });
  const smoothed = image.gaussianBlur(smoothingOptions);
  const descriptors = [];
  const filteredKeypoints = [];
  for (const keypoint of keypoints) {
    let patch;
    try {
      patch = getKeypointPatch(smoothed, keypoint, {
        patchSize
      });
    } catch {
      continue;
    }
    if (patch === null) continue;
    const descriptor = new Uint8Array(descriptorLength);
    for (let i = 0; i < descriptorLength; i++) {
      const p1 = gaussianPoints[i];
      const p2 = gaussianPoints[i + descriptorLength];
      descriptor[i] = Number(compareIntensity(patch, p1, p2));
    }
    descriptors.push(descriptor);
    filteredKeypoints.push(keypoint);
  }
  return {
    keypoints: filteredKeypoints,
    descriptors
  };
}

/**
 * Get the keypoints and corresponding descriptors for an image.
 * @param image - Image to process.
 * @param options - Get brief options.
 * @returns The Brief (keypoints and corresponding descriptors).
 */
function getBrief(image, options = {}) {
  const {
    centroidPatchDiameter = 15,
    bestKptRadius = 10,
    minScore
  } = options;
  const allSourceKeypoints = getOrientedFastKeypoints(image, {
    centroidPatchDiameter
  });
  const sourceKeypoints = getBestKeypointsInRadius(allSourceKeypoints, bestKptRadius);
  const brief = getBriefDescriptors(image, sourceKeypoints);
  if (minScore) {
    for (let i = 0; i < brief.keypoints.length; i++) {
      if (brief.keypoints[i].score < minScore) {
        return {
          keypoints: brief.keypoints.slice(0, i - 1),
          descriptors: brief.descriptors.slice(0, i - 1)
        };
      }
    }
  }
  return brief;
}

/**
 * Compute the pq order intensity moment of the image
 * relatively to the origin defined in the options.
 * Original article: {@link https://doi.org/10.1006/cviu.1998.0719}.
 * @see {@link https://en.wikipedia.org/wiki/Image_moment}
 * @param image - Image to process. Should have an odd number of rows and columns.
 * @param p - Order along x.
 * @param q - Order along y.
 * @param options - Get intensity moment options.
 * @returns The intensity moment of order pq.
 */
function getIntensityMoment(image, p, q, options = {}) {
  const {
    origin = image.getCoordinates('center')
  } = options;
  const moment = new Array(image.channels).fill(0);
  for (let row = 0; row < image.height; row++) {
    for (let column = 0; column < image.width; column++) {
      const xDistance = column - origin.column;
      const yDistance = row - origin.row;
      for (let channel = 0; channel < image.channels; channel++) {
        const intensity = image.getValue(column, row, channel);
        moment[channel] += xDistance ** p * yDistance ** q * intensity;
      }
    }
  }
  return moment;
}

/**
 * Compute the intensity centroid of an image for each channel relatively to the center of the image.
 * Original article: {@link https://doi.org/10.1006/cviu.1998.0719}.
 * @see {@link https://en.wikipedia.org/wiki/Image_moment}
 * @param image - Image to process.
 * @returns The intensity centroid of each channel of the image.
 */
function getIntensityCentroid(image) {
  const moment10 = getIntensityMoment(image, 1, 0);
  const moment01 = getIntensityMoment(image, 0, 1);
  const moment00 = getIntensityMoment(image, 0, 0);
  const centroid = [];
  for (let channel = 0; channel < image.channels; channel++) {
    if (moment00[channel] === 0) {
      centroid.push({
        column: 0,
        row: 0
      });
    } else {
      centroid.push({
        column: moment10[channel] / moment00[channel],
        row: moment01[channel] / moment00[channel]
      });
    }
  }
  return centroid;
}

/**
 * Compute the Hamming distance between two bit strings.
 * @see {@link https://en.wikipedia.org/wiki/Hamming_distance}
 * @param descriptor1 - First bit string.
 * @param descriptor2 - Second bit string.
 * @returns The Hamming distance.
 */
function getHammingDistance(descriptor1, descriptor2) {
  let sum = 0;
  for (let i = 0; i < descriptor1.length; i++) {
    sum += descriptor1[i] ^ descriptor2[i];
  }
  return sum;
}

/**
 * Find the best match for each of the source descriptors using brute force matching.
 * @param source - Source descriptors.
 * @param destination - Destination descriptors.
 * @param options - Brute force amtch options.
 * @returns The best match for each source descriptor.
 */
function bruteForceOneMatch(source, destination, options = {}) {
  const {
    sort = !!options.nbBestMatches,
    nbBestMatches = source.length
  } = options;
  const matches = [];
  for (let sourceIndex = 0; sourceIndex < source.length; sourceIndex++) {
    let minDistance = Number.POSITIVE_INFINITY;
    let index = 0;
    for (let destinationIndex = 0; destinationIndex < destination.length; destinationIndex++) {
      const distance = getHammingDistance(source[sourceIndex], destination[destinationIndex]);
      if (distance < minDistance) {
        minDistance = distance;
        index = destinationIndex;
      }
    }
    matches.push({
      sourceIndex,
      destinationIndex: index,
      distance: minDistance
    });
  }
  if (sort) {
    matches.sort((a, b) => a.distance - b.distance);
  }
  return matches.slice(0, nbBestMatches);
}

/**
 * Sort array of matches by source index and then destination index.
 * @param matches - Array of matches to sort.
 * @returns Sorted copy of the array of matches.
 */
function sortBySourceDest(matches) {
  const sorted = matches.slice();
  sorted.sort((match1, match2) => {
    if (match1.sourceIndex < match2.sourceIndex) return -1;
    if (match1.sourceIndex > match2.sourceIndex) return 1;
    return match1.destinationIndex - match2.destinationIndex;
  });
  return sorted;
}
/**
 * Sort array of matches by destination index and then source index.
 * @param matches - Array of matches to sort.
 * @returns Sorted copy of the array of matches.
 */
function sortByDestSource(matches) {
  const sorted = matches.slice();
  sorted.sort((match1, match2) => {
    if (match1.destinationIndex < match2.destinationIndex) return -1;
    if (match1.destinationIndex > match2.destinationIndex) return 1;
    return match1.sourceIndex - match2.sourceIndex;
  });
  return sorted;
}

/**
 * Get the crosscheck matches from the source and destination descriptors.
 * @param source - Source descriptors.
 * @param destination - Destination descriptors.
 * @returns The array of crossckeck matches.
 */
function getCrosscheckMatches(source, destination) {
  const srcMatches = bruteForceOneMatch(source, destination);
  const dstMatches = bruteForceOneMatch(destination, source);
  return crosscheck(srcMatches, dstMatches);
}
/**
 * Return the indices of pairs the keypoints that are mutually the best match.
 * This means that if B is the best match for A, A should be the best match for B.
 * The distance of the resulting matches is the maximum distance between the two.
 * @param srcDstMatches - Best matches computed from source do destination.
 * @param dstSrcMatches - Best matches computed from destination to source.
 * @returns The pairs of keypoints that are mutually the best match.
 */
function crosscheck(srcDstMatches, dstSrcMatches) {
  const result = [];
  const sortedSrcDst = sortBySourceDest(srcDstMatches);
  const sortedDstSrc = sortByDestSource(dstSrcMatches);
  let pointer1 = 0;
  let pointer2 = 0;
  while (pointer1 < sortedSrcDst.length && pointer2 < sortedDstSrc.length) {
    const match1 = sortedSrcDst[pointer1];
    const match2 = sortedDstSrc[pointer2];
    if (match1.sourceIndex > match2.destinationIndex) {
      pointer2++;
    } else if (match1.sourceIndex < match2.destinationIndex) {
      pointer1++;
    } else if (match1.destinationIndex > match2.sourceIndex) {
      pointer2++;
    } else if (match1.destinationIndex < match2.sourceIndex) {
      pointer1++;
    } else {
      result.push({
        distance: Math.max(match1.distance, match2.distance),
        sourceIndex: match1.sourceIndex,
        destinationIndex: match1.destinationIndex
      });
      pointer1++;
      pointer2++;
    }
  }
  return result;
}

/**
 * Validate an array of channels.
 * @param channels - Array of channels.
 * @param image - The image being processed.
 */
function validateChannels(channels, image) {
  for (const channel of channels) {
    validateChannel(channel, image);
  }
}
/**
 * Validates that a channel index passed by the user is within range and is an integer.
 * @param channel - Channel index to validate.
 * @param image - The image being processed.
 */
function validateChannel(channel, image) {
  if (!Number.isInteger(channel) || channel >= image.channels || channel < 0) {
    throw new RangeError(`invalid channel: ${channel}. It must be a positive integer smaller than ${image.channels}`);
  }
}
/**
 * Validates that array of svalues passed by the user are positive and within range.
 * @param values - Array of values to validate.
 * @param image - Image from which the values come.
 */
function validateValues(values, image) {
  for (const value of values) {
    validateValue(value, image);
  }
}
/**
 * Validates that a value passed by the user is positive and within range.
 * @param value - Value to validate.
 * @param image - Image from which the value comes.
 */
function validateValue(value, image) {
  if (value > image.maxValue || value < 0) {
    throw new RangeError(`invalid value: ${value}. It must be a positive value smaller than ${image.maxValue + 1}`);
  }
}
/**
 * Validate that two images are compatible for comparison functions.
 * @param image - First image.
 * @param other - Second image.
 */
function validateForComparison(image, other) {
  if (image.width !== other.width || image.height !== other.height) {
    throw new RangeError('both images must have the same size');
  }
  if (image.alpha !== other.alpha || image.bitDepth !== other.bitDepth) {
    throw new RangeError('both images must have the same alpha and bitDepth');
  }
  if (image.channels !== other.channels) {
    throw new RangeError('both images must have the same number of channels');
  }
}
/**
 * Checks if the given color is valid.
 * @param color - Color to check.
 * @param image - Image.
 */
function validateColor(color, image) {
  validateChannel(color.length - 1, image);
  validateValues(color, image);
}

/**
 *
 * Divides image pixels by a certain value.
 * @param image - image to which division will be applied.
 * @param value - Value by which each pixel will be divided.
 * @param options - Divide options
 * @returns image.
 */
function divide(image, value, options = {}) {
  const {
    channels = new Array(image.channels).fill(0).map((value, index) => index)
  } = options;
  validateChannels(channels, image);
  if (value === 0) {
    throw new TypeError(`Cannot divide by 0`);
  }
  const newImage = getOutputImage(image, options, {
    clone: true
  });
  if (channels.length === 0) {
    return newImage;
  }
  for (const channel of channels) {
    for (let row = 0; row < newImage.height; row++) {
      for (let column = 0; column < newImage.width; column++) {
        const newIntensity = newImage.getValue(column, row, channel) / value;
        newImage.setClampedValue(column, row, channel, newIntensity);
      }
    }
  }
  return newImage;
}

/**
 * Compute the Root Mean Square Error (RMSE) between two images. It is just the square root of the MSE.
 * @see {@link https://en.wikipedia.org/wiki/Root-mean-square_deviation}
 * @param image - First image.
 * @param otherImage - Second image.
 * @returns RMSE of the two images.
 */
function computeRmse(image, otherImage) {
  const globalMse = computeMse(image, otherImage);
  return Math.sqrt(globalMse);
}
/**
 * Compute the Mean Square Error (MSE) between two images.
 * The input images can have any number of channels.
 * @param image - First image.
 * @param otherImage - Second image.
 * @returns MSE of the two images.
 */
function computeMse(image, otherImage) {
  const difference = image.subtract(otherImage, {
    absolute: true
  });
  let sum = 0;
  for (let i = 0; i < image.size; i++) {
    for (let channel = 0; channel < image.channels; channel++) {
      const value = difference.getValueByIndex(i, channel);
      sum += value ** 2;
    }
  }
  return sum / (image.size * image.channels);
}

/**
 * Compute the Peak signal-to-noise ratio (PSNR) between two images.
 * The larger the PSNR, the more similar the images.
 * @see {@link https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio}
 * @param image - First image.
 * @param otherImage - Second image.
 * @returns PSNR of the two images in decibels.
 */
function computePsnr(image, otherImage) {
  const rmsePixel = computeRmse(image, otherImage);
  return 20 * Math.log10(image.maxValue / (rmsePixel + Number.MIN_VALUE));
}

/**
 * Get the default color for a given color model.
 * The color is black for images and 1 for masks.
 * @param image - The used image.
 * @returns Default color.
 */
function getDefaultColor(image) {
  return M$2(image.colorModel).with('GREY', () => [0]).with('GREYA', () => [0, image.maxValue]).with('RGB', () => [0, 0, 0]).with('RGBA', () => [0, 0, 0, image.maxValue]).with('BINARY', () => [1]).exhaustive();
}

/**
 * Blend the given pixel with the pixel at the specified location in the image.
 * @param image - The image with which to blend.
 * @param column - Column of the target pixel.
 * @param row - Row of the target pixel.
 * @param color - Color with which to blend the image pixel. Default: `Opaque black`.
 */
function setBlendedPixel(image, column, row, color) {
  color = color ?? getDefaultColor(image);
  if (!image.alpha) {
    image.setPixel(column, row, color);
  } else {
    assert(image instanceof Image);
    const sourceAlpha = color.at(-1);
    if (sourceAlpha === image.maxValue) {
      image.setPixel(column, row, color);
      return;
    }
    const targetAlpha = image.getValue(column, row, image.channels - 1);
    const newAlpha = sourceAlpha + targetAlpha * (1 - sourceAlpha / image.maxValue);
    image.setValue(column, row, image.channels - 1, newAlpha);
    for (let component = 0; component < image.components; component++) {
      const sourceComponent = color[component];
      const targetComponent = image.getValue(column, row, component);
      const newComponent = (sourceComponent * sourceAlpha + targetComponent * targetAlpha * (1 - sourceAlpha / image.maxValue)) / newAlpha;
      image.setValue(column, row, component, newComponent);
    }
  }
}

/**
 * Blend the given pixel with the pixel at the specified location in the image if the pixel is in image's bounds.
 * @param image - The image with which to blend.
 * @param column - Column of the target pixel.
 * @param row - Row of the target pixel.
 * @param color - Color with which to blend the image pixel. Default: `Opaque black`.
 */
function setBlendedVisiblePixel(image, column, row, color) {
  if (column >= 0 && column < image.width && row >= 0 && row < image.height) {
    setBlendedPixel(image, column, row, color);
  }
}

/**
 * Round a point to the nearest integer.
 * @param point - Point to round.
 * @returns The rounded point.
 */
function roundPoint(point) {
  return {
    row: Math.round(point.row),
    column: Math.round(point.column)
  };
}

/**
 * Draw a circle defined by center and radius.
 * @param image - Image to process.
 * @param center - Circle center point.
 * @param radius - Circle radius.
 * @param options - Draw circle options.
 * @returns The original drawn image.
 */
function drawCircleOnImage(image, center, radius, options = {}) {
  const newImage = getOutputImage(image, options, {
    clone: true
  });
  const {
    strokeColor = getDefaultColor(newImage),
    fillColor
  } = options;
  validateColor(strokeColor, newImage);
  checkProcessable$1(newImage, {
    bitDepth: [8, 16]
  });
  if (radius < 0) {
    throw new RangeError('circle radius must be positive');
  }
  center = roundPoint(center);
  radius = Math.round(radius);
  if (radius === 0) {
    setBlendedVisiblePixel(newImage, center.column, center.row, strokeColor);
    return newImage;
  }
  if (!fillColor) {
    index_umdExports.circle(center.column, center.row, radius, (column, row) => {
      setBlendedVisiblePixel(newImage, column, row, strokeColor);
    });
  } else {
    if (radius === 1) {
      setBlendedVisiblePixel(newImage, center.column, center.row, fillColor);
    }
    //Starting points for the top and bottom row of the circle.
    let prevRow = center.row + radius;
    let index = 0;
    index_umdExports.circle(center.column, center.row, radius, (column, row) => {
      setBlendedVisiblePixel(newImage, column, row, strokeColor);
      // Filling the first line of the circle.
      if (index === 0) {
        newImage.drawLine({
          row,
          column: column - 1
        }, {
          row,
          column: center.column - (column - center.column - 1)
        }, {
          strokeColor: fillColor,
          out: newImage
        });
      }
      // The algorithm used is Bresenham's circle algorithm (@link https://www.geeksforgeeks.org/bresenhams-circle-drawing-algorithm/) to find points that constitute the circle outline. However, in this algorithm The circle is divided in 4 parts instead of 8: top, right, bottom and left.
      // The algorithm draws a point per quadrant until the circle is complete.
      // We use bottom (index % 4 === 1, quadrant 2) point of the outline to fill the circle with color.
      // Filling half of the circle.
      if (index % 4 === 1 && prevRow !== row) {
        // For quadrant 2, column < center.column
        newImage.drawLine({
          row,
          column: column + 1
        }, {
          row,
          column: center.column - (column - center.column + 1)
        }, {
          strokeColor: fillColor,
          out: newImage
        });
        prevRow = row;
        // Filling top half of the circle.
        newImage.drawLine({
          row: center.row - (row - center.row),
          column: column + 1
        }, {
          row: center.row - (row - center.row),
          column: center.column - (column - center.column + 1)
        }, {
          strokeColor: fillColor,
          out: newImage
        });
      }
      index++;
    });
  }
  return newImage;
}

/**
 * Draw a line defined by two points onto an image.
 * @param image - Image to process.
 * @param from - Line starting point.
 * @param to - Line ending point.
 * @param options - Draw Line options.
 * @returns The mask with the line drawing.
 */
function drawLineOnImage(image, from, to, options = {}) {
  const newImage = getOutputImage(image, options, {
    clone: true
  });
  const {
    strokeColor = getDefaultColor(newImage),
    origin = {
      column: 0,
      row: 0
    }
  } = options;
  validateColor(strokeColor, newImage);
  checkProcessable$1(newImage, {
    bitDepth: [8, 16]
  });
  index_umdExports.line(Math.round(origin.column + from.column), Math.round(origin.row + from.row), Math.round(origin.column + to.column), Math.round(origin.row + to.row), (column, row) => {
    setBlendedVisiblePixel(newImage, column, row, strokeColor);
  });
  return newImage;
}

/**
 * Draw a line defined by two points onto a mask.
 * @param mask - Mask to process.
 * @param from - Line starting point.
 * @param to - Line ending point.
 * @param options - Draw Line options.
 * @returns The mask with the line drawing.
 */
function drawLineOnMask(mask, from, to, options = {}) {
  const {
    origin = {
      column: 0,
      row: 0
    }
  } = options;
  const newMask = maskToOutputMask(mask, options, {
    clone: true
  });
  index_umdExports.line(Math.round(origin.column + from.column), Math.round(origin.row + from.row), Math.round(origin.column + to.column), Math.round(origin.row + to.row), (column, row) => {
    newMask.setVisiblePixel(column, row, [1]);
  });
  return newMask;
}

/**
 * Draw a polyline defined by an array of points on an image.
 * @param image - Image to process.
 * @param points - Polyline array of points.
 * @param options - Draw polyline options.
 * @returns The image with the polyline drawing.
 */
function drawPolylineOnImage(image, points, options = {}) {
  const {
    strokeColor: color = getDefaultColor(image),
    origin = {
      column: 0,
      row: 0
    }
  } = options;
  checkProcessable$1(image, {
    bitDepth: [8, 16]
  });
  const newImage = getOutputImage(image, options, {
    clone: true
  });
  validateColor(color, newImage);
  for (let i = 0; i < points.length - 1; i++) {
    const from = points[i];
    const to = points[i + 1];
    newImage.drawLine(from, to, {
      out: newImage,
      strokeColor: color,
      origin
    });
  }
  return newImage;
}

/**
 * Draw a polyline defined by an array of points on an image.
 * @param mask - Mask to process.
 * @param points - Polyline array of points.
 * @param options - Draw polyline options.
 * @returns The mask with the polyline drawing.
 */
function drawPolylineOnMask(mask, points, options = {}) {
  const newImage = maskToOutputMask(mask, options, {
    clone: true
  });
  for (let i = 0; i < points.length - 1; i++) {
    const from = points[i];
    const to = points[i + 1];
    newImage.drawLine(from, to, {
      out: newImage,
      origin: options.origin
    });
  }
  return newImage;
}

var orientation = {exports: {}};

var twoProduct_1 = twoProduct$1;
var SPLITTER = +(Math.pow(2, 27) + 1.0);
function twoProduct$1(a, b, result) {
  var x = a * b;
  var c = SPLITTER * a;
  var abig = c - a;
  var ahi = c - abig;
  var alo = a - ahi;
  var d = SPLITTER * b;
  var bbig = d - b;
  var bhi = d - bbig;
  var blo = b - bhi;
  var err1 = x - ahi * bhi;
  var err2 = err1 - alo * bhi;
  var err3 = err2 - ahi * blo;
  var y = alo * blo - err3;
  if (result) {
    result[0] = y;
    result[1] = x;
    return result;
  }
  return [y, x];
}

var robustSum = linearExpansionSum;

//Easy case: Add two scalars
function scalarScalar$1(a, b) {
  var x = a + b;
  var bv = x - a;
  var av = x - bv;
  var br = b - bv;
  var ar = a - av;
  var y = ar + br;
  if (y) {
    return [y, x];
  }
  return [x];
}
function linearExpansionSum(e, f) {
  var ne = e.length | 0;
  var nf = f.length | 0;
  if (ne === 1 && nf === 1) {
    return scalarScalar$1(e[0], f[0]);
  }
  var n = ne + nf;
  var g = new Array(n);
  var count = 0;
  var eptr = 0;
  var fptr = 0;
  var abs = Math.abs;
  var ei = e[eptr];
  var ea = abs(ei);
  var fi = f[fptr];
  var fa = abs(fi);
  var a, b;
  if (ea < fa) {
    b = ei;
    eptr += 1;
    if (eptr < ne) {
      ei = e[eptr];
      ea = abs(ei);
    }
  } else {
    b = fi;
    fptr += 1;
    if (fptr < nf) {
      fi = f[fptr];
      fa = abs(fi);
    }
  }
  if (eptr < ne && ea < fa || fptr >= nf) {
    a = ei;
    eptr += 1;
    if (eptr < ne) {
      ei = e[eptr];
      ea = abs(ei);
    }
  } else {
    a = fi;
    fptr += 1;
    if (fptr < nf) {
      fi = f[fptr];
      fa = abs(fi);
    }
  }
  var x = a + b;
  var bv = x - a;
  var y = b - bv;
  var q0 = y;
  var q1 = x;
  var _x, _bv, _av, _br, _ar;
  while (eptr < ne && fptr < nf) {
    if (ea < fa) {
      a = ei;
      eptr += 1;
      if (eptr < ne) {
        ei = e[eptr];
        ea = abs(ei);
      }
    } else {
      a = fi;
      fptr += 1;
      if (fptr < nf) {
        fi = f[fptr];
        fa = abs(fi);
      }
    }
    b = q0;
    x = a + b;
    bv = x - a;
    y = b - bv;
    if (y) {
      g[count++] = y;
    }
    _x = q1 + x;
    _bv = _x - q1;
    _av = _x - _bv;
    _br = x - _bv;
    _ar = q1 - _av;
    q0 = _ar + _br;
    q1 = _x;
  }
  while (eptr < ne) {
    a = ei;
    b = q0;
    x = a + b;
    bv = x - a;
    y = b - bv;
    if (y) {
      g[count++] = y;
    }
    _x = q1 + x;
    _bv = _x - q1;
    _av = _x - _bv;
    _br = x - _bv;
    _ar = q1 - _av;
    q0 = _ar + _br;
    q1 = _x;
    eptr += 1;
    if (eptr < ne) {
      ei = e[eptr];
    }
  }
  while (fptr < nf) {
    a = fi;
    b = q0;
    x = a + b;
    bv = x - a;
    y = b - bv;
    if (y) {
      g[count++] = y;
    }
    _x = q1 + x;
    _bv = _x - q1;
    _av = _x - _bv;
    _br = x - _bv;
    _ar = q1 - _av;
    q0 = _ar + _br;
    q1 = _x;
    fptr += 1;
    if (fptr < nf) {
      fi = f[fptr];
    }
  }
  if (q0) {
    g[count++] = q0;
  }
  if (q1) {
    g[count++] = q1;
  }
  if (!count) {
    g[count++] = 0.0;
  }
  g.length = count;
  return g;
}

var twoSum$1 = fastTwoSum;
function fastTwoSum(a, b, result) {
  var x = a + b;
  var bv = x - a;
  var av = x - bv;
  var br = b - bv;
  var ar = a - av;
  if (result) {
    result[0] = ar + br;
    result[1] = x;
    return result;
  }
  return [ar + br, x];
}

var twoProduct = twoProduct_1;
var twoSum = twoSum$1;
var robustScale = scaleLinearExpansion;
function scaleLinearExpansion(e, scale) {
  var n = e.length;
  if (n === 1) {
    var ts = twoProduct(e[0], scale);
    if (ts[0]) {
      return ts;
    }
    return [ts[1]];
  }
  var g = new Array(2 * n);
  var q = [0.1, 0.1];
  var t = [0.1, 0.1];
  var count = 0;
  twoProduct(e[0], scale, q);
  if (q[0]) {
    g[count++] = q[0];
  }
  for (var i = 1; i < n; ++i) {
    twoProduct(e[i], scale, t);
    var pq = q[1];
    twoSum(pq, t[0], q);
    if (q[0]) {
      g[count++] = q[0];
    }
    var a = t[1];
    var b = q[1];
    var x = a + b;
    var bv = x - a;
    var y = b - bv;
    q[1] = x;
    if (y) {
      g[count++] = y;
    }
  }
  if (q[1]) {
    g[count++] = q[1];
  }
  if (count === 0) {
    g[count++] = 0.0;
  }
  g.length = count;
  return g;
}

var robustDiff = robustSubtract;

//Easy case: Add two scalars
function scalarScalar(a, b) {
  var x = a + b;
  var bv = x - a;
  var av = x - bv;
  var br = b - bv;
  var ar = a - av;
  var y = ar + br;
  if (y) {
    return [y, x];
  }
  return [x];
}
function robustSubtract(e, f) {
  var ne = e.length | 0;
  var nf = f.length | 0;
  if (ne === 1 && nf === 1) {
    return scalarScalar(e[0], -f[0]);
  }
  var n = ne + nf;
  var g = new Array(n);
  var count = 0;
  var eptr = 0;
  var fptr = 0;
  var abs = Math.abs;
  var ei = e[eptr];
  var ea = abs(ei);
  var fi = -f[fptr];
  var fa = abs(fi);
  var a, b;
  if (ea < fa) {
    b = ei;
    eptr += 1;
    if (eptr < ne) {
      ei = e[eptr];
      ea = abs(ei);
    }
  } else {
    b = fi;
    fptr += 1;
    if (fptr < nf) {
      fi = -f[fptr];
      fa = abs(fi);
    }
  }
  if (eptr < ne && ea < fa || fptr >= nf) {
    a = ei;
    eptr += 1;
    if (eptr < ne) {
      ei = e[eptr];
      ea = abs(ei);
    }
  } else {
    a = fi;
    fptr += 1;
    if (fptr < nf) {
      fi = -f[fptr];
      fa = abs(fi);
    }
  }
  var x = a + b;
  var bv = x - a;
  var y = b - bv;
  var q0 = y;
  var q1 = x;
  var _x, _bv, _av, _br, _ar;
  while (eptr < ne && fptr < nf) {
    if (ea < fa) {
      a = ei;
      eptr += 1;
      if (eptr < ne) {
        ei = e[eptr];
        ea = abs(ei);
      }
    } else {
      a = fi;
      fptr += 1;
      if (fptr < nf) {
        fi = -f[fptr];
        fa = abs(fi);
      }
    }
    b = q0;
    x = a + b;
    bv = x - a;
    y = b - bv;
    if (y) {
      g[count++] = y;
    }
    _x = q1 + x;
    _bv = _x - q1;
    _av = _x - _bv;
    _br = x - _bv;
    _ar = q1 - _av;
    q0 = _ar + _br;
    q1 = _x;
  }
  while (eptr < ne) {
    a = ei;
    b = q0;
    x = a + b;
    bv = x - a;
    y = b - bv;
    if (y) {
      g[count++] = y;
    }
    _x = q1 + x;
    _bv = _x - q1;
    _av = _x - _bv;
    _br = x - _bv;
    _ar = q1 - _av;
    q0 = _ar + _br;
    q1 = _x;
    eptr += 1;
    if (eptr < ne) {
      ei = e[eptr];
    }
  }
  while (fptr < nf) {
    a = fi;
    b = q0;
    x = a + b;
    bv = x - a;
    y = b - bv;
    if (y) {
      g[count++] = y;
    }
    _x = q1 + x;
    _bv = _x - q1;
    _av = _x - _bv;
    _br = x - _bv;
    _ar = q1 - _av;
    q0 = _ar + _br;
    q1 = _x;
    fptr += 1;
    if (fptr < nf) {
      fi = -f[fptr];
    }
  }
  if (q0) {
    g[count++] = q0;
  }
  if (q1) {
    g[count++] = q1;
  }
  if (!count) {
    g[count++] = 0.0;
  }
  g.length = count;
  return g;
}

(function (module) {

  var twoProduct = twoProduct_1;
  var robustSum$1 = robustSum;
  var robustScale$1 = robustScale;
  var robustSubtract = robustDiff;
  var NUM_EXPAND = 5;
  var EPSILON = 1.1102230246251565e-16;
  var ERRBOUND3 = (3.0 + 16.0 * EPSILON) * EPSILON;
  var ERRBOUND4 = (7.0 + 56.0 * EPSILON) * EPSILON;
  function orientation_3(sum, prod, scale, sub) {
    return function orientation3Exact(m0, m1, m2) {
      var p = sum(sum(prod(m1[1], m2[0]), prod(-m2[1], m1[0])), sum(prod(m0[1], m1[0]), prod(-m1[1], m0[0])));
      var n = sum(prod(m0[1], m2[0]), prod(-m2[1], m0[0]));
      var d = sub(p, n);
      return d[d.length - 1];
    };
  }
  function orientation_4(sum, prod, scale, sub) {
    return function orientation4Exact(m0, m1, m2, m3) {
      var p = sum(sum(scale(sum(prod(m2[1], m3[0]), prod(-m3[1], m2[0])), m1[2]), sum(scale(sum(prod(m1[1], m3[0]), prod(-m3[1], m1[0])), -m2[2]), scale(sum(prod(m1[1], m2[0]), prod(-m2[1], m1[0])), m3[2]))), sum(scale(sum(prod(m1[1], m3[0]), prod(-m3[1], m1[0])), m0[2]), sum(scale(sum(prod(m0[1], m3[0]), prod(-m3[1], m0[0])), -m1[2]), scale(sum(prod(m0[1], m1[0]), prod(-m1[1], m0[0])), m3[2]))));
      var n = sum(sum(scale(sum(prod(m2[1], m3[0]), prod(-m3[1], m2[0])), m0[2]), sum(scale(sum(prod(m0[1], m3[0]), prod(-m3[1], m0[0])), -m2[2]), scale(sum(prod(m0[1], m2[0]), prod(-m2[1], m0[0])), m3[2]))), sum(scale(sum(prod(m1[1], m2[0]), prod(-m2[1], m1[0])), m0[2]), sum(scale(sum(prod(m0[1], m2[0]), prod(-m2[1], m0[0])), -m1[2]), scale(sum(prod(m0[1], m1[0]), prod(-m1[1], m0[0])), m2[2]))));
      var d = sub(p, n);
      return d[d.length - 1];
    };
  }
  function orientation_5(sum, prod, scale, sub) {
    return function orientation5Exact(m0, m1, m2, m3, m4) {
      var p = sum(sum(sum(scale(sum(scale(sum(prod(m3[1], m4[0]), prod(-m4[1], m3[0])), m2[2]), sum(scale(sum(prod(m2[1], m4[0]), prod(-m4[1], m2[0])), -m3[2]), scale(sum(prod(m2[1], m3[0]), prod(-m3[1], m2[0])), m4[2]))), m1[3]), sum(scale(sum(scale(sum(prod(m3[1], m4[0]), prod(-m4[1], m3[0])), m1[2]), sum(scale(sum(prod(m1[1], m4[0]), prod(-m4[1], m1[0])), -m3[2]), scale(sum(prod(m1[1], m3[0]), prod(-m3[1], m1[0])), m4[2]))), -m2[3]), scale(sum(scale(sum(prod(m2[1], m4[0]), prod(-m4[1], m2[0])), m1[2]), sum(scale(sum(prod(m1[1], m4[0]), prod(-m4[1], m1[0])), -m2[2]), scale(sum(prod(m1[1], m2[0]), prod(-m2[1], m1[0])), m4[2]))), m3[3]))), sum(scale(sum(scale(sum(prod(m2[1], m3[0]), prod(-m3[1], m2[0])), m1[2]), sum(scale(sum(prod(m1[1], m3[0]), prod(-m3[1], m1[0])), -m2[2]), scale(sum(prod(m1[1], m2[0]), prod(-m2[1], m1[0])), m3[2]))), -m4[3]), sum(scale(sum(scale(sum(prod(m3[1], m4[0]), prod(-m4[1], m3[0])), m1[2]), sum(scale(sum(prod(m1[1], m4[0]), prod(-m4[1], m1[0])), -m3[2]), scale(sum(prod(m1[1], m3[0]), prod(-m3[1], m1[0])), m4[2]))), m0[3]), scale(sum(scale(sum(prod(m3[1], m4[0]), prod(-m4[1], m3[0])), m0[2]), sum(scale(sum(prod(m0[1], m4[0]), prod(-m4[1], m0[0])), -m3[2]), scale(sum(prod(m0[1], m3[0]), prod(-m3[1], m0[0])), m4[2]))), -m1[3])))), sum(sum(scale(sum(scale(sum(prod(m1[1], m4[0]), prod(-m4[1], m1[0])), m0[2]), sum(scale(sum(prod(m0[1], m4[0]), prod(-m4[1], m0[0])), -m1[2]), scale(sum(prod(m0[1], m1[0]), prod(-m1[1], m0[0])), m4[2]))), m3[3]), sum(scale(sum(scale(sum(prod(m1[1], m3[0]), prod(-m3[1], m1[0])), m0[2]), sum(scale(sum(prod(m0[1], m3[0]), prod(-m3[1], m0[0])), -m1[2]), scale(sum(prod(m0[1], m1[0]), prod(-m1[1], m0[0])), m3[2]))), -m4[3]), scale(sum(scale(sum(prod(m2[1], m3[0]), prod(-m3[1], m2[0])), m1[2]), sum(scale(sum(prod(m1[1], m3[0]), prod(-m3[1], m1[0])), -m2[2]), scale(sum(prod(m1[1], m2[0]), prod(-m2[1], m1[0])), m3[2]))), m0[3]))), sum(scale(sum(scale(sum(prod(m2[1], m3[0]), prod(-m3[1], m2[0])), m0[2]), sum(scale(sum(prod(m0[1], m3[0]), prod(-m3[1], m0[0])), -m2[2]), scale(sum(prod(m0[1], m2[0]), prod(-m2[1], m0[0])), m3[2]))), -m1[3]), sum(scale(sum(scale(sum(prod(m1[1], m3[0]), prod(-m3[1], m1[0])), m0[2]), sum(scale(sum(prod(m0[1], m3[0]), prod(-m3[1], m0[0])), -m1[2]), scale(sum(prod(m0[1], m1[0]), prod(-m1[1], m0[0])), m3[2]))), m2[3]), scale(sum(scale(sum(prod(m1[1], m2[0]), prod(-m2[1], m1[0])), m0[2]), sum(scale(sum(prod(m0[1], m2[0]), prod(-m2[1], m0[0])), -m1[2]), scale(sum(prod(m0[1], m1[0]), prod(-m1[1], m0[0])), m2[2]))), -m3[3])))));
      var n = sum(sum(sum(scale(sum(scale(sum(prod(m3[1], m4[0]), prod(-m4[1], m3[0])), m2[2]), sum(scale(sum(prod(m2[1], m4[0]), prod(-m4[1], m2[0])), -m3[2]), scale(sum(prod(m2[1], m3[0]), prod(-m3[1], m2[0])), m4[2]))), m0[3]), scale(sum(scale(sum(prod(m3[1], m4[0]), prod(-m4[1], m3[0])), m0[2]), sum(scale(sum(prod(m0[1], m4[0]), prod(-m4[1], m0[0])), -m3[2]), scale(sum(prod(m0[1], m3[0]), prod(-m3[1], m0[0])), m4[2]))), -m2[3])), sum(scale(sum(scale(sum(prod(m2[1], m4[0]), prod(-m4[1], m2[0])), m0[2]), sum(scale(sum(prod(m0[1], m4[0]), prod(-m4[1], m0[0])), -m2[2]), scale(sum(prod(m0[1], m2[0]), prod(-m2[1], m0[0])), m4[2]))), m3[3]), scale(sum(scale(sum(prod(m2[1], m3[0]), prod(-m3[1], m2[0])), m0[2]), sum(scale(sum(prod(m0[1], m3[0]), prod(-m3[1], m0[0])), -m2[2]), scale(sum(prod(m0[1], m2[0]), prod(-m2[1], m0[0])), m3[2]))), -m4[3]))), sum(sum(scale(sum(scale(sum(prod(m2[1], m4[0]), prod(-m4[1], m2[0])), m1[2]), sum(scale(sum(prod(m1[1], m4[0]), prod(-m4[1], m1[0])), -m2[2]), scale(sum(prod(m1[1], m2[0]), prod(-m2[1], m1[0])), m4[2]))), m0[3]), scale(sum(scale(sum(prod(m2[1], m4[0]), prod(-m4[1], m2[0])), m0[2]), sum(scale(sum(prod(m0[1], m4[0]), prod(-m4[1], m0[0])), -m2[2]), scale(sum(prod(m0[1], m2[0]), prod(-m2[1], m0[0])), m4[2]))), -m1[3])), sum(scale(sum(scale(sum(prod(m1[1], m4[0]), prod(-m4[1], m1[0])), m0[2]), sum(scale(sum(prod(m0[1], m4[0]), prod(-m4[1], m0[0])), -m1[2]), scale(sum(prod(m0[1], m1[0]), prod(-m1[1], m0[0])), m4[2]))), m2[3]), scale(sum(scale(sum(prod(m1[1], m2[0]), prod(-m2[1], m1[0])), m0[2]), sum(scale(sum(prod(m0[1], m2[0]), prod(-m2[1], m0[0])), -m1[2]), scale(sum(prod(m0[1], m1[0]), prod(-m1[1], m0[0])), m2[2]))), -m4[3]))));
      var d = sub(p, n);
      return d[d.length - 1];
    };
  }
  function orientation(n) {
    var fn = n === 3 ? orientation_3 : n === 4 ? orientation_4 : orientation_5;
    return fn(robustSum$1, twoProduct, robustScale$1, robustSubtract);
  }
  var orientation3Exact = orientation(3);
  var orientation4Exact = orientation(4);
  var CACHED = [function orientation0() {
    return 0;
  }, function orientation1() {
    return 0;
  }, function orientation2(a, b) {
    return b[0] - a[0];
  }, function orientation3(a, b, c) {
    var l = (a[1] - c[1]) * (b[0] - c[0]);
    var r = (a[0] - c[0]) * (b[1] - c[1]);
    var det = l - r;
    var s;
    if (l > 0) {
      if (r <= 0) {
        return det;
      } else {
        s = l + r;
      }
    } else if (l < 0) {
      if (r >= 0) {
        return det;
      } else {
        s = -(l + r);
      }
    } else {
      return det;
    }
    var tol = ERRBOUND3 * s;
    if (det >= tol || det <= -tol) {
      return det;
    }
    return orientation3Exact(a, b, c);
  }, function orientation4(a, b, c, d) {
    var adx = a[0] - d[0];
    var bdx = b[0] - d[0];
    var cdx = c[0] - d[0];
    var ady = a[1] - d[1];
    var bdy = b[1] - d[1];
    var cdy = c[1] - d[1];
    var adz = a[2] - d[2];
    var bdz = b[2] - d[2];
    var cdz = c[2] - d[2];
    var bdxcdy = bdx * cdy;
    var cdxbdy = cdx * bdy;
    var cdxady = cdx * ady;
    var adxcdy = adx * cdy;
    var adxbdy = adx * bdy;
    var bdxady = bdx * ady;
    var det = adz * (bdxcdy - cdxbdy) + bdz * (cdxady - adxcdy) + cdz * (adxbdy - bdxady);
    var permanent = (Math.abs(bdxcdy) + Math.abs(cdxbdy)) * Math.abs(adz) + (Math.abs(cdxady) + Math.abs(adxcdy)) * Math.abs(bdz) + (Math.abs(adxbdy) + Math.abs(bdxady)) * Math.abs(cdz);
    var tol = ERRBOUND4 * permanent;
    if (det > tol || -det > tol) {
      return det;
    }
    return orientation4Exact(a, b, c, d);
  }];
  function slowOrient(args) {
    var proc = CACHED[args.length];
    if (!proc) {
      proc = CACHED[args.length] = orientation(args.length);
    }
    return proc.apply(undefined, args);
  }
  function proc(slow, o0, o1, o2, o3, o4, o5) {
    return function getOrientation(a0, a1, a2, a3, a4) {
      switch (arguments.length) {
        case 0:
        case 1:
          return 0;
        case 2:
          return o2(a0, a1);
        case 3:
          return o3(a0, a1, a2);
        case 4:
          return o4(a0, a1, a2, a3);
        case 5:
          return o5(a0, a1, a2, a3, a4);
      }
      var s = new Array(arguments.length);
      for (var i = 0; i < arguments.length; ++i) {
        s[i] = arguments[i];
      }
      return slow(s);
    };
  }
  function generateOrientationProc() {
    while (CACHED.length <= NUM_EXPAND) {
      CACHED.push(orientation(CACHED.length));
    }
    module.exports = proc.apply(undefined, [slowOrient].concat(CACHED));
    for (var i = 0; i <= NUM_EXPAND; ++i) {
      module.exports[i] = CACHED[i];
    }
  }
  generateOrientationProc();
})(orientation);
var orientationExports = orientation.exports;

var robustPnp = robustPointInPolygon$1;
var orient = orientationExports;
function robustPointInPolygon$1(vs, point) {
  var x = point[0];
  var y = point[1];
  var n = vs.length;
  var inside = 1;
  var lim = n;
  for (var i = 0, j = n - 1; i < lim; j = i++) {
    var a = vs[i];
    var b = vs[j];
    var yi = a[1];
    var yj = b[1];
    if (yj < yi) {
      if (yj < y && y < yi) {
        var s = orient(a, b, point);
        if (s === 0) {
          return 0;
        } else {
          inside ^= 0 < s | 0;
        }
      } else if (y === yi) {
        var c = vs[(i + 1) % n];
        var yk = c[1];
        if (yi < yk) {
          var s = orient(a, b, point);
          if (s === 0) {
            return 0;
          } else {
            inside ^= 0 < s | 0;
          }
        }
      }
    } else if (yi < yj) {
      if (yi < y && y < yj) {
        var s = orient(a, b, point);
        if (s === 0) {
          return 0;
        } else {
          inside ^= s < 0 | 0;
        }
      } else if (y === yi) {
        var c = vs[(i + 1) % n];
        var yk = c[1];
        if (yk < yi) {
          var s = orient(a, b, point);
          if (s === 0) {
            return 0;
          } else {
            inside ^= s < 0 | 0;
          }
        }
      }
    } else if (y === yi) {
      var x0 = Math.min(a[0], b[0]);
      var x1 = Math.max(a[0], b[0]);
      if (i === 0) {
        while (j > 0) {
          var k = (j + n - 1) % n;
          var p = vs[k];
          if (p[1] !== y) {
            break;
          }
          var px = p[0];
          x0 = Math.min(x0, px);
          x1 = Math.max(x1, px);
          j = k;
        }
        if (j === 0) {
          if (x0 <= x && x <= x1) {
            return 0;
          }
          return 1;
        }
        lim = j + 1;
      }
      var y0 = vs[(j + n - 1) % n][1];
      while (i + 1 < lim) {
        var p = vs[i + 1];
        if (p[1] !== y) {
          break;
        }
        var px = p[0];
        x0 = Math.min(x0, px);
        x1 = Math.max(x1, px);
        i += 1;
      }
      if (x0 <= x && x <= x1) {
        return 0;
      }
      var y1 = vs[(i + 1) % n][1];
      if (x < x0 && y0 < y !== y1 < y) {
        inside ^= 1;
      }
    }
  }
  return 2 * inside - 1;
}
var robustPointInPolygon = /*@__PURE__*/getDefaultExportFromCjs(robustPnp);

/**
 * Convert object points into array points.
 * @param points - Array of points as objects.
 * @returns Array of points as arrays.
 */
function arrayPointsToObjects(points) {
  const result = [];
  for (const point of points) {
    result.push([point.column, point.row]);
  }
  return result;
}

/**
 * Draw a polygon defined by an array of points onto an image.
 * @param image - Image to process.
 * @param points - Polygon vertices.
 * @param options - Draw Line options.
 * @returns The image with the polygon drawing.
 */
function drawPolygonOnImage(image, points, options = {}) {
  const {
    fillColor,
    origin = {
      column: 0,
      row: 0
    },
    ...otherOptions
  } = options;
  checkProcessable$1(image, {
    bitDepth: [8, 16]
  });
  const newImage = getOutputImage(image, options, {
    clone: true
  });
  if (fillColor === undefined) {
    return newImage.drawPolyline([...points, points[0]], {
      origin,
      ...otherOptions
    });
  } else {
    validateColor(fillColor, newImage);
    const filteredPoints = deleteDuplicates(points);
    const arrayPoints = arrayPointsToObjects(filteredPoints);
    for (let row = 0; row < newImage.height; row++) {
      for (let column = 0; column < newImage.width; column++) {
        if (robustPointInPolygon(arrayPoints, [column, row]) === -1) {
          setBlendedVisiblePixel(newImage, Math.round(origin.column) + column, Math.round(origin.row) + row, fillColor);
        }
      }
    }
  }
  return newImage.drawPolyline([...points, points[0]], {
    origin,
    ...otherOptions
  });
}

/**
 * Draw a polygon defined by an array of points on a mask.
 * @param mask - Mask to process.
 * @param points - Polygon vertices.
 * @param options - Draw Line options.
 * @returns The mask with the polygon drawing.
 */
function drawPolygonOnMask(mask, points, options = {}) {
  const {
    filled = false,
    origin = {
      column: 0,
      row: 0
    },
    ...otherOptions
  } = options;
  const newMask = maskToOutputMask(mask, options, {
    clone: true
  });
  if (!filled) {
    return newMask.drawPolyline([...points, points[0]], {
      origin,
      ...otherOptions
    });
  }
  const filteredPoints = deleteDuplicates(points);
  const arrayPoints = arrayPointsToObjects(filteredPoints);
  for (let row = 0; row < newMask.height; row++) {
    for (let column = 0; column < newMask.width; column++) {
      if (robustPointInPolygon(arrayPoints, [column, row]) === -1) {
        newMask.setBit(Math.round(origin.column) + column, Math.round(origin.row) + row, 1);
      }
    }
  }
  return newMask.drawPolyline([...points, points[0]], {
    origin,
    ...otherOptions
  });
}

/**
 * Draw a rectangle defined by position of the top-left corner, width and height.
 * @param image - Image to process.
 * @param options - Draw rectangle options.
 * @returns The image with the rectangle drawing.
 */
function drawRectangle(image, options = {}) {
  const {
    width: rectangleWidth = image.width,
    height: rectangleHeight = image.height,
    origin = {
      column: 0,
      row: 0
    },
    strokeColor = getDefaultColor(image),
    fillColor
  } = options;
  const width = Math.round(rectangleWidth);
  const height = Math.round(rectangleHeight);
  const column = Math.round(origin.column);
  const row = Math.round(origin.row);
  let newImage;
  if (image instanceof Image) {
    checkProcessable$1(image, {
      bitDepth: [8, 16]
    });
    validateColor(strokeColor, image);
    if (fillColor) {
      validateColor(fillColor, image);
    }
    newImage = getOutputImage(image, options, {
      clone: true
    });
  } else {
    newImage = maskToOutputMask(image, options, {
      clone: true
    });
  }
  for (let currentColumn = column; currentColumn < column + width; currentColumn++) {
    setBlendedVisiblePixel(newImage, currentColumn, row, strokeColor);
    setBlendedVisiblePixel(newImage, currentColumn, row + height - 1, strokeColor);
  }
  for (let currentRow = row + 1; currentRow < row + height - 1; currentRow++) {
    setBlendedVisiblePixel(newImage, column, currentRow, strokeColor);
    setBlendedVisiblePixel(newImage, column + width - 1, currentRow, strokeColor);
  }
  if (fillColor) {
    for (let currentRow = row + 1; currentRow < row + height - 1; currentRow++) {
      for (let currentColumn = column + 1; currentColumn < column + width - 1; currentColumn++) {
        setBlendedVisiblePixel(newImage, currentColumn, currentRow, fillColor);
      }
    }
  }
  return newImage;
}

/**
 * Draw a set of points on an image or a mask.
 * @param image - The image on which to draw the points.
 * @param points - Array of points.
 * @param options - Draw points on Image options.
 * @returns New mask.
 */
function drawPoints(image, points, options = {}) {
  const {
    color = getDefaultColor(image),
    origin = {
      row: 0,
      column: 0
    }
  } = options;
  let newImage;
  if (image instanceof Image) {
    newImage = getOutputImage(image, options, {
      clone: true
    });
    validateColor(color, newImage);
  } else {
    newImage = maskToOutputMask(image, options, {
      clone: true
    });
  }
  checkProcessable$1(newImage, {
    bitDepth: [1, 8, 16]
  });
  for (const point of points) {
    setBlendedVisiblePixel(newImage, Math.round(origin.column + point.column), Math.round(origin.row + point.row), color);
  }
  return newImage;
}

/**
 * Draw a marker on the image.
 * @param image - Image to process.
 * @param point - Marker center point.
 * @param options - Draw marker options.
 * @returns The image with the marker drawing.
 */
function drawMarker(image, point, options) {
  const newImage = getOutputImage(image, options, {
    clone: true
  });
  const {
    strokeColor = getDefaultColor(newImage),
    fillColor,
    shape = 'cross',
    size: markerSize = 1
  } = options;
  const size = Math.round(markerSize);
  validateColor(strokeColor, newImage);
  if (fillColor) {
    validateColor(fillColor, newImage);
  }
  checkProcessable$1(newImage, {
    bitDepth: [8, 16]
  });
  if (shape === 'circle') {
    newImage.drawCircle(point, size, {
      strokeColor,
      fillColor,
      out: newImage
    });
  }
  if (shape === 'triangle') {
    const points = [{
      row: point.row - size,
      column: point.column
    }, {
      row: point.row,
      column: point.column + size
    }, {
      row: point.row,
      column: point.column - size
    }];
    newImage.drawPolygon(points, {
      strokeColor,
      fillColor,
      out: newImage
    });
  }
  if (shape === 'cross') {
    newImage.drawLine({
      row: point.row - size,
      column: point.column
    }, {
      row: point.row + size,
      column: point.column
    }, {
      strokeColor,
      out: newImage
    });
    newImage.drawLine({
      row: point.row,
      column: point.column - size
    }, {
      row: point.row,
      column: point.column + size
    }, {
      strokeColor,
      out: newImage
    });
  }
  if (shape === 'square') {
    const origin = {
      row: point.row - (size - 1) / 2,
      column: point.column - (size - 1) / 2
    };
    newImage.drawRectangle({
      origin,
      width: size,
      height: size,
      strokeColor,
      fillColor,
      out: newImage
    });
  }
  return newImage;
}

/**
 * Draw markers on the image.
 * @param image - Image to process.
 * @param points - Markers center points.
 * @param options - Draw marker options.
 * @returns The image with the markers drawing.
 */
function drawMarkers(image, points, options = {}) {
  const newImage = getOutputImage(image, options, {
    clone: true
  });
  for (const point of points) {
    drawMarker(newImage, point, {
      ...options,
      out: newImage
    });
  }
  return newImage;
}

/**
 * Perform an AND operation on two masks.
 * @param mask - First mask.
 * @param otherMask - Second mask.
 * @param options - And options.
 * @returns AND of the two masks.
 */
function and(mask, otherMask, options) {
  const newMask = maskToOutputMask(mask, options);
  if (mask.width !== otherMask.width || mask.height !== otherMask.height) {
    throw new RangeError('both masks must have the same size');
  }
  for (let i = 0; i < newMask.size; i++) {
    if (mask.getBitByIndex(i) && otherMask.getBitByIndex(i)) {
      newMask.setBitByIndex(i, 1);
    } else {
      newMask.setBitByIndex(i, 0);
    }
  }
  return newMask;
}

function checkSize(size) {
  if (!Number.isInteger(size) || size < 1) {
    throw new TypeError(`size must be a positive integer. Got ${size}`);
  }
}
function checkKernel$1(kernel) {
  if (kernel.length === 0 || kernel.length % 2 !== 1) {
    throw new RangeError(`kernel must have an odd positive length. Got ${kernel.length}`);
  }
}
function checkBorderType(borderType) {
  if (borderType !== 'CONSTANT' && borderType !== 'CUT') {
    throw new RangeError(`unexpected border type: ${borderType}`);
  }
}
function checkInputLength(actual, expected) {
  if (actual !== expected) {
    throw new RangeError(`input length (${actual}) does not match setup size (${expected})`);
  }
}
function createArray(len) {
  const array = [];
  for (var i = 0; i < len; i++) {
    array.push(0);
  }
  return array;
}

class DirectConvolution {
  constructor(size, kernel, borderType = 'CONSTANT') {
    checkSize(size);
    checkKernel$1(kernel);
    checkBorderType(borderType);
    this.size = size;
    this.kernelOffset = (kernel.length - 1) / 2;
    this.outputSize = borderType === 'CONSTANT' ? size : size - 2 * this.kernelOffset;
    this.output = createArray(this.outputSize);
    this.kernel = kernel;
    this.kernelSize = kernel.length;
    this.borderType = borderType;
  }
  convolve(input) {
    checkInputLength(input.length, this.size);
    this.output.fill(0);
    if (this.borderType === 'CONSTANT') {
      this._convolutionBorder0(input);
    } else {
      this._convolutionBorderCut(input);
    }
    return this.output;
  }
  _convolutionBorder0(input) {
    for (let i = 0; i < this.size; i++) {
      for (let j = 0; j < this.kernelSize; j++) {
        this.output[i] += interpolateInput(input, i - this.kernelOffset + j) * this.kernel[j];
      }
    }
  }
  _convolutionBorderCut(input) {
    for (let i = this.kernelOffset; i < this.size - this.kernelOffset; i++) {
      const index = i - this.kernelOffset;
      for (let j = 0; j < this.kernelSize; j++) {
        this.output[index] += input[index + j] * this.kernel[j];
      }
    }
  }
}
function interpolateInput(input, idx) {
  if (idx < 0) return 0;else if (idx >= input.length) return 0;
  return input[idx];
}

const BorderType$1 = {
  CUT: 'CUT'
};

const BorderType = {
  CONSTANT: 'constant',
  REPLICATE: 'replicate',
  REFLECT: 'reflect',
  WRAP: 'wrap',
  REFLECT_101: 'reflect101'
};
/**
 * Pick the border interpolation algorithm.
 * The different algorithms are illustrated here:
 * @see {@link https://vovkos.github.io/doxyrest-showcase/opencv/sphinx_rtd_theme/enum_cv_BorderTypes.html}
 * @param type - The border type.
 * @param value - A pixel value if BorderType.CONSTANT is used.
 * @returns The border interpolation function.
 */
function getBorderInterpolation(type, value) {
  if (typeof value === 'number') {
    value = new Array(4).fill(value);
  }
  return M$2(type).with('constant', () => getInterpolateConstant(value)).with('replicate', () => interpolateReplicate).with('reflect', () => interpolateReflect).with('reflect101', () => interpolateReflect101).with('wrap', () => interpolateWrap).exhaustive();
}
function checkRange(point, length) {
  if (point <= 0 - length || point >= length + length - 1) {
    throw new RangeError('border must be smaller than the original image');
  }
}
function getInterpolateConstant(value) {
  return function interpolateConstant(column, row, channel, image) {
    const newColumn = interpolateConstantPoint(column, image.width);
    const newRow = interpolateConstantPoint(row, image.height);
    if (newColumn === -1 || newRow === -1) {
      return value[channel];
    }
    return image.getValue(newColumn, newRow, channel);
  };
}
/**
 * Interpolate using a constant point.
 * @param point - The point to interpolate.
 * @param length  - The length of the image.
 * @returns The interpolated point.
 */
function interpolateConstantPoint(point, length) {
  if (point >= 0 && point < length) {
    return point;
  }
  return -1;
}
function interpolateReplicate(column, row, channel, image) {
  return image.getValue(interpolateReplicatePoint(column, image.width), interpolateReplicatePoint(row, image.height), channel);
}
/**
 * Interpolate by replicating the border.
 * @param point - The point to interpolate.
 * @param length - The length of the image.
 * @returns The interpolated point.
 */
function interpolateReplicatePoint(point, length) {
  if (point >= 0 && point < length) {
    return point;
  }
  checkRange(point, length);
  if (point < 0) {
    return 0;
  } else {
    return length - 1;
  }
}
function interpolateReflect(column, row, channel, image) {
  return image.getValue(interpolateReflectPoint(column, image.width), interpolateReflectPoint(row, image.height), channel);
}
/**
 * Interpolate by reflecting the border.
 * @param point - The point to interpolate.
 * @param length - The length of the image.
 * @returns The interpolated point.
 */
function interpolateReflectPoint(point, length) {
  if (point >= 0 && point < length) {
    return point;
  }
  checkRange(point, length);
  if (point < 0) {
    return -1 - point;
  } else {
    return length + length - 1 - point;
  }
}
function interpolateWrap(column, row, channel, image) {
  return image.getValue(interpolateWrapPoint(column, image.width), interpolateWrapPoint(row, image.height), channel);
}
/**
 * Interpolate by wrapping the border.
 * @param point - The point to interpolate.
 * @param length - The length of the image.
 * @returns The interpolated point.
 */
function interpolateWrapPoint(point, length) {
  if (point >= 0 && point < length) {
    return point;
  }
  checkRange(point, length);
  if (point < 0) {
    return length + point;
  } else {
    return point - length;
  }
}
function interpolateReflect101(column, row, channel, image) {
  return image.getValue(interpolateReflect101Point(column, image.width), interpolateReflect101Point(row, image.height), channel);
}
/**
 * Interpolate by reflecting the border.
 * @param point - The point to interpolate.
 * @param length - The length of the image.
 * @returns The interpolated point.
 */
function interpolateReflect101Point(point, length) {
  if (point >= 0 && point < length) {
    return point;
  }
  checkRange(point, length);
  if (point < 0) {
    return 0 - point;
  } else {
    return length + length - 2 - point;
  }
}

/**
 * Extend the borders of an image according to the given border type.
 * @param image - Image to extend.
 * @param options - Options.
 * @returns A copy of the image with extended borders.
 */
function extendBorders(image, options) {
  const {
    horizontal,
    vertical,
    borderType = 'reflect101',
    borderValue = getDefaultColor(image)
  } = options;
  if (Array.isArray(borderValue)) {
    validateColor(borderValue, image);
  }
  const interpolateBorder = getBorderInterpolation(borderType, borderValue);
  const newImage = Image.createFrom(image, {
    width: image.width + 2 * horizontal,
    height: image.height + 2 * vertical
  });
  image.copyTo(newImage, {
    origin: {
      column: horizontal,
      row: vertical
    },
    out: newImage
  });
  // Top strip
  for (let row = 0; row < vertical; row++) {
    for (let col = 0; col < newImage.width; col++) {
      for (let channel = 0; channel < image.channels; channel++) {
        const newValue = interpolateBorder(col - horizontal, row - vertical, channel, image);
        newImage.setValue(col, row, channel, newValue);
      }
    }
  }
  // Bottom strip
  for (let row = newImage.height - vertical; row < newImage.height; row++) {
    for (let col = 0; col < newImage.width; col++) {
      for (let channel = 0; channel < image.channels; channel++) {
        const newValue = interpolateBorder(col - horizontal, row - vertical, channel, image);
        newImage.setValue(col, row, channel, newValue);
      }
    }
  }
  // Left strip
  for (let row = vertical; row < newImage.height - vertical; row++) {
    for (let col = 0; col < horizontal; col++) {
      for (let channel = 0; channel < image.channels; channel++) {
        const newValue = interpolateBorder(col - horizontal, row - vertical, channel, image);
        newImage.setValue(col, row, channel, newValue);
      }
    }
  }
  // Right strip
  for (let row = vertical; row < newImage.height - vertical; row++) {
    for (let col = newImage.width - horizontal; col < newImage.width; col++) {
      for (let channel = 0; channel < image.channels; channel++) {
        const newValue = interpolateBorder(col - horizontal, row - vertical, channel, image);
        newImage.setValue(col, row, channel, newValue);
      }
    }
  }
  return newImage;
}

/**
 * Round a pixel value.
 * @param value - Value of the pixel.
 * @returns The rounded value.
 */
function round(value) {
  const integer = Math.trunc(value);
  const decimal = value - integer;
  if (decimal < 0.5) {
    return integer;
  } else if (decimal > 0.5) {
    return integer + 1;
  } else {
    return integer % 2 === 0 ? integer : integer + 1;
  }
}

/**
 * Apply a direct convolution on an image using the specified kernel. The convolution corresponds of a weighted average of the surrounding pixels, the weights being defined in the kernel.
 * @param image - The image to process.
 * @param kernel - Kernel to use for the convolution. Should be a 2D matrix with odd number of rows and columns.
 * @param options - Convolution options.
 * @returns The convoluted image.
 */
function directConvolution(image, kernel, options = {}) {
  const {
    borderType = 'reflect101',
    borderValue = 0
  } = options;
  const convolutedData = rawDirectConvolution(image, kernel, {
    borderType,
    borderValue
  });
  const newImage = getOutputImage(image, options);
  const clamp = getClamp(newImage);
  for (let i = 0; i < image.size; i++) {
    for (let channel = 0; channel < image.channels; channel++) {
      const dataIndex = i * image.channels + channel;
      const newValue = round(clamp(convolutedData[dataIndex]));
      newImage.setValueByIndex(i, channel, newValue);
    }
  }
  return newImage;
}
/**
 * Compute direct convolution of an image and return an array with the raw values.
 * @param image - Image to process.
 * @param kernel - 2D kernel used for the convolution.
 * @param options - Convolution options.
 * @returns Array with the raw convoluted values.
 */
function rawDirectConvolution(image, kernel, options = {}) {
  const {
    borderType = 'reflect101',
    borderValue = getDefaultColor(image)
  } = options;
  if (Array.isArray(borderValue)) {
    validateColor(borderValue, image);
  }
  const interpolateBorder = getBorderInterpolation(borderType, borderValue);
  const result = new Float64Array(image.size * image.channels);
  for (let channel = 0; channel < image.channels; channel++) {
    for (let row = 0; row < image.height; row++) {
      for (let column = 0; column < image.width; column++) {
        const index = getIndex(column, row, image, channel);
        result[index] = computeConvolutionValue(column, row, channel, image, kernel, interpolateBorder, {
          returnRawValue: true
        });
      }
    }
  }
  return result;
}
/**
 * Compute the separable convolution of an image.
 * @param image - Image to convolute.
 * @param kernelX - Kernel along x axis.
 * @param kernelY - Kernel along y axis.
 * @param options - Convolution options.
 * @returns The convoluted image.
 */
function separableConvolution(image, kernelX, kernelY, options = {}) {
  const {
    normalize,
    borderType = 'reflect101',
    borderValue = 0
  } = options;
  if (normalize) {
    [kernelX, kernelY] = normalizeSeparatedKernel(kernelX, kernelY);
  }
  const doubleKernelOffsetX = kernelX.length - 1;
  const kernelOffsetX = doubleKernelOffsetX / 2;
  const doubleKernelOffsetY = kernelY.length - 1;
  const kernelOffsetY = doubleKernelOffsetY / 2;
  const extendedImage = extendBorders(image, {
    horizontal: kernelOffsetX,
    vertical: kernelOffsetY,
    borderType,
    borderValue
  });
  const newImage = Image.createFrom(image);
  const clamp = getClamp(newImage);
  const rowConvolution = new DirectConvolution(extendedImage.width, kernelX, BorderType$1.CUT);
  const columnConvolution = new DirectConvolution(extendedImage.height, kernelY, BorderType$1.CUT);
  const rowData = new Float64Array(extendedImage.width);
  const columnData = new Float64Array(extendedImage.height);
  const convolvedData = new Float64Array(
  // Use `image.width` because convolution with BorderType.CUT reduces the size of the convolved data.
  image.width * extendedImage.height);
  for (let channel = 0; channel < extendedImage.channels; channel++) {
    for (let row = 0; row < extendedImage.height; row++) {
      for (let column = 0; column < extendedImage.width; column++) {
        rowData[column] = extendedImage.getValue(column, row, channel);
      }
      const convolvedRow = rowConvolution.convolve(rowData);
      for (let column = 0; column < image.width; column++) {
        convolvedData[row * image.width + column] = convolvedRow[column];
      }
    }
    for (let column = 0; column < image.width; column++) {
      for (let row = 0; row < extendedImage.height; row++) {
        columnData[row] = convolvedData[row * image.width + column];
      }
      const convolvedColumn = columnConvolution.convolve(columnData);
      for (let row = 0; row < image.height; row++) {
        newImage.setValue(column, row, channel, round(clamp(convolvedColumn[row])));
      }
    }
  }
  return newImage;
}
/**
 * Compute the convolution of a value of a pixel in an image.
 * @param column - Column of the pixel.
 * @param row - Row of the pixel.
 * @param channel - Channel to process.
 * @param image - Image to process.
 * @param kernel - Kernel for the convolutions.
 * @param interpolateBorder - Function to interpolate the border pixels.
 * @param options - Compute convolution value options.
 * @returns The convoluted value.
 */
function computeConvolutionValue(column, row, channel, image, kernel, interpolateBorder, options = {}) {
  let {
    clamp
  } = options;
  const {
    returnRawValue = false
  } = options;
  if (returnRawValue) {
    clamp = undefined;
  }
  let val = 0;
  const kernelWidth = kernel[0].length;
  const kernelHeight = kernel.length;
  const kernelOffsetX = (kernelWidth - 1) / 2;
  const kernelOffsetY = (kernelHeight - 1) / 2;
  for (let kY = 0; kY < kernelHeight; kY++) {
    for (let kX = 0; kX < kernelWidth; kX++) {
      const kernelValue = kernel[kY][kX];
      val += kernelValue * interpolateBorder(column + kX - kernelOffsetX, row + kY - kernelOffsetY, channel, image);
    }
  }
  if (!clamp) {
    return val;
  } else {
    return round(clamp(val));
  }
}
/**
 * Normalize a separated kernel.
 * @param kernelX - Horizontal component of the separated kernel.
 * @param kernelY - Vertical component of the separated kernel.
 * @returns The normalized kernel.
 */
function normalizeSeparatedKernel(kernelX, kernelY) {
  const sumKernelX = kernelX.reduce((prev, current) => prev + current, 0);
  const sumKernelY = kernelY.reduce((prev, current) => prev + current, 0);
  const prod = sumKernelX * sumKernelY;
  if (prod < 0) {
    throw new RangeError('this separated kernel cannot be normalized');
  }
  const factor = 1 / Math.sqrt(Math.abs(prod));
  return [kernelX.map(v => v * factor), kernelY.map(v => v * factor)];
}

/**
 * Blur an image. The pixel in the center becomes an average of the surrounding ones.
 * @param image - Image to blur.
 * @param options - Blur options.
 * @returns The blurred image.
 */
function blur(image, options) {
  const {
    width,
    height
  } = options;
  if (width < 1 || width % 2 === 0) {
    throw new RangeError(`Invalid property "width". Must be an odd number greater than 0. Received ${width}.`);
  }
  if (height < 1 || height % 2 === 0) {
    throw new RangeError(`Invalid property "height". Must be an odd number greater than 0. Received ${height}.`);
  }
  const kernelX = new Array(width).fill(1);
  const kernelY = new Array(height).fill(1);
  return separableConvolution(image, kernelX, kernelY, {
    normalize: true,
    ...options
  });
}

const DerivativeFilter = {
  SOBEL: 'sobel',
  SCHARR: 'scharr',
  PREWITT: 'prewitt'
  // todo: handle even sized kernels to implement Roberts' filter
  // for 2x2 matrices, the current pixel corresponds to the top-left
  //  ROBERTS = 'roberts',
};
/**
 * Apply a derivative filter to an image.
 * @param image - Image to process.
 * @param options - Derivative filter options.
 * @returns The processed image.
 */
function derivativeFilter(image, options = {}) {
  const {
    filter = 'sobel'
  } = options;
  const kernels = M$2(filter).with('sobel', () => ({
    kernelX: SOBEL_X,
    kernelY: SOBEL_Y
  })).with('scharr', () => ({
    kernelX: SCHARR_X,
    kernelY: SCHARR_Y
  })).with('prewitt', () => ({
    kernelX: PREWITT_X,
    kernelY: PREWITT_Y
  })).exhaustive();
  return image.gradientFilter({
    ...kernels,
    ...options
  });
}

const ImageColorModel = {
  GREY: 'GREY',
  GREYA: 'GREYA',
  RGB: 'RGB',
  RGBA: 'RGBA',
  BINARY: 'BINARY'
};
const colorModels = {
  GREY: {
    components: 1,
    alpha: false,
    channels: 1
  },
  GREYA: {
    components: 1,
    alpha: true,
    channels: 2
  },
  RGB: {
    components: 3,
    alpha: false,
    channels: 3
  },
  RGBA: {
    components: 3,
    alpha: true,
    channels: 4
  },
  BINARY: {
    components: 1,
    alpha: false,
    channels: 1
  }
};

/**
 * Increase the contrast of an image by spanning each channel on the range [0, image.maxValue].
 * This algorithm is based on the level algorithm.
 * @param image - The image to enhance.
 * @param options - Increase contrast options.
 * @returns The enhanced image.
 */
function increaseContrast(image, options = {}) {
  const {
    uniform = false
  } = options;
  checkProcessable$1(image, {
    bitDepth: [8, 16]
  });
  const minMax = image.minMax();
  let min = minMax.min;
  let max = minMax.max;
  if (uniform) {
    let maxDiffIndex = -1;
    let previousDiff = -1;
    for (let i = 0; i < minMax.max.length; i++) {
      const difference = minMax.max[i] - minMax.min[i];
      if (difference > previousDiff) {
        maxDiffIndex = i;
        previousDiff = difference;
      }
    }
    min = minMax.min[maxDiffIndex];
    max = minMax.max[maxDiffIndex];
  }
  let channels = new Array(image.components).fill(0).map((value, index) => index);
  if (image.colorModel === ImageColorModel.GREYA) {
    channels = [0];
  } else if (image.colorModel === ImageColorModel.RGBA) {
    channels = [0, 1, 2];
  }
  return image.level({
    inputMin: min,
    inputMax: max,
    outputMin: 0,
    outputMax: image.maxValue,
    channels,
    ...options
  });
}

/**
 * Apply a gaussian filter to an image.
 * @param image - Image to blur.
 * @param options - Gaussian blur options.
 * @returns The blurred image.
 */
function gaussianBlur(image, options) {
  if ('sigma' in options) {
    const {
      sigma,
      size = getSize$1(sigma),
      borderType
    } = options;
    const radius = getRadius(size);
    const kernel = getKernel(radius, sigma);
    return separableConvolution(image, kernel, kernel, {
      borderType
    });
  } else if ('sigmaX' in options && 'sigmaY' in options) {
    const {
      sigmaX,
      sigmaY,
      sizeX = getSize$1(sigmaX),
      sizeY = getSize$1(sigmaY),
      borderType
    } = options;
    const radiusX = getRadius(sizeX);
    const radiusY = getRadius(sizeY);
    const kernelX = getKernel(radiusX, sigmaX);
    const kernelY = getKernel(radiusY, sigmaY);
    return separableConvolution(image, kernelX, kernelY, {
      borderType
    });
  } else {
    throw new TypeError('you must either define sigma or sigmaX and sigmaY in the options argument');
  }
}
function getKernel(radius, sigma) {
  const n = radius * 2 + 1;
  const kernel = new Array(n);
  // TODO: check if sigma can really be 0 or undefined.
  const sigmaX = sigma || ((n - 1) * 0.5 - 1) * 0.3 + 0.8;
  const scale2X = -0.5 / (sigmaX * sigmaX);
  let sum = 0;
  for (let i = 0; i < n; i++) {
    const x = i - radius;
    const t = Math.exp(scale2X * x * x);
    kernel[i] = t;
    sum += t;
  }
  for (let i = 0; i < n; i++) {
    kernel[i] /= sum;
  }
  return kernel;
}
function getSize$1(sigma) {
  return 2 * Math.ceil(2 * sigma) + 1;
}

/**
 * Apply a gradient filter to an image.
 * @param image - The image to process.
 * @param options - Gradient filter options.
 * @returns The gradient image.
 */
function gradientFilter(image, options) {
  const {
    borderType = 'replicate',
    borderValue = 0
  } = options;
  checkProcessable$1(image, {
    bitDepth: [8, 16],
    colorModel: 'GREY'
  });
  if ('kernelX' in options && 'kernelY' in options) {
    const {
      kernelX,
      kernelY
    } = options;
    const gradientX = image.rawDirectConvolution(kernelX, {
      borderType,
      borderValue
    });
    const gradientY = image.rawDirectConvolution(kernelY, {
      borderType,
      borderValue
    });
    const gradient = new Image(image.width, image.height, {
      colorModel: 'GREY'
    });
    for (let i = 0; i < image.size; i++) {
      gradient.setValueByIndex(i, 0, Math.hypot(gradientX[i], gradientY[i]));
    }
    return gradient;
  } else if ('kernelX' in options) {
    return image.directConvolution(options.kernelX, {
      borderType,
      borderValue
    });
  } else if ('kernelY' in options) {
    return image.directConvolution(options.kernelY, {
      borderType,
      borderValue
    });
  } else {
    throw new TypeError(`kernelX and KernelY are not defined`);
  }
}

/**
 * Calculate a new image that is the hypotenuse between the current image and the otherImage.
 * @param image - First image to process.
 * @param otherImage - Second image.
 * @param options - Hypotenuse options.
 * @returns Hypotenuse of the two images.
 */
function hypotenuse(image, otherImage, options = {}) {
  const {
    channels = new Array(image.components).fill(0).map((value, index) => index)
  } = options;
  checkProcessable$1(image, {
    bitDepth: [8, 16]
  });
  if (image.width !== otherImage.width || image.height !== otherImage.height) {
    throw new RangeError('both images must have the same size');
  }
  if (image.alpha !== otherImage.alpha || image.bitDepth !== otherImage.bitDepth) {
    throw new RangeError('both images must have the same alpha and bitDepth');
  }
  if (image.channels !== otherImage.channels) {
    throw new RangeError('both images must have the same number of channels');
  }
  validateChannels(channels, image);
  const newImage = getOutputImage(image, {}, {
    clone: true
  });
  for (const channel of channels) {
    for (let i = 0; i < image.size; i++) {
      const value = Math.hypot(image.getValueByIndex(i, channel), otherImage.getValueByIndex(i, channel));
      newImage.setValueByIndex(i, channel, Math.min(value, newImage.maxValue));
    }
  }
  return newImage;
}

/**
 * Convert image to a different color model.
 * @param image - Image to convert.
 * @param colorModel - New color model.
 * @param options - Convert color options.
 * @returns The converted image.
 */
function convertColor(image, colorModel, options = {}) {
  const canConvert = new Map([['GREY', ['GREYA', 'RGB', 'RGBA']], ['GREYA', ['GREY', 'RGB', 'RGBA']], ['RGB', ['GREY', 'GREYA', 'RGBA']], ['RGBA', ['GREY', 'GREYA', 'RGB']], ['BINARY', ['GREY', 'RGB', 'RGBA']]]);
  if (image.colorModel === colorModel && colorModel !== 'BINARY') {
    return getOutputImage(image, {
      out: options.out
    }, {
      clone: true
    });
  }
  const canConvertTo = canConvert.get(image.colorModel);
  if (!canConvertTo?.includes(colorModel)) {
    throw new RangeError(`conversion from ${image.colorModel} to ${colorModel} not implemented`);
  }
  if (image instanceof Image) {
    const output = getOutputImage(image, options, {
      newParameters: {
        colorModel
      }
    });
    if (image.colorModel === 'GREY' || image.colorModel === 'GREYA') {
      convertGreyToAny(image, output);
    }
    if (image.colorModel === 'RGB' || image.colorModel === 'RGBA') {
      if (colorModel === 'RGB' || colorModel === 'RGBA') {
        convertRgbToRgb(image, output);
      } else {
        // GREYA or GREY
        convertRgbToGrey(image, output);
      }
    }
    if (!image.alpha && output.alpha) {
      output.fillAlpha(output.maxValue);
    }
    if (image.alpha && output.alpha) {
      copyAlpha(image, output);
    }
    return output;
  } else if (colorModel === 'GREY') {
    const output = maskToOutputImage(image, options);
    convertBinaryToGrey(image, output);
    return output;
  } else {
    const img = new Image(image.width, image.height, {
      colorModel
    });
    convertBinaryToRgb(image, img);
    return img;
  }
}
/**
 * Copy alpha channel of source to dest.
 * @param source - Source image.
 * @param dest - Destination image.
 */
function copyAlpha(source, dest) {
  if (source.size !== dest.size) {
    throw new RangeError('source and destination have different sizes');
  }
  if (!source.alpha) {
    throw new RangeError('source image does not have alpha');
  }
  if (!dest.alpha) {
    throw new RangeError('destination does not have alpha');
  }
  for (let i = 0; i < dest.size; i++) {
    dest.setValueByIndex(i, dest.channels - 1, source.getValueByIndex(i, source.channels - 1));
  }
}
/**
 * Convert grey image to other color model.
 * @param image - Image to convert.
 * @param newImage - Converted image.
 */
function convertGreyToAny(image, newImage) {
  for (let i = 0; i < image.size; i++) {
    for (let j = 0; j < newImage.components; j++) {
      newImage.setValueByIndex(i, j, image.getValueByIndex(i, 0));
    }
  }
}
/**
 * Convert RGB image to RGB. Allows to use convert with an RGB target whatever the image color model is.
 * @param image - Image to convert.
 * @param newImage - Converted image.
 */
function convertRgbToRgb(image, newImage) {
  for (let i = 0; i < image.size; i++) {
    for (let j = 0; j < 3; j++) {
      newImage.setValueByIndex(i, j, image.getValueByIndex(i, j));
    }
  }
}
/**
 * Convert RGB image to GREY.
 * @param image - Image to convert.
 * @param newImage - Converted image.
 */
function convertRgbToGrey(image, newImage) {
  for (let i = 0; i < image.size; i++) {
    const r = image.getValueByIndex(i, 0);
    const g = image.getValueByIndex(i, 1);
    const b = image.getValueByIndex(i, 2);
    newImage.setValueByIndex(i, 0, Math.round(0.299 * r + 0.587 * g + 0.114 * b));
  }
}
/**
 * Convert Mask to GREY.
 * @param mask - Mask to convert.
 * @param newImage - Converted image.
 */
function convertBinaryToGrey(mask, newImage) {
  for (let i = 0; i < mask.size; i++) {
    newImage.setValueByIndex(i, 0, mask.getBitByIndex(i) ? newImage.maxValue : 0);
  }
}
/**
 * Convert mask to RGB or RGBA.
 * @param mask - Mask to convert.
 * @param newImage - Converted image.
 */
function convertBinaryToRgb(mask, newImage) {
  const black = new Array(newImage.components).fill(0);
  const white = new Array(newImage.components).fill(newImage.maxValue);
  if (newImage.alpha) {
    black.push(newImage.maxValue);
    white.push(newImage.maxValue);
  }
  for (let i = 0; i < mask.size; i++) {
    newImage.setPixelByIndex(i, mask.getBitByIndex(i) ? white : black);
  }
}

/**
 * Convert the bit depth of an image.
 * @param image - Image to convert.
 * @param newBitDepth - Bit depth to convert to.
 * @param options - Convert bit depth options.
 * @returns Converted image.
 */
function convertBitDepth(image, newBitDepth, options = {}) {
  if (image.bitDepth === newBitDepth) {
    return getOutputImage(image, options, {
      clone: true
    });
  }
  if (newBitDepth !== 8 && newBitDepth !== 16) {
    throw new RangeError(`This image bit depth is not supported: ${newBitDepth}`);
  }
  // Get the output image first - this handles the out option
  const newImage = getOutputImage(image, options, {
    clone: false,
    newParameters: {
      bitDepth: newBitDepth,
      colorModel: image.colorModel
    }
  });
  return newBitDepth === 8 ? convertToUint8(image, newImage) : convertToUint16(image, newImage);
}
/**
 * Convert bit depth to 16 bits.
 * @param image - Image to convert.
 * @param targetImage - Target image to write to.
 * @returns Converted image.
 */
function convertToUint16(image, targetImage) {
  for (let i = 0; i < image.size; i++) {
    for (let j = 0; j < targetImage.channels; j++) {
      targetImage.setValueByIndex(i, j, image.getValueByIndex(i, j) << 8);
    }
  }
  return targetImage;
}
/**
 * Convert bit depth to 8 bits.
 * @param image - Image to convert.
 * @param targetImage - Target image to write to.
 * @returns Converted image.
 */
function convertToUint8(image, targetImage) {
  for (let i = 0; i < image.size; i++) {
    for (let j = 0; j < targetImage.channels; j++) {
      targetImage.setValueByIndex(i, j, image.getValueByIndex(i, j) >> 8);
    }
  }
  return targetImage;
}

/**
 * Check that the coordinates of a point are integers.
 * @param point - Point to check.
 * @param name - Specify name of the point to include in the error message.
 */
function checkPointIsInteger(point, name = 'Point') {
  if (!Number.isInteger(point.row) || !Number.isInteger(point.column)) {
    throw new TypeError(`${name} row and column must be integers`);
  }
}

/**
 * Extract the pixels of an image, as specified in a mask.
 * @param image - The image to process.
 * @param mask - The mask defining which pixels to keep.
 * @param options - Extract options.
 * @returns The extracted image.
 */
function extract(image, mask, options = {}) {
  const {
    origin = {
      row: 0,
      column: 0
    }
  } = options;
  const {
    row,
    column
  } = origin;
  assert(row < image.height && column < image.width && row + mask.width > 0 && column + mask.height > 0, 'extract: image and mask have no overlap');
  checkPointIsInteger(origin, 'Origin');
  const resultWidth = Math.min(image.width, mask.width + column) - Math.max(0, column);
  const resultHeight = Math.min(image.height, mask.height + row) - Math.max(0, row);
  let newImage = new Image(resultWidth, resultHeight, {
    colorModel: image.colorModel,
    origin
  });
  if (newImage.alpha) {
    newImage = newImage.fillAlpha(0);
  }
  const imageStartRow = Math.max(0, row);
  const imageStartColumn = Math.max(0, column);
  const maskStartRow = row < 0 ? -row : 0;
  const maskStartColumn = column < 0 ? -column : 0;
  for (let resultRow = 0; resultRow < resultHeight; resultRow++) {
    for (let resultColumn = 0; resultColumn < resultWidth; resultColumn++) {
      if (mask.getBit(maskStartColumn + resultColumn, maskStartRow + resultRow)) {
        newImage.setPixel(resultColumn, resultRow, image.getPixel(imageStartColumn + resultColumn, imageStartRow + resultRow));
      }
    }
  }
  return newImage;
}

/**
 * Inverse of split. Merges multiple single-channel images into one.
 * @param images - An array of single-channel images.
 * @returns The merged image.
 */
function merge(images) {
  const channels = images.length;
  let colorModel;
  switch (channels) {
    case 2:
      {
        colorModel = 'GREYA';
        break;
      }
    case 3:
      {
        colorModel = 'RGB';
        break;
      }
    case 4:
      {
        colorModel = 'RGBA';
        break;
      }
    default:
      {
        throw new RangeError(`merge expects an array of two to four images. Received ${channels}`);
      }
  }
  const first = images[0];
  if (first.channels !== 1) {
    throw new RangeError(`each image must have one channel. Received ${first.channels}`);
  }
  for (let i = 1; i < channels; i++) {
    const img = images[i];
    if (img.channels !== 1) {
      throw new RangeError(`each image must have one channel. Received ${img.channels}`);
    }
    if (img.width !== first.width || img.height !== first.height || img.bitDepth !== first.bitDepth) {
      throw new RangeError('all images must have the same width, height and bitDepth');
    }
  }
  const newImage = Image.createFrom(first, {
    colorModel
  });
  for (let c = 0; c < channels; c++) {
    const img = images[c];
    for (let i = 0; i < newImage.size; i++) {
      newImage.setValueByIndex(i, c, img.getValueByIndex(i, 0));
    }
  }
  return newImage;
}

/**
 * Create an array of single-channel images based on a multi-channel image.
 * @param image - The image with many channels.
 * @returns Array of single-channel images.
 */
function split(image) {
  const result = [];
  for (let c = 0; c < image.channels; c++) {
    const channel = Image.createFrom(image, {
      colorModel: 'GREY'
    });
    for (let i = 0; i < channel.size; i++) {
      channel.setValueByIndex(i, 0, image.getValueByIndex(i, c));
    }
    result.push(channel);
  }
  return result;
}

/*
 * * see http://rsb.info.nih.gov/ij/developer/source/ij/process/AutoThresholder.java.html.
 * Huang: Implements Huang's fuzzy thresholding method: Huang, L-K & Wang, M-J J (1995),
 * "Image thresholding by minimizing the measure of fuzziness", Pattern Recognition 28(1): 41-51
 */
/**
 * Return a threshold for a histogram using Huang algorithm.
 * @param histogram - Image histogram.
 * @returns The threshold.
 */
function huang(histogram) {
  /* Determine the first non-zero bin */
  let firstBin = 0;
  for (let ih = 0; ih < histogram.length; ih++) {
    if (histogram[ih] !== 0) {
      firstBin = ih;
      break;
    }
  }
  /* Determine the last non-zero bin */
  let lastBin = histogram.length - 1;
  for (let ih = histogram.length - 1; ih >= firstBin; ih--) {
    if (histogram[ih] !== 0) {
      lastBin = ih;
      break;
    }
  }
  const term = 1 / (lastBin - firstBin);
  const mu0 = new Array(histogram.length);
  let sumPix = 0;
  let numPix = 0;
  for (let ih = firstBin; ih < histogram.length; ih++) {
    sumPix += ih * histogram[ih];
    numPix += histogram[ih];
    mu0[ih] = sumPix / numPix;
  }
  const mu1 = new Array(histogram.length);
  sumPix = 0;
  numPix = 0;
  for (let ih = lastBin; ih > 0; ih--) {
    sumPix += ih * histogram[ih];
    numPix += histogram[ih];
    mu1[ih - 1] = sumPix / numPix;
  }
  /* Determine the threshold that minimizes the fuzzy entropy*/
  let threshold = -1;
  let minEnt = Number.MAX_VALUE;
  for (let it = 0; it < histogram.length; it++) {
    let ent = 0;
    let muX;
    for (let ih = 0; ih <= it; ih++) {
      /* Equation (4) in Ref. 1 */
      muX = 1 / (1 + term * Math.abs(ih - mu0[it]));
      if (!(muX < 1e-6 || muX > 0.999999)) {
        /* Equation (6) & (8) in Ref. 1 */
        ent += histogram[ih] * (-muX * Math.log(muX) - (1 - muX) * Math.log(1 - muX));
      }
    }
    for (let ih = it + 1; ih < histogram.length; ih++) {
      /* Equation (4) in Ref. 1 */
      muX = 1 / (1 + term * Math.abs(ih - mu1[it]));
      if (!(muX < 1e-6 || muX > 0.999999)) {
        /* Equation (6) & (8) in Ref. 1 */
        ent += histogram[ih] * (-muX * Math.log(muX) - (1 - muX) * Math.log(1 - muX));
      }
    }
    if (ent < minEnt) {
      minEnt = ent;
      threshold = it;
    }
  }
  return threshold;
}

/*
 *
 * see https://github.com/fiji/Auto_Threshold/blob/master/src/main/java/fiji/threshold/Auto_Threshold.java
 * Intermodes: This assumes a bimodal histogram. Implements the thresholding Prewitt, JMS & Mendelsohn, ML (1966),
 * "The analysis of cell images", Annals of the NewYork Academy of Sciences 128: 1035-1053
 *
 */
/**
 * Return a threshold for a histogram using Intermodes algorithm.
 * @param histogram - Image histogram.
 * @returns The threshold.
 */
function intermodes(histogram) {
  const iHisto = histogram.slice();
  let iter = 0;
  while (!bimodalTest$1(iHisto)) {
    // smooth with a 3 point running mean filter
    let previous = 0;
    let current = 0;
    let next = iHisto[0];
    for (let i = 0; i < histogram.length - 1; i++) {
      previous = current;
      current = next;
      next = iHisto[i + 1];
      iHisto[i] = (previous + current + next) / 3;
    }
    iHisto[histogram.length - 1] = (current + next) / 3;
    iter++;
    assert(iter < 1000, 'Intermodes threshold not found after 1000 iterations');
  }
  // The threshold is the mean between the two peaks.
  let tt = 0;
  for (let i = 1; i < histogram.length - 1; i++) {
    if (iHisto[i - 1] < iHisto[i] && iHisto[i + 1] < iHisto[i]) {
      tt += i;
    }
  }
  return Math.floor(tt / 2);
}
function bimodalTest$1(iHisto) {
  let b = false;
  let modes = 0;
  for (let k = 1; k < iHisto.length - 1; k++) {
    if (iHisto[k - 1] < iHisto[k] && iHisto[k + 1] < iHisto[k]) {
      modes++;
      if (modes > 2) {
        return false;
      }
    }
  }
  if (modes === 2) {
    b = true;
  }
  return b;
}

/*
 * see https://github.com/fiji/Auto_Threshold/blob/master/src/main/java/fiji/threshold/Auto_Threshold.java
 * Isodata: Ridler, TW & Calvard, S (1978), "Picture thresholding using an iterative selection method"
 * IEEE Transactions on Systems, Man and Cybernetics 8: 630-632.
 *
 */
/**
 * Return a threshold for a histogram using Isodata algorithm.
 * @param histogram - Image histogram.
 * @returns The threshold.
 */
function isodata(histogram) {
  let l; // the average grey value of pixels with intensities < g
  let toth; // the the average grey value of pixels with intensities > g
  let totl; // the total the average grey value of pixels with intensities < g
  let h; // the average grey value of pixels with intensities > g
  let g = 0; // threshold value
  for (let i = 1; i < histogram.length; i++) {
    if (histogram[i] > 0) {
      g = i + 1;
      break;
    }
  }
  while (true) {
    l = 0;
    totl = 0;
    for (let i = 0; i < g; i++) {
      totl = totl + histogram[i];
      l = l + histogram[i] * i;
    }
    h = 0;
    toth = 0;
    for (let i = g + 1; i < histogram.length; i++) {
      toth += histogram[i];
      h += histogram[i] * i;
    }
    if (totl > 0 && toth > 0) {
      l /= totl;
      h /= toth;
      if (g === Math.round((l + h) / 2)) {
        break;
      }
    }
    g++;
    assert(g <= histogram.length - 2, 'Threshold not found');
  }
  return g;
}

/*
 * see http://rsb.info.nih.gov/ij/developer/source/ij/process/AutoThresholder.java.html
 * The method is present in: Implements Li's Minimum Cross Entropy thresholding method
 * This implementation is based on the iterative version (Ref. 2nd reference below) of the algorithm.
 *  1) Li, CH & Lee, CK (1993), "Minimum Cross Entropy Thresholding", Pattern Recognition 26(4): 61 625
 *  2) Li, CH & Tam, PKS (1998), "An Iterative Algorithm for Minimum Cross Entropy Thresholding",
 *     Pattern Recognition Letters 18(8): 771-776
 *  3) Sezgin, M & Sankur, B (2004), "Survey over Image Thresholding Techniques and Quantitative Performance
 *     Evaluation",Journal of Electronic Imaging 13(1): 146-165
 * @param histogram - the histogram of the image
 * @param total - the number of pixels in the image
 * @returns {number} - the threshold
 */
/**
 * Return a threshold for a histogram using Li algorithm.
 * @param histogram - Image histogram.
 * @param total - Number of pixels in the image.
 * @returns The threshold.
 */
function li(histogram, total) {
  let threshold;
  let sumBack; /* sum of the background pixels at a given threshold */
  let sumObj; /* sum of the object pixels at a given threshold */
  let numBack; /* number of background pixels at a given threshold */
  let numObj; /* number of object pixels at a given threshold */
  let oldThresh;
  let newThresh;
  let meanBack; /* mean of the background pixels at a given threshold */
  let meanObj; /* mean of the object pixels at a given threshold */
  let mean; /* mean gray-level in the image */
  const tolerance = 0.5; /* threshold tolerance */
  let temp;
  /* Calculate the mean gray-level */
  mean = 0;
  for (let ih = 0; ih < histogram.length; ih++) {
    mean += ih * histogram[ih];
  }
  mean /= total;
  /* Initial estimate */
  newThresh = mean;
  do {
    oldThresh = newThresh;
    threshold = oldThresh + 0.5 | 0; /* range */
    /* Calculate the means of background and object pixels */
    /* Background */
    sumBack = 0;
    numBack = 0;
    for (let ih = 0; ih <= threshold; ih++) {
      sumBack += ih * histogram[ih];
      numBack += histogram[ih];
    }
    meanBack = numBack === 0 ? 0 : sumBack / numBack;
    /* Object */
    sumObj = 0;
    numObj = 0;
    for (let ih = threshold + 1; ih < histogram.length; ih++) {
      sumObj += ih * histogram[ih];
      numObj += histogram[ih];
    }
    meanObj = numObj === 0 ? 0 : sumObj / numObj;
    temp = (meanBack - meanObj) / (Math.log(meanBack) - Math.log(meanObj));
    if (temp < -Number.EPSILON) {
      newThresh = temp - 0.5 | 0;
    } else {
      newThresh = temp + 0.5 | 0;
    }
    /*  Stop the iterations when the difference between the
         new and old threshold values is less than the tolerance */
  } while (Math.abs(newThresh - oldThresh) > tolerance);
  return threshold;
}

/*
 * see http://rsb.info.nih.gov/ij/developer/source/ij/process/AutoThresholder.java.html
 * The method is present in: Implements Kapur-Sahoo-Wong (Maximum Entropy) thresholding method:
 * Kapur, JN; Sahoo, PK & Wong, ACK (1985), "A New Method for Gray-Level Picture Thresholding Using the Entropy of the Histogram",
 * Graphical Models and Image Processing 29(3): 273-285
 * @param histogram - the histogram of the image
 *        total - the number of pixels in the image
 * @returns {number} - the threshold
 */
/**
 * Return a threshold for a histogram using maximal enthropy algorithm.
 * @param histogram - Image histogram.
 * @param total - Number of pixels in the image.
 * @returns The threshold.
 */
function maxEntropy(histogram, total) {
  const normHisto = new Array(histogram.length); // normalized histogram
  for (let ih = 0; ih < histogram.length; ih++) {
    normHisto[ih] = histogram[ih] / total;
  }
  const P1 = new Array(histogram.length); // cumulative normalized histogram
  const P2 = new Array(histogram.length);
  P1[0] = normHisto[0];
  P2[0] = 1 - P1[0];
  for (let ih = 1; ih < histogram.length; ih++) {
    P1[ih] = P1[ih - 1] + normHisto[ih];
    P2[ih] = 1 - P1[ih];
  }
  /* Determine the first non-zero bin */
  let firstBin = 0;
  for (let ih = 0; ih < histogram.length; ih++) {
    if (Math.abs(P1[ih]) >= Number.EPSILON) {
      firstBin = ih;
      break;
    }
  }
  /* Determine the last non-zero bin */
  let lastBin = histogram.length - 1;
  for (let ih = histogram.length - 1; ih >= firstBin; ih--) {
    if (Math.abs(P2[ih]) >= Number.EPSILON) {
      lastBin = ih;
      break;
    }
  }
  // Calculate the total entropy each gray-level
  // and find the threshold that maximizes it
  let threshold = -1;
  let totEnt; // total entropy
  let maxEnt = Number.MIN_VALUE; // max entropy
  let entBack; // entropy of the background pixels at a given threshold
  let entObj; // entropy of the object pixels at a given threshold
  for (let it = firstBin; it <= lastBin; it++) {
    /* Entropy of the background pixels */
    entBack = 0;
    for (let ih = 0; ih <= it; ih++) {
      if (histogram[ih] !== 0) {
        entBack -= normHisto[ih] / P1[it] * Math.log(normHisto[ih] / P1[it]);
      }
    }
    /* Entropy of the object pixels */
    entObj = 0;
    for (let ih = it + 1; ih < histogram.length; ih++) {
      if (histogram[ih] !== 0) {
        entObj -= normHisto[ih] / P2[it] * Math.log(normHisto[ih] / P2[it]);
      }
    }
    /* Total entropy */
    totEnt = entBack + entObj;
    if (maxEnt < totEnt) {
      maxEnt = totEnt;
      threshold = it;
    }
  }
  return threshold;
}

/*
 * The method is present in: Uses the mean of grey levels as the threshold. It is described in:
 * Glasbey, CA (1993), "An analysis of histogram-based thresholding algorithms",
 * CVGIP: Graphical Models and Image Processing 55: 532-537
 * @param histogram - the histogram of the image
 * @param total - the number of pixels in the image
 * @returns {number} - the threshold
 */
/**
 * Return a threshold for a histogram by making its average.
 * @param histogram - Image histogram.
 * @param total - Number of pixels in the image.
 * @returns The threshold.
 */
function mean$1(histogram, total) {
  let sum = 0;
  for (let i = 0; i < histogram.length; i++) {
    sum += i * histogram[i];
  }
  return Math.floor(sum / total);
}

/*
 * see http://rsb.info.nih.gov/ij/developer/source/ij/process/AutoThresholder.java.html
 * The method is present in: An iterative implementation of Kittler and Illingworth's Minimum Error
 * thresholding:Kittler, J & Illingworth, J (1986), "Minimum error thresholding", Pattern Recognition 19: 41-47
 * @param histogram - the histogram of the image
 * @param total - the number of pixels in the image
 * @returns {number} - the threshold
 */
/**
 * Return a threshold for a histogram using Li algorithm.
 * @param histogram - Image histogram.
 * @param total - Number of pixels in the image.
 * @returns The threshold.
 */
function minError(histogram, total) {
  let threshold;
  let Tprev = -2;
  let mu, nu, p, q, sigma2, tau2, w0, w1, w2, sqterm, temp;
  /* Calculate the mean gray-level */
  let mean = 0;
  for (let ih = 0; ih < histogram.length; ih++) {
    mean += ih * histogram[ih];
  }
  mean /= total;
  threshold = mean;
  while (threshold !== Tprev) {
    // Calculate some statistics.
    const sumA1 = sumA(histogram, threshold);
    const sumA2 = sumA(histogram, histogram.length - 1);
    const sumB1 = sumB(histogram, threshold);
    const sumB2 = sumB(histogram, histogram.length - 1);
    const sumC1 = sumC(histogram, threshold);
    const sumC2 = sumC(histogram, histogram.length - 1);
    mu = sumB1 / sumA1;
    nu = (sumB2 - sumB1) / (sumA2 - sumA1);
    p = sumA1 / sumA2;
    q = (sumA2 - sumA1) / sumA2;
    sigma2 = sumC1 / sumA1 - mu * mu;
    tau2 = (sumC2 - sumC1) / (sumA2 - sumA1) - nu * nu;
    // The terms of the quadratic equation to be solved.
    w0 = 1 / sigma2 - 1 / tau2;
    w1 = mu / sigma2 - nu / tau2;
    w2 = mu * mu / sigma2 - nu * nu / tau2 + Math.log10(sigma2 * (q * q) / (tau2 * (p * p)));
    // If the next threshold would be imaginary, return with the current one.
    sqterm = w1 * w1 - w0 * w2;
    if (sqterm < 0) {
      return threshold;
    }
    // The updated threshold is the integer part of the solution of the quadratic equation.
    Tprev = threshold;
    temp = (w1 + Math.sqrt(sqterm)) / w0;
    if (Number.isNaN(temp)) {
      threshold = Tprev;
    } else {
      threshold = Math.floor(temp);
    }
  }
  return threshold;
}
// aux func
function sumA(y, j) {
  let x = 0;
  for (let i = 0; i <= j; i++) {
    x += y[i];
  }
  return x;
}
function sumB(y, j) {
  let x = 0;
  for (let i = 0; i <= j; i++) {
    x += i * y[i];
  }
  return x;
}
function sumC(y, j) {
  let x = 0;
  for (let i = 0; i <= j; i++) {
    x += i * i * y[i];
  }
  return x;
}

// see https://github.com/fiji/Auto_Threshold/blob/master/src/main/java/fiji/threshold/Auto_Threshold.java
// J. M. S. Prewitt and M. L. Mendelsohn, "The analysis of cell images," in
// Annals of the New York Academy of Sciences, vol. 128, pp. 1035-1053, 1966.
// ported to ImageJ plugin by G.Landini from Antti Niemisto's Matlab code (GPL)
// Original Matlab code Copyright (C) 2004 Antti Niemisto
// See http://www.cs.tut.fi/~ant/histthresh/ for an excellent slide presentation
// and the original Matlab code
/**
 * Return a threshold for a histogram.
 * @param histogram - Image histogram.
 * @returns The threshold.
 */
function minimum(histogram) {
  if (histogram.length < 2) {
    // validate that the histogram has at least two color values
    return 0;
  }
  let iterations = 0; // number of iterations of the smoothing process
  let threshold = -1;
  let max = -1; // maximum color value with a greater number of pixels to 0
  let histogramCopy = new Array(histogram.length); // a copy of the histogram
  for (let i = 0; i < histogram.length; i++) {
    histogramCopy[i] = histogram[i];
    if (histogram[i] > 0) {
      max = i;
    }
  }
  while (!bimodalTest(histogramCopy)) {
    histogramCopy = smoothed(histogramCopy);
    iterations++;
    if (iterations > 10000) {
      // if they occur more than 10000 iterations it returns -1
      return threshold;
    }
  }
  for (let i = 1; i < max; i++) {
    if (histogramCopy[i - 1] > histogramCopy[i] && histogramCopy[i + 1] >= histogramCopy[i]) {
      threshold = i;
      break;
    }
  }
  return threshold;
}
function smoothed(histogram) {
  // Smooth with a 3 point running mean filter
  const auHistogram = new Array(histogram.length); // a copy of the histogram for the smoothing process
  for (let i = 1; i < histogram.length - 1; i++) {
    auHistogram[i] = (histogram[i - 1] + histogram[i] + histogram[i + 1]) / 3;
  }
  auHistogram[0] = (histogram[0] + histogram[1]) / 3;
  auHistogram[histogram.length - 1] = (histogram.at(-2) + histogram.at(-1)) / 3;
  return auHistogram;
}
function bimodalTest(histogram) {
  // It is responsible for determining if a histogram is bimodal
  const len = histogram.length;
  let isBimodal = false;
  let peaks = 0;
  for (let k = 1; k < len - 1; k++) {
    if (histogram[k - 1] < histogram[k] && histogram[k + 1] < histogram[k]) {
      peaks++;
      if (peaks > 2) {
        return false;
      }
    }
  }
  if (peaks === 2) {
    isBimodal = true;
  }
  return isBimodal;
}

// see https://github.com/fiji/Auto_Threshold/blob/master/src/main/java/fiji/threshold/Auto_Threshold.java
// W. Tsai, "Moment-preserving thresholding: a new approach," Computer Vision,
// Graphics, and Image Processing, vol. 29, pp. 377-393, 1985.
// Ported to ImageJ plugin by G.Landini from the the open source project FOURIER 0.8
// by M. Emre Celebi , Department of Computer Science, Louisiana State University in Shreveport
// Shreveport, LA 71115, USA
// http://sourceforge.net/projects/fourier-ipal
// http://www.lsus.edu/faculty/~ecelebi/fourier.htm
/**
 * Return a threshold for a histogram.
 * @param histogram - Image histogram.
 * @param total - Number of pixels in the image.
 * @returns The threshold.
 */
function moments(histogram, total) {
  // moments
  const m0 = 1;
  let m1 = 0;
  let m2 = 0;
  let m3 = 0;
  let sum = 0;
  let threshold = -1;
  const histogramLength = histogram.length;
  const normalizedHistogram = [];
  for (let i = 0; i < histogramLength; i++) {
    normalizedHistogram.push(histogram[i] / total);
  }
  /* Calculate the first, second, and third order moments */
  for (let i = 0; i < histogramLength; i++) {
    m1 += i * normalizedHistogram[i];
    m2 += i * i * normalizedHistogram[i];
    m3 += i * i * i * normalizedHistogram[i];
  }
  /*
     First 4 moments of the gray-level image should match the first 4 moments
     of the target binary image. This leads to 4 equalities whose solutions
     are given in the Appendix of Ref. 1
     */
  const cd = m0 * m2 - m1 * m1; // determinant of the matriz of hankel for moments 2x2
  const c0 = (-m2 * m2 + m1 * m3) / cd;
  const c1 = (m0 * -m3 + m2 * m1) / cd;
  // new two gray values where z0<z1
  const z0 = 0.5 * (-c1 - Math.sqrt(c1 * c1 - 4 * c0));
  const z1 = 0.5 * (-c1 + Math.sqrt(c1 * c1 - 4 * c0));
  const p0 = (z1 - m1) / (z1 - z0); /* Fraction of the object pixels in the target binary image (p0z0+p1z1=m1) */
  // The threshold is the gray-level closest to the p0-tile of the normalized histogram
  for (let i = 0; i < histogramLength; i++) {
    sum += normalizedHistogram[i];
    if (sum > p0) {
      threshold = i;
      break;
    }
  }
  return threshold;
}

/*
 * The method is present in: Otsu, N (1979), "A threshold selection method from gray-level histograms", IEEE Trans. Sys., Man., Cyber. 9: 62-66
 * The Otsu implementation is based on: https://en.wikipedia.org/wiki/Otsu's_method
 * @param histogram - the histogram of the image
 * @returns {number} - the threshold
 */
/**
 * Return a threshold for a histogram using Otsu algorithm.
 * @param histogramCounts - The image histogram.
 * @param total - Total number of pixels of the image.
 * @returns The threshold.
 */
function otsu(histogramCounts, total) {
  let sumB = 0;
  let wB = 0;
  let maximum = 0;
  let level = 0;
  let sum1 = 0;
  for (let i = 0; i < histogramCounts.length; i++) {
    sum1 += i * histogramCounts[i];
  }
  for (let ii = 0; ii < histogramCounts.length; ii++) {
    wB = wB + histogramCounts[ii];
    const wF = total - wB;
    if (wB === 0 || wF === 0) {
      continue;
    }
    sumB = sumB + ii * histogramCounts[ii];
    const mF = (sum1 - sumB) / wF;
    const between = wB * wF * (sumB / wB - mF) * (sumB / wB - mF);
    if (between >= maximum) {
      level = ii;
      maximum = between;
    }
  }
  return level;
}

// See http://imagej.nih.gov/ij/download/tools/source/ij/process/AutoThresholder.java
// W. Doyle, "Operation useful for similarity-invariant pattern recognition,"
// Journal of the Association for Computing Machinery, vol. 9,pp. 259-267, 1962.
// ported to ImageJ plugin by G.Landini from Antti Niemisto's Matlab code (GPL)
// Original Matlab code Copyright (C) 2004 Antti Niemisto
// See http://www.cs.tut.fi/~ant/histthresh/ for an excellent slide presentation
// and the original Matlab code.
/**
 * Return a threshold for a histogram using percentiles.
 * @param histogram - Image histogram.
 * @returns The threshold.
 */
function percentile(histogram) {
  let threshold = -1;
  const percentile = 0.5; // default fraction of foreground pixels
  const avec = new Array(histogram.length);
  const total = partialSum(histogram, histogram.length - 1);
  let temp = 1;
  for (let i = 0; i < histogram.length; i++) {
    avec[i] = Math.abs(partialSum(histogram, i) / total - percentile);
    if (avec[i] < temp) {
      temp = avec[i];
      threshold = i;
    }
  }
  return threshold;
}
function partialSum(histogram, endIndex) {
  let x = 0;
  for (let i = 0; i <= endIndex; i++) {
    x += histogram[i];
  }
  return x;
}

// see https://github.com/fiji/Auto_Threshold/blob/master/src/main/java/fiji/threshold/Auto_Threshold.java
// Kapur J.N., Sahoo P.K., and Wong A.K.C. (1985) "A New Method for
// Gray-Level Picture Thresholding Using the Entropy of the Histogram"
// Graphical Models and Image Processing, 29(3): 273-285
// M. Emre Celebi
// 06.15.2007
// Ported to ImageJ plugin by G.Landini from E Celebi's fourier_0.8 routines
/**
 * Return a threshold for a histogram using its entropy.
 * @param histogram - The image histogram.
 * @param total - Total number of pixels of the image.
 * @returns The threshold.
 */
function renyiEntropy(histogram, total) {
  let firstBin; // First non-zero bin
  let lastBin; // last non-zero bin
  const normHisto = new Array(histogram.length); // normalized histogram
  const P1 = new Array(histogram.length); // accumulative normalized histogram
  const P2 = new Array(histogram.length); // accumulative normalized histogram
  // Entropy Variables
  let threshold1 = 0;
  let threshold2 = 0;
  let threshold3 = 0;
  let maxEnt1 = 0;
  let maxEnt2 = 0;
  let maxEnt3 = 0;
  const alpha2 = 0.5;
  const term2 = 1 / (1 - alpha2);
  const alpha3 = 2;
  const term3 = 1 / (1 - alpha3);
  for (let ih = 0; ih < histogram.length; ih++) {
    normHisto[ih] = histogram[ih] / total;
  }
  P1[0] = normHisto[0];
  P2[0] = 1 - P1[0];
  for (let ih = 1; ih < histogram.length; ih++) {
    P1[ih] = P1[ih - 1] + normHisto[ih];
    P2[ih] = 1 - P1[ih];
  }
  /* Determine the first non-zero bin */
  firstBin = 0;
  for (let ih = 0; ih < histogram.length; ih++) {
    if (Math.abs(P1[ih]) >= Number.EPSILON) {
      firstBin = ih;
      break;
    }
  }
  /* Determine the last non-zero bin */
  lastBin = histogram.length - 1;
  for (let ih = histogram.length - 1; ih >= firstBin; ih--) {
    if (Math.abs(P2[ih]) >= Number.EPSILON) {
      lastBin = ih;
      break;
    }
  }
  /* Maximum Entropy Thresholding - BEGIN */
  /* ALPHA = 1.0 */
  /* Calculate the total entropy each gray-level
     and find the threshold that maximizes it
     */
  for (let it = firstBin; it <= lastBin; it++) {
    /* Entropy of the background pixels */
    let entBack1 = 0;
    let entBack2 = 0;
    let entBack3 = 0;
    for (let ih = 0; ih <= it; ih++) {
      if (histogram[ih] !== 0) {
        entBack1 -= normHisto[ih] / P1[it] * Math.log(normHisto[ih] / P1[it]);
      }
      entBack2 += Math.sqrt(normHisto[ih] / P1[it]);
      entBack3 += normHisto[ih] * normHisto[ih] / (P1[it] * P1[it]);
    }
    /* Entropy of the object pixels */
    let entObj1 = 0;
    let entObj2 = 0;
    let entObj3 = 0;
    for (let ih = it + 1; ih < histogram.length; ih++) {
      if (histogram[ih] !== 0) {
        entObj1 -= normHisto[ih] / P2[it] * Math.log(normHisto[ih] / P2[it]);
      }
      entObj2 += Math.sqrt(normHisto[ih] / P2[it]);
      entObj3 += normHisto[ih] * normHisto[ih] / (P2[it] * P2[it]);
    }
    /* Total entropy */
    const totEnt1 = entBack1 + entObj1;
    const totEnt2 = term2 * (entBack2 * entObj2 > 0 ? Math.log(entBack2 * entObj2) : 0);
    const totEnt3 = term3 * (entBack3 * entObj3 > 0 ? Math.log(entBack3 * entObj3) : 0);
    if (totEnt1 > maxEnt1) {
      maxEnt1 = totEnt1;
      threshold1 = it;
    }
    if (totEnt2 > maxEnt2) {
      maxEnt2 = totEnt2;
      threshold2 = it;
    }
    if (totEnt3 > maxEnt3) {
      maxEnt3 = totEnt3;
      threshold3 = it;
    }
  }
  /* End Maximum Entropy Thresholding */
  const tStars = new Uint32Array([threshold1, threshold2, threshold3]);
  tStars.sort();
  let betas;
  /* Adjust beta values */
  if (Math.abs(tStars[0] - tStars[1]) <= 5) {
    if (Math.abs(tStars[1] - tStars[2]) <= 5) {
      betas = [1, 2, 1];
    } else {
      betas = [0, 1, 3];
    }
  } else if (Math.abs(tStars[1] - tStars[2]) <= 5) {
    betas = [3, 1, 0];
  } else {
    betas = [1, 2, 1];
  }
  /* Determine the optimal threshold value */
  const omega = P1[tStars[2]] - P1[tStars[0]];
  const optThreshold = Math.round(tStars[0] * (P1[tStars[0]] + 0.25 * omega * betas[0]) + 0.25 * tStars[1] * omega * betas[1] + tStars[2] * (P2[tStars[2]] + 0.25 * omega * betas[2]));
  return optThreshold;
}

// see https://github.com/fiji/Auto_Threshold/blob/master/src/main/java/fiji/threshold/Auto_Threshold.java
// Shanhbag A.G. (1994) "Utilization of Information Measure as a Means of
// Image Thresholding" Graphical Models and Image Processing, 56(5): 414-419
// Ported to ImageJ plugin by G.Landini from E Celebi's fourier_0.8 routines
/**
 * Return a threshold for a histogram using Shanbhag algorithm.
 * @param histogram - The image histogram.
 * @param total - Total number of pixels of the image.
 * @returns The threshold.
 */
function shanbhag(histogram, total) {
  const normHisto = new Array(histogram.length); // normalized histogram
  for (let ih = 0; ih < histogram.length; ih++) {
    normHisto[ih] = histogram[ih] / total;
  }
  const P1 = new Array(histogram.length); // cumulative normalized histogram
  const P2 = new Array(histogram.length);
  P1[0] = normHisto[0];
  P2[0] = 1 - P1[0];
  for (let ih = 1; ih < histogram.length; ih++) {
    P1[ih] = P1[ih - 1] + normHisto[ih];
    P2[ih] = 1 - P1[ih];
  }
  /* Determine the first non-zero bin */
  let firstBin = 0;
  for (let ih = 0; ih < histogram.length; ih++) {
    if (Math.abs(P1[ih]) >= Number.EPSILON) {
      firstBin = ih;
      break;
    }
  }
  /* Determine the last non-zero bin */
  let lastBin = histogram.length - 1;
  for (let ih = histogram.length - 1; ih >= firstBin; ih--) {
    if (Math.abs(P2[ih]) >= Number.EPSILON) {
      lastBin = ih;
      break;
    }
  }
  // Calculate the total entropy each gray-level
  // and find the threshold that maximizes it
  let threshold = -1;
  let minEnt = Number.MAX_VALUE; // min entropy
  let term;
  let totEnt; // total entropy
  let entBack; // entropy of the background pixels at a given threshold
  let entObj; // entropy of the object pixels at a given threshold
  for (let it = firstBin; it <= lastBin; it++) {
    /* Entropy of the background pixels */
    entBack = 0;
    term = 0.5 / P1[it];
    for (let ih = 1; ih <= it; ih++) {
      entBack -= normHisto[ih] * Math.log(1 - term * P1[ih - 1]);
    }
    entBack *= term;
    /* Entropy of the object pixels */
    entObj = 0;
    term = 0.5 / P2[it];
    for (let ih = it + 1; ih < histogram.length; ih++) {
      entObj -= normHisto[ih] * Math.log(1 - term * P2[ih]);
    }
    entObj *= term;
    /* Total entropy */
    totEnt = Math.abs(entBack - entObj);
    if (totEnt < minEnt) {
      minEnt = totEnt;
      threshold = it;
    }
  }
  return threshold;
}

// see https://github.com/fiji/Auto_Threshold/blob/master/src/main/java/fiji/threshold/Auto_Threshold.java
// Zack, G. W., Rogers, W. E. and Latt, S. A., 1977,
// Automatic Measurement of Sister Chromatid Exchange Frequency,
// Journal of Histochemistry and Cytochemistry 25 (7), pp. 741-753
//
//  modified from Johannes Schindelin plugin
/**
 * Return a threshold for a histogram using Triangle algorithm.
 * @param histogram - The image histogram.
 * @returns The threshold.
 */
function triangle(histogram) {
  // find min and max
  let min = 0;
  let dmax = 0;
  let max = 0;
  let min2 = 0;
  for (let i = 0; i < histogram.length; i++) {
    if (histogram[i] > 0) {
      min = i;
      break;
    }
  }
  if (min > 0) {
    // line to the (p==0) point, not to histogram[min]
    min--;
  }
  // The Triangle algorithm cannot tell whether the data is skewed to one side or another.
  // This causes a problem as there are 2 possible thresholds between the max and the 2 extremes
  // of the histogram.
  // Here I propose to find out to which side of the max point the data is furthest, and use that as
  //  the other extreme.
  for (let i = histogram.length - 1; i > 0; i--) {
    if (histogram[i] > 0) {
      min2 = i;
      break;
    }
  }
  if (min2 < histogram.length - 1) {
    // line to the (p==0) point, not to data[min]
    min2++;
  }
  for (let i = 0; i < histogram.length; i++) {
    if (histogram[i] > dmax) {
      max = i;
      dmax = histogram[i];
    }
  }
  // find which is the furthest side
  let inverted = false;
  if (max - min < min2 - max) {
    // reverse the histogram
    inverted = true;
    let left = 0; // index of leftmost element
    let right = histogram.length - 1; // index of rightmost element
    while (left < right) {
      // exchange the left and right elements
      const temp = histogram[left];
      histogram[left] = histogram[right];
      histogram[right] = temp;
      // move the bounds toward the center
      left++;
      right--;
    }
    min = histogram.length - 1 - min2;
    max = histogram.length - 1 - max;
  }
  if (min === max) {
    return min;
  }
  // describe line by nx * x + ny * y - d = 0
  let nx, ny, d;
  // nx is just the max frequency as the other point has freq=0
  nx = histogram[max]; // -min; // data[min]; //  lowest value bmin = (p=0)% in the image
  ny = min - max;
  d = Math.hypot(nx, ny);
  nx /= d;
  ny /= d;
  d = nx * min + ny * histogram[min];
  // find split point
  let split = min;
  let splitDistance = 0;
  for (let i = min + 1; i <= max; i++) {
    const newDistance = nx * i + ny * histogram[i] - d;
    if (newDistance > splitDistance) {
      split = i;
      splitDistance = newDistance;
    }
  }
  split--;
  if (inverted) {
    // The histogram might be used for something else, so let's reverse it back
    let left = 0;
    let right = histogram.length - 1;
    while (left < right) {
      const temp = histogram[left];
      histogram[left] = histogram[right];
      histogram[right] = temp;
      left++;
      right--;
    }
    return histogram.length - 1 - split;
  } else {
    return split;
  }
}

// see https://github.com/fiji/Auto_Threshold/blob/master/src/main/java/fiji/threshold/Auto_Threshold.java
// Implements Yen  thresholding method
// 1) Yen J.C., Chang F.J., and Chang S. (1995) "A New Criterion
//    for Automatic Multilevel Thresholding" IEEE Trans. on Image
//    Processing, 4(3): 370-378
// 2) Sezgin M. and Sankur B. (2004) "Survey over Image Thresholding
//    Techniques and Quantitative Performance Evaluation" Journal of
//    Electronic Imaging, 13(1): 146-165
//    http://citeseer.ist.psu.edu/sezgin04survey.html
//
// M. Emre Celebi
// 06.15.2007
// Ported to ImageJ plugin by G.Landini from E Celebi's fourier_0.8 routines
/**
 * Return a threshold for a histogram using Yen algorithm.
 * @param histogram - The image histogram.
 * @param total - Total number of pixels of the image.
 * @returns The threshold.
 */
function yen(histogram, total) {
  const normHisto = new Array(histogram.length); // normalized histogram
  for (let ih = 0; ih < histogram.length; ih++) {
    normHisto[ih] = histogram[ih] / total;
  }
  const P1 = new Array(histogram.length); // cumulative normalized histogram
  P1[0] = normHisto[0];
  for (let ih = 1; ih < histogram.length; ih++) {
    P1[ih] = P1[ih - 1] + normHisto[ih];
  }
  const P1Sq = new Array(histogram.length);
  P1Sq[0] = normHisto[0] * normHisto[0];
  for (let ih = 1; ih < histogram.length; ih++) {
    P1Sq[ih] = P1Sq[ih - 1] + normHisto[ih] * normHisto[ih];
  }
  const P2Sq = new Array(histogram.length);
  P2Sq[histogram.length - 1] = 0;
  for (let ih = histogram.length - 2; ih >= 0; ih--) {
    P2Sq[ih] = P2Sq[ih + 1] + normHisto[ih + 1] * normHisto[ih + 1];
  }
  /* Find the threshold that maximizes the criterion */
  let threshold = -1;
  let maxCrit = Number.MIN_VALUE;
  let crit;
  for (let it = 0; it < histogram.length; it++) {
    crit = -1 * (P1Sq[it] * P2Sq[it] > 0 ? Math.log(P1Sq[it] * P2Sq[it]) : 0) + 2 * (P1[it] * (1 - P1[it]) > 0 ? Math.log(P1[it] * (1 - P1[it])) : 0);
    if (crit > maxCrit) {
      maxCrit = crit;
      threshold = it;
    }
  }
  return threshold;
}

const ThresholdAlgorithm = {
  HUANG: 'huang',
  INTERMODES: 'intermodes',
  ISODATA: 'isodata',
  LI: 'li',
  MAX_ENTROPY: 'maxEntropy',
  MEAN: 'mean',
  MIN_ERROR: 'minError',
  MINIMUM: 'minimum',
  MOMENTS: 'moments',
  OTSU: 'otsu',
  PERCENTILE: 'percentile',
  RENYI_ENTROPY: 'renyiEntropy',
  SHANBHAG: 'shanbhag',
  TRIANGLE: 'triangle',
  YEN: 'yen'
};
/**
 * Compute threshold value for an image using the specified algorithm.
 * @param image - The grey image.
 * @param options - Threshold options.
 * @returns The threshold value for the image.
 */
function computeThreshold(image, options = {}) {
  const {
    algorithm = 'otsu',
    slots
  } = options;
  if (image.channels !== 1) {
    throw new TypeError('threshold can only be computed on images with one channel');
  }
  const histogram = image.histogram({
    slots
  });
  const scale = slots ? 2 ** image.bitDepth / slots : 1;
  return M$2(algorithm).with('huang', () => huang(histogram) * scale).with('intermodes', () => intermodes(histogram) * scale).with('isodata', () => isodata(histogram) * scale).with('li', () => li(histogram, image.size) * scale).with('maxEntropy', () => maxEntropy(histogram, image.size) * scale).with('mean', () => mean$1(histogram, image.size) * scale).with('minimum', () => minimum(histogram) * scale).with('minError', () => minError(histogram, image.size) * scale).with('moments', () => moments(histogram, image.size) * scale).with('otsu', () => otsu(histogram, image.size) * scale).with('percentile', () => percentile(histogram) * scale).with('renyiEntropy', () => renyiEntropy(histogram, image.size) * scale).with('shanbhag', () => shanbhag(histogram, image.size) * scale).with('triangle', () => triangle(histogram) * scale).with('yen', () => yen(histogram, image.size) * scale).exhaustive();
}
// See: https://docs.opencv.org/4.0.1/d7/d1b/group__imgproc__misc.html#gaa9e58d2860d4afa658ef70a9b1115576
/**
 * Create a black and white image based on a threshold value.
 * @param image - The grey image to convert.
 * @param options - Threshold options.
 * @returns The resulting mask.
 */
function threshold(image, options = {}) {
  let thresholdValue;
  if ('threshold' in options) {
    const threshold = options.threshold;
    if (threshold < 0 || threshold > 1) {
      throw new RangeError('threshold must be a value between 0 and 1');
    }
    thresholdValue = threshold * image.maxValue;
  } else {
    thresholdValue = computeThreshold(image, options);
  }
  const result = imageToOutputMask(image, options);
  for (let i = 0; i < image.size; i++) {
    result.setBitByIndex(i, image.getValueByIndex(i, 0) > thresholdValue ? 1 : 0);
  }
  return result;
}

/**
 * Converts R, G and B values to a single value using Luma 709 standard({@link https://en.wikipedia.org/wiki/Luma_(video)}).
 * @param red - Red value of current pixel.
 * @param green - Green value of current pixel.
 * @param blue - Blue value of current pixel.
 * @returns - Corresponding gray value.
 */
function luma709(red, green, blue) {
  // sRGB
  // return red * 0.2126 + green * 0.7152 + blue * 0.0722;
  // Let's do a little trick ... in order not convert the integer to a double we do
  // the multiplication with integer to reach a total of 32768 and then shift the bits
  // of 15 to the right
  // This does a Math.floor and may lead to small (max 1) difference
  // Same result, > 10% faster on the full grey conversion
  return red * 6966 + green * 23436 + blue * 2366 >> 15;
}
/**
 *  Converts R, G and B values to a single value using Luma 601 standard({@link https://en.wikipedia.org/wiki/Luma_(video)}).
 * @param red - Red value of current pixel.
 * @param green - Green value of current pixel.
 * @param blue - Blue value of current pixel.
 * @returns - Corresponding gray value.
 */
function luma601(red, green, blue) {
  // NTSC
  // return this.red * 0.299 + green * 0.587 + blue * 0.114;
  return red * 9798 + green * 19235 + blue * 3735 >> 15;
}
/**
 * Return the maximal value between red, green and blue.
 * @param red - Red value of current pixel.
 * @param green - Green value of current pixel.
 * @param blue - Blue value of current pixel.
 * @returns - Corresponding gray value.
 */
function max$1(red, green, blue) {
  return Math.max(red, green, blue);
}
/**
 * Return the minimal value between red, green and blue.
 * @param red - Red value of current pixel.
 * @param green - Green value of current pixel.
 * @param blue - Blue value of current pixel.
 * @returns - Corresponding gray value.
 */
function min(red, green, blue) {
  return Math.min(red, green, blue);
}
/**
 * Return the average of red, green and blue.
 * @param red - Red value of current pixel.
 * @param green - Green value of current pixel.
 * @param blue - Blue value of current pixel.
 * @returns - Corresponding gray value.
 */
function average(red, green, blue) {
  return (red + green + blue) / 3 >> 0;
}
/**
 * Return the average between the max and min values of red, green and blue.
 * @param red - Red value of current pixel.
 * @param green - Green value of current pixel.
 * @param blue - Blue value of current pixel.
 * @returns - Corresponding gray value.
 */
function minmax(red, green, blue) {
  return (Math.max(red, green, blue) + Math.min(red, green, blue)) / 2;
}
/**
 * Return the red value.
 * @param red - Red value of current pixel.
 * @returns - Corresponding gray value.
 */
function red(red) {
  return red;
}
/**
 * Return the green value.
 * @param red - Red value of current pixel.
 * @param green - Green value of current pixel.
 * @returns - Corresponding gray value.
 */
function green(red, green) {
  return green;
}
/**
 * Return the blue value.
 * @param red - Red value of current pixel.
 * @param green - Green value of current pixel.
 * @param blue - Blue value of current pixel.
 * @returns - Corresponding gray value.
 */
function blue(red, green, blue) {
  return blue;
}
/**
 * Return the minimum of the inverses of red, green and blue.
 * @param red - Red value of current pixel.
 * @param green - Green value of current pixel.
 * @param blue - Blue value of current pixel.
 * @param image - Image to convert to grey.
 * @returns - Corresponding gray value.
 */
function black(red, green, blue, image) {
  return Math.min(image.maxValue - red, image.maxValue - green, image.maxValue - blue);
}
/**
 * Returns the cyan component of a pixel.
 * @param red - Red value of current pixel.
 * @param green - Green value of current pixel.
 * @param blue - Blue value of current pixel.
 * @param image - Image to convert to grey.
 * @returns - Corresponding gray value.
 */
function cyan(red, green, blue, image) {
  const blackColor = black(red, green, blue, image);
  return (image.maxValue - red - blackColor) / (1 - blackColor / image.maxValue) >> 0;
}
/**
 * Returns the magenta component of a pixel.
 * @param red - Red value of current pixel.
 * @param green - Green value of current pixel.
 * @param blue - Blue value of current pixel.
 * @param image - Image to convert to grey.
 * @returns - Corresponding gray value.
 */
function magenta(red, green, blue, image) {
  const blackColor = black(red, green, blue, image);
  return (image.maxValue - green - blackColor) / (1 - blackColor / image.maxValue) >> 0;
}
/**
 * Returns the yellow component of a pixel.
 * @param red - Red value of current pixel.
 * @param green - Green value of current pixel.
 * @param blue - Blue value of current pixel.
 * @param image - Image to convert to grey.
 * @returns - Corresponding gray value.
 */
function yellow(red, green, blue, image) {
  const blackColor = black(red, green, blue, image);
  return (image.maxValue - blue - blackColor) / (1 - blackColor / image.maxValue) >> 0;
}
/**
 * Returns the hue of a pixel as a value between 0 and 255.
 * @param red - Red value of current pixel.
 * @param green - Green value of current pixel.
 * @param blue - Blue value of current pixel.
 * @param image - Source image for the RGB values.
 * @returns - Hue of the pixel.
 */
function hue(red, green, blue, image) {
  const minValue = min(red, green, blue);
  const maxValue = max$1(red, green, blue);
  if (maxValue === minValue) {
    return 0;
  }
  let hue = 0;
  const delta = maxValue - minValue;
  if (maxValue === red) {
    hue = (green - blue) / delta + (green < blue ? 6 : 0);
  } else if (maxValue === green) {
    hue = (blue - red) / delta + 2;
  } else {
    assert(maxValue === blue);
    hue = (red - green) / delta + 4;
  }
  return hue / 6 * image.maxValue >> 0;
}
/**
 * Returns the saturation component of a pixel.
 * @param red - Red value of current pixel.
 * @param green - Green value of current pixel.
 * @param blue - Blue value of current pixel.
 * @param image - Source image for the RGB values.
 * @returns - Saturation of the pixel.
 */
function saturation(red, green, blue, image) {
  // from HSV model
  const minValue = min(red, green, blue);
  const maxValue = max$1(red, green, blue);
  const delta = maxValue - minValue;
  return maxValue === 0 ? 0 : delta / maxValue * image.maxValue;
}
/**
 * Returns the lightness of a pixel.
 * @param red - Red value of current pixel.
 * @param green - Green value of current pixel.
 * @param blue - Blue value of current pixel.
 * @returns - Lightness of the pixel.
 */
function lightness(red, green, blue) {
  const minValue = min(red, green, blue);
  const maxValue = max$1(red, green, blue);
  return (maxValue + minValue) / 2;
}

var greyAlgorithms = /*#__PURE__*/Object.freeze({
	__proto__: null,
	average: average,
	black: black,
	blue: blue,
	cyan: cyan,
	green: green,
	hue: hue,
	lightness: lightness,
	luma601: luma601,
	luma709: luma709,
	magenta: magenta,
	max: max$1,
	min: min,
	minmax: minmax,
	red: red,
	saturation: saturation,
	yellow: yellow
});

const GreyAlgorithm = {
  LUMA_709: 'luma709',
  LUMA_601: 'luma601',
  MAX: 'max',
  MIN: 'min',
  AVERAGE: 'average',
  MINMAX: 'minmax',
  RED: 'red',
  GREEN: 'green',
  BLUE: 'blue',
  BLACK: 'black',
  CYAN: 'cyan',
  MAGENTA: 'magenta',
  YELLOW: 'yellow',
  HUE: 'hue',
  SATURATION: 'saturation',
  LIGHTNESS: 'lightness'
};
{
  // Check that all the algorithms are in the enum.
  const algos = new Set(Object.values(GreyAlgorithm));
  for (const algo of Object.keys(greyAlgorithms)) {
    assert(algos.has(algo), `Grey algorithm ${algo} is missing in the GreyAlgorithm enum`);
  }
}
/**
 * Convert the current image to grayscale.
 * The source image has to be RGB or RGBA.
 * If there is an alpha channel you have to specify what to do:
 * - keepAlpha :  keep the alpha channel, you will get a GREYA image.
 * - mergeAlpha : multiply each pixel of the image by the alpha, you will get a GREY image.
 * @param image - Original color image to convert to grey.
 * @param options - The grey conversion options.
 * @returns The resulting grey image.
 */
function grey(image, options = {}) {
  let {
    keepAlpha = false,
    mergeAlpha = true
  } = options;
  const {
    algorithm = 'luma709'
  } = options;
  checkProcessable$1(image, {
    colorModel: ['RGB', 'RGBA']
  });
  keepAlpha = keepAlpha && image.alpha;
  mergeAlpha = mergeAlpha && image.alpha;
  if (keepAlpha) {
    mergeAlpha = false;
  }
  const newColorModel = keepAlpha ? 'GREYA' : 'GREY';
  const newImage = getOutputImage(image, options, {
    newParameters: {
      colorModel: newColorModel
    }
  });
  let method;
  if (typeof algorithm === 'function') {
    method = algorithm;
  } else {
    method = greyAlgorithms[algorithm];
  }
  const clamp = getClamp(newImage);
  for (let i = 0; i < image.size; i++) {
    const red = image.getValueByIndex(i, 0);
    const green = image.getValueByIndex(i, 1);
    const blue = image.getValueByIndex(i, 2);
    let newValue;
    if (mergeAlpha) {
      const alpha = image.getValueByIndex(i, 3);
      newValue = clamp(method(red, green, blue, image) * alpha / image.maxValue);
    } else {
      newValue = clamp(method(red, green, blue, image));
      if (keepAlpha) {
        const alpha = image.getValueByIndex(i, 3);
        newImage.setValueByIndex(i, 1, alpha);
      }
    }
    newImage.setValueByIndex(i, 0, newValue);
  }
  return newImage;
}

/**
 * Copy the image to another one by specifying the location in the target image.
 * If the source image exceeds the boundaries of the target image, the excess pixels
 * are ignored. The result image will have the same dimensions as the target image.
 * @param source - The source image.
 * @param target - The target image.
 * @param options - Options.
 * @returns The target with the source copied to it.
 */
function copyTo(source, target, options = {}) {
  const {
    origin = {
      column: 0,
      row: 0
    }
  } = options;
  const {
    column,
    row
  } = origin;
  if (source.colorModel !== target.colorModel) {
    throw new RangeError('source and target must have the same color model');
  }
  checkPointIsInteger(origin, 'Origin');
  let result;
  if (target instanceof Image) {
    result = getOutputImage(target, options, {
      clone: true
    });
  } else {
    result = maskToOutputMask(target, options, {
      clone: true
    });
  }
  for (let currentRow = Math.max(row, 0); currentRow < Math.min(source.height + row, target.height); currentRow++) {
    for (let currentColumn = Math.max(column, 0); currentColumn < Math.min(source.width + column, target.width); currentColumn++) {
      const sourcePixel = source.getPixel(currentColumn - column, currentRow - row);
      setBlendedPixel(result, currentColumn, currentRow, sourcePixel);
    }
  }
  return result;
}

/**
 * Crop the input image to a desired size.
 * @param image - Image to crop.
 * @param [options] - Crop options.
 * @returns The new cropped image.
 * @example
 * var cropped = image.crop({
 *   row:20,
 *   column:100
 * });
 */
function crop(image, options = {}) {
  const {
    origin = {
      row: 0,
      column: 0
    },
    width = image.width - origin.column,
    height = image.height - origin.row
  } = options;
  const {
    column,
    row
  } = origin;
  checkProcessable$1(image, {
    bitDepth: [8, 16]
  });
  checkPointIsInteger(origin, 'Origin');
  if (!Number.isInteger(width) || !Number.isInteger(height)) {
    throw new RangeError(`Width and height (width:${width}; height:${height}) must be integers`);
  }
  if (row > image.height - 1 || column > image.width - 1) {
    throw new RangeError(`Origin (row:${row}, column:${column}) out of range (${image.width - 1}; ${image.height - 1})`);
  }
  if (width <= 0 || height <= 0) {
    throw new RangeError(`Width and height (width:${width}; height:${height}) must be positive numbers`);
  }
  if (row < 0 || column < 0) {
    throw new RangeError(`Row and column (row:${row}, column:${column}) must be positive numbers`);
  }
  if (width > image.width - column || height > image.height - row) {
    throw new RangeError(`Size is out of range (row:${row}, column:${column}, width:${width}, height:${height})`);
  }
  const newImage = Image.createFrom(image, {
    width,
    height
  });
  for (let currentRow = 0; currentRow < height; currentRow++) {
    for (let currentColumn = 0; currentColumn < width; currentColumn++) {
      newImage.setPixel(currentColumn, currentRow, image.getPixel(column + currentColumn, row + currentRow));
    }
  }
  return newImage;
}

/**
 * Crops the image based on the alpha channel
 * This removes lines and columns where the alpha channel is lower than a threshold value.
 * @param image - Image to process.
 * @param options - Crop alpha options.
 * @returns The cropped image.
 */
function cropAlpha(image, options = {}) {
  checkProcessable$1(image, {
    alpha: true
  });
  const {
    threshold = image.maxValue
  } = options;
  const left = findLeft(image, threshold, image.components);
  if (left === -1) {
    throw new RangeError(`could not find new dimensions. Threshold may be too high: ${threshold}`);
  }
  const top = findTop(image, threshold, image.components, left);
  const bottom = findBottom(image, threshold, image.components, left);
  const right = findRight(image, threshold, image.components, left, top, bottom);
  return image.crop({
    origin: {
      column: left,
      row: top
    },
    width: right - left + 1,
    height: bottom - top + 1
  });
}
function findLeft(image, threshold, channel) {
  for (let row = 0; row < image.width; row++) {
    for (let column = 0; column < image.height; column++) {
      if (image.getValue(row, column, channel) >= threshold) {
        return row;
      }
    }
  }
  return -1;
}
function findTop(image, threshold, channel, left) {
  for (let row = 0; row < image.height; row++) {
    for (let column = left; column < image.width; column++) {
      if (image.getValue(column, row, channel) >= threshold) {
        return row;
      }
    }
  }
  /* istanbul ignore next */
  return -1;
}
function findBottom(image, threshold, channel, left) {
  for (let row = image.height - 1; row >= 0; row--) {
    for (let column = left; column < image.width; column++) {
      if (image.getValue(column, row, channel) >= threshold) {
        return row;
      }
    }
  }
  /* istanbul ignore next */
  return -1;
}
function findRight(image, threshold, channel, left, top, bottom) {
  for (let row = image.width - 1; row >= left; row--) {
    for (let column = top; column <= bottom; column++) {
      if (image.getValue(row, column, channel) >= threshold) {
        return row;
      }
    }
  }
  /* istanbul ignore next */
  return -1;
}

const InterpolationType = {
  NEAREST: 'nearest',
  BILINEAR: 'bilinear',
  BICUBIC: 'bicubic'
};
/**
 * Get the interpolation function based on its name.
 * @param interpolationType - Specified interpolation type.
 * @returns The interpolation function.
 */
function getInterpolationFunction(interpolationType) {
  return M$2(interpolationType).with('nearest', () => interpolateNearest).with('bilinear', () => interpolateBilinear).with('bicubic', () => interpolateBicubic).exhaustive();
}
/**
 * Interpolate using nearest neighbor.
 * @param image - The image to interpolate.
 * @param column - Column index.
 * @param row - Row index.
 * @param channel - Channel index.
 * @param interpolateBorder - Border interpolation function.
 * @returns The interpolated value.
 */
function interpolateNearest(image, column, row, channel, interpolateBorder) {
  column = Math.round(column);
  row = Math.round(row);
  return interpolateBorder(column, row, channel, image);
}
/**
 * Interpolate using bilinear interpolation.
 * @param image - The image to interpolate.
 * @param column - Column index.
 * @param row - Row index.
 * @param channel - Channel index.
 * @param interpolateBorder - Border interpolation function.
 * @returns The interpolated value.
 */
function interpolateBilinear(image, column, row, channel, interpolateBorder) {
  const px0 = Math.floor(column);
  const py0 = Math.floor(row);
  const px1 = px0 + 1;
  const py1 = py0 + 1;
  if (px1 < image.width && py1 < image.height && px0 >= 0 && py0 >= 0) {
    const vx0y0 = image.getValue(px0, py0, channel);
    const vx1y0 = image.getValue(px1, py0, channel);
    const vx0y1 = image.getValue(px0, py1, channel);
    const vx1y1 = image.getValue(px1, py1, channel);
    const r1 = (px1 - column) * vx0y0 + (column - px0) * vx1y0;
    const r2 = (px1 - column) * vx0y1 + (column - px0) * vx1y1;
    return round((py1 - row) * r1 + (row - py0) * r2);
  } else {
    const vx0y0 = interpolateBorder(px0, py0, channel, image);
    const vx1y0 = interpolateBorder(px1, py0, channel, image);
    const vx0y1 = interpolateBorder(px0, py1, channel, image);
    const vx1y1 = interpolateBorder(px1, py1, channel, image);
    const r1 = (px1 - column) * vx0y0 + (column - px0) * vx1y0;
    const r2 = (px1 - column) * vx0y1 + (column - px0) * vx1y1;
    return round((py1 - row) * r1 + (row - py0) * r2);
  }
}
/**
 * Interpolate using bicubic interpolation.
 * @param image - The image to interpolate.
 * @param column - Column index.
 * @param row - Row index.
 * @param channel - Channel index.
 * @param interpolateBorder - Border interpolation function.
 * @param clamp - Clamp function.
 * @returns The interpolated value.
 */
function interpolateBicubic(image, column, row, channel, interpolateBorder, clamp) {
  const px1 = Math.floor(column);
  const py1 = Math.floor(row);
  if (px1 === column && py1 === row) {
    return interpolateBorder(px1, py1, channel, image);
  }
  const xNorm = column - px1;
  const yNorm = row - py1;
  const vx0y0 = interpolateBorder(px1 - 1, py1 - 1, channel, image);
  const vx1y0 = interpolateBorder(px1, py1 - 1, channel, image);
  const vx2y0 = interpolateBorder(px1 + 1, py1 - 1, channel, image);
  const vx3y0 = interpolateBorder(px1 + 2, py1 - 1, channel, image);
  const v0 = cubic(vx0y0, vx1y0, vx2y0, vx3y0, xNorm);
  const vx0y1 = interpolateBorder(px1 - 1, py1, channel, image);
  const vx1y1 = interpolateBorder(px1, py1, channel, image);
  const vx2y1 = interpolateBorder(px1 + 1, py1, channel, image);
  const vx3y1 = interpolateBorder(px1 + 2, py1, channel, image);
  const v1 = cubic(vx0y1, vx1y1, vx2y1, vx3y1, xNorm);
  const vx0y2 = interpolateBorder(px1 - 1, py1 + 1, channel, image);
  const vx1y2 = interpolateBorder(px1, py1 + 1, channel, image);
  const vx2y2 = interpolateBorder(px1 + 1, py1 + 1, channel, image);
  const vx3y2 = interpolateBorder(px1 + 2, py1 + 1, channel, image);
  const v2 = cubic(vx0y2, vx1y2, vx2y2, vx3y2, xNorm);
  const vx0y3 = interpolateBorder(px1 - 1, py1 + 2, channel, image);
  const vx1y3 = interpolateBorder(px1, py1 + 2, channel, image);
  const vx2y3 = interpolateBorder(px1 + 1, py1 + 2, channel, image);
  const vx3y3 = interpolateBorder(px1 + 2, py1 + 2, channel, image);
  const v3 = cubic(vx0y3, vx1y3, vx2y3, vx3y3, xNorm);
  return round(clamp(cubic(v0, v1, v2, v3, yNorm)));
}
/**
 * Cubic function.
 * @param a - First value.
 * @param b - Second value.
 * @param c - Third value.
 * @param d - Fourth value.
 * @param x - X value.
 * @returns The interpolated value.
 */
function cubic(a, b, c, d, x) {
  return b + 0.5 * x * (c - a + x * (2 * a - 5 * b + 4 * c - d + x * (3 * (b - c) + d - a)));
}

/**
 * Transforms an image using a matrix.
 * @param image - Original image.
 * @param transformMatrix - 2×3 transform matrix.
 * @param options - Transform options.
 * @returns The new image.
 */
function transform(image, transformMatrix, options = {}) {
  const {
    borderValue = getDefaultColor(image),
    borderType = 'constant',
    interpolationType = 'bilinear',
    fullImage
  } = options;
  let {
    width = image.width,
    height = image.height
  } = options;
  if (Array.isArray(borderValue)) {
    validateColor(borderValue, image);
  }
  if (!isValidMatrix(transformMatrix)) {
    throw new TypeError(`transformation matrix must be 2x3 or 3x3. Received ${transformMatrix.length}x${transformMatrix[1].length}`);
  }
  if (transformMatrix.length === 2) {
    transformMatrix.push([0, 0, 1]);
  }
  if (fullImage) {
    transformMatrix = transformMatrix.map(row => row.slice());
    transformMatrix[0][2] = 0;
    transformMatrix[1][2] = 0;
    const corners = [image.getCoordinates('top-left'), image.getCoordinates('top-right'), image.getCoordinates('bottom-right'), image.getCoordinates('bottom-left')];
    corners[1].column += 1;
    corners[2].column += 1;
    corners[2].row += 1;
    corners[3].row += 1;
    const transformedCorners = corners.map(corner => {
      return [transformPoint(transformMatrix[0], transformMatrix[2], corner.column, corner.row), transformPoint(transformMatrix[1], transformMatrix[2], corner.column, corner.row)];
    });
    const xCoordinates = transformedCorners.map(c => c[0]);
    const yCoordinates = transformedCorners.map(c => c[1]);
    const maxX = Math.max(...xCoordinates);
    const maxY = Math.max(...yCoordinates);
    const minX = Math.min(...xCoordinates);
    const minY = Math.min(...yCoordinates);
    const center = [(image.width - 1) / 2, (image.height - 1) / 2];
    width = maxX - minX;
    height = maxY - minY;
    const centerX = transformPoint(transformMatrix[0], transformMatrix[2], center[0], center[1]);
    const centerY = transformPoint(transformMatrix[1], transformMatrix[2], center[0], center[1]);
    const a = (width - 1) / 2 - centerX;
    const b = (height - 1) / 2 - centerY;
    transformMatrix[0][2] = a;
    transformMatrix[1][2] = b;
    width = Math.round(width);
    height = Math.round(height);
  }
  if (!options.inverse) {
    transformMatrix = inverse(new Matrix$1(transformMatrix)).to2DArray();
  }
  const newImage = Image.createFrom(image, {
    width,
    height
  });
  const interpolateBorder = getBorderInterpolation(borderType, borderValue);
  const clamp = getClamp(newImage);
  const interpolate = getInterpolationFunction(interpolationType);
  for (let row = 0; row < newImage.height; row++) {
    for (let column = 0; column < newImage.width; column++) {
      const nx = transformPoint(transformMatrix[0], transformMatrix[2], column, row);
      const ny = transformPoint(transformMatrix[1], transformMatrix[2], column, row);
      for (let channel = 0; channel < newImage.channels; channel++) {
        const newValue = interpolate(image, nx, ny, channel, interpolateBorder, clamp);
        newImage.setValue(column, row, channel, newValue);
      }
    }
  }
  return newImage;
}
/**
 * Apply a transformation to a point.
 * @param transform - Transformation matrix.
 * @param perspective - Perspective matrix.
 * @param column - Column of the point.
 * @param row - Row of the point.
 * @returns New value.
 */
function transformPoint(transform, perspective, column, row) {
  return (transform[0] * column + transform[1] * row + transform[2]) / (perspective[0] * column + perspective[1] * row + perspective[2]);
}
function isValidMatrix(transformationMatrix) {
  return transformationMatrix.length === 3 && transformationMatrix[0].length === 3 && transformationMatrix[1].length === 3 && transformationMatrix[2].length === 3 || transformationMatrix.length === 2 && transformationMatrix[0].length === 3 && transformationMatrix[1].length === 3;
}

/**
 * Returns a resized copy of an image.
 * @param image - Original image.
 * @param options - Resize options.
 * @returns The new image.
 */
function resize(image, options) {
  const {
    interpolationType = 'bilinear',
    borderType = 'replicate',
    borderValue = 0
  } = options;
  const {
    width,
    height,
    xFactor,
    yFactor
  } = checkOptions(image, options);
  return transform(image, [[xFactor, 0, xFactor / 2], [0, yFactor, yFactor / 2]], {
    interpolationType,
    borderType,
    borderValue,
    height,
    width
  });
}
/**
 * Verify that the resize options are valid.
 * @param image - Image.
 * @param options - Resize options.
 * @returns Resize options.
 */
function checkOptions(image, options) {
  const {
    width,
    height,
    xFactor,
    yFactor,
    preserveAspectRatio = true
  } = options;
  if (width === undefined && height === undefined && xFactor === undefined && yFactor === undefined) {
    throw new TypeError('at least one of the width, height, xFactor or yFactor options must be passed');
  }
  let newWidth;
  let newHeight;
  const maybeWidth = getSize(width, xFactor, image.width, preserveAspectRatio);
  const maybeHeight = getSize(height, yFactor, image.height, preserveAspectRatio);
  if (maybeWidth === undefined) {
    assert(maybeHeight !== undefined);
    newWidth = Math.round(maybeHeight * (image.width / image.height));
  } else {
    newWidth = maybeWidth;
  }
  if (maybeHeight === undefined) {
    assert(maybeWidth !== undefined);
    newHeight = Math.round(maybeWidth * (image.height / image.width));
  } else {
    newHeight = maybeHeight;
  }
  return {
    width: newWidth,
    height: newHeight,
    xFactor: xFactor ?? newWidth / image.width,
    yFactor: yFactor ?? newHeight / image.height
  };
}
/**
 * Compute automatic new size.
 * @param sizeOpt - Size option.
 * @param factor - Factor option.
 * @param sizeImg - Size of the image.
 * @param preserveAspectRatio - Whether to preserve the aspect ratio.
 * @returns New size.
 */
function getSize(sizeOpt, factor, sizeImg, preserveAspectRatio) {
  if (sizeOpt === undefined) {
    if (factor !== undefined) {
      return Math.round(sizeImg * factor);
    } else if (!preserveAspectRatio) {
      return sizeImg;
    }
  } else if (factor !== undefined) {
    throw new TypeError('factor and size cannot be passed together');
  } else {
    return sizeOpt;
  }
  return undefined;
}

/**
 * Rotates an image in multiples of 90 degrees.
 * @param image - The image to rotate.
 * @param angle - The angle to rotate the image by. Positive values rotate clockwise, negative values rotate counter-clockwise.
 * @returns - The rotated image.
 */
function rotate(image, angle) {
  const newWidth = angle % 180 === 0 ? image.width : image.height;
  const newHeight = angle % 180 === 0 ? image.height : image.width;
  const newImage = Image.createFrom(image, {
    width: newWidth,
    height: newHeight
  });
  if (angle === 90 || angle === -270) {
    for (let column = 0; column < image.width; column++) {
      for (let row = 0; row < image.height; row++) {
        for (let channel = 0; channel < image.channels; channel++) {
          newImage.setValue(newImage.width - row - 1, column, channel, image.getValue(column, row, channel));
        }
      }
    }
  } else if (angle === 180 || angle === -180) {
    for (let column = 0; column < image.width; column++) {
      for (let row = 0; row < image.height; row++) {
        for (let channel = 0; channel < image.channels; channel++) {
          newImage.setValue(newImage.width - column - 1, newImage.height - row - 1, channel, image.getValue(column, row, channel));
        }
      }
    }
  } else if (angle === 270 || angle === -90) {
    for (let column = 0; column < image.width; column++) {
      for (let row = 0; row < image.height; row++) {
        for (let channel = 0; channel < image.channels; channel++) {
          newImage.setValue(row, newImage.height - column - 1, channel, image.getValue(column, row, channel));
        }
      }
    }
  } else {
    throw new RangeError(`invalid angle: ${angle}`);
  }
  return newImage;
}

/**
 * Rotate an image anti-clockwise of a given angle.
 * @param image - Original image.
 * @param angle - Angle in degrees.
 * @param options - Rotate options.
 * @returns A new rotated image.
 */
function transformRotate(image, angle, options = {}) {
  const {
    center = 'center',
    scale = 1,
    ...otherOptions
  } = options;
  let centerCoordinates;
  if (typeof center === 'string') {
    centerCoordinates = image.getCoordinates(center);
  } else {
    centerCoordinates = center;
  }
  const transformMatrix = getRotationMatrix(angle, centerCoordinates, scale);
  return transform(image, transformMatrix, otherOptions);
}
/**
 * Generates a rotation matrix for the given angle.
 * @param angle - Angle in degrees.
 * @param center - Center point of the image.
 * @param scale - Scaling factor.
 * @returns 3 x 3 rotation matrix.
 */
function getRotationMatrix(angle, center, scale) {
  const angleRadians = angle * Math.PI / 180;
  const cos = scale * Math.cos(angleRadians);
  const sin = scale * Math.sin(angleRadians);
  return [[cos, sin, (1 - cos) * center.column - sin * center.row], [-sin, cos, sin * center.column + (1 - cos) * center.row], [0, 0, 1]];
}

// REFERENCES :
// http://graphics.cs.cmu.edu/courses/15-463/2011_fall/Lectures/morphing.pdf
/**
 * Computes a perspective transformation matrix to rectify a quadrilateral region into a rectangle.
 *
 * This function takes four corner points of a quadrilateral (e.g., a document photographed at an angle) and calculates the transformation matrix needed to "unwarp" it into a rectangular image.
 * The output dimensions can be specified or calculated automatically based on the input geometry.
 * @param pts - 4 reference corners.
 * @param options - PerspectiveWarpOptions.
 * @returns - Matrix from 4 points.
 */
function getPerspectiveWarp(pts, options = {}) {
  if (pts.length !== 4) {
    throw new Error(`The array pts must have four elements, which are the four corners. Currently, pts have ${pts.length} elements`);
  }
  const {
    width,
    height
  } = options;
  const [tl, tr, br, bl] = order4Points(pts);
  let widthRect;
  let heightRect;
  if (height && width) {
    widthRect = width;
    heightRect = height;
  } else if (!height && !width) {
    widthRect = Math.ceil(Math.max(distance2Points(tl, tr), distance2Points(bl, br)));
    heightRect = Math.ceil(Math.max(distance2Points(tl, bl), distance2Points(tr, br)));
  } else {
    throw new Error(`Invalid dimensions: ${width ? '`height`' : '`width`'} is missing. ` + `Either provide both width and height, or omit both to auto-calculate dimensions.`);
  }
  const [x1, y1] = [0, 0];
  const [x2, y2] = [widthRect - 1, 0];
  const [x3, y3] = [widthRect - 1, heightRect - 1];
  const [x4, y4] = [0, heightRect - 1];
  const S = new Matrix$1([[x1, y1, 1, 0, 0, 0, -x1 * tl.column, -y1 * tl.column], [x2, y2, 1, 0, 0, 0, -x2 * tr.column, -y2 * tr.column], [x3, y3, 1, 0, 0, 0, -x3 * br.column, -y3 * br.column], [x4, y4, 1, 0, 0, 0, -x4 * bl.column, -y4 * bl.column], [0, 0, 0, x1, y1, 1, -x1 * tl.row, -y1 * tl.row], [0, 0, 0, x2, y2, 1, -x2 * tr.row, -y2 * tr.row], [0, 0, 0, x3, y3, 1, -x3 * br.row, -y3 * br.row], [0, 0, 0, x4, y4, 1, -x4 * bl.row, -y4 * bl.row]]);
  const D = Matrix$1.columnVector([tl.column, tr.column, br.column, bl.column, tl.row, tr.row, br.row, bl.row]);
  const svd = new SingularValueDecomposition(S);
  const T = svd.solve(D).to1DArray(); // solve S*T = D
  T.push(1);
  const M = [];
  for (let i = 0; i < 3; i++) {
    const row = [];
    for (let j = 0; j < 3; j++) {
      row.push(T[i * 3 + j]);
    }
    M.push(row);
  }
  return {
    matrix: M,
    width: widthRect,
    height: heightRect
  };
}
/**
 * Sorts 4 points in order =>[top-left,top-right,bottom-right,bottom-left]. Input points must be in clockwise or counter-clockwise order.
 * @param pts - Array of 4 points.
 * @returns Sorted array of 4 points.
 */
function order4Points(pts) {
  let tl;
  let tr;
  let br;
  let bl;
  let minX = pts[0].column;
  let indexMinX = 0;
  for (let i = 1; i < pts.length; i++) {
    if (pts[i].column < minX) {
      minX = pts[i].column;
      indexMinX = i;
    }
  }
  let minX2 = pts[(indexMinX + 1) % pts.length].column;
  let indexMinX2 = (indexMinX + 1) % pts.length;
  for (let i = 0; i < pts.length; i++) {
    if (pts[i].column < minX2 && i !== indexMinX) {
      minX2 = pts[i].column;
      indexMinX2 = i;
    }
  }
  if (pts[indexMinX2].row < pts[indexMinX].row) {
    tl = pts[indexMinX2];
    bl = pts[indexMinX];
    if (indexMinX !== (indexMinX2 + 1) % 4) {
      tr = pts[(indexMinX2 + 1) % 4];
      br = pts[(indexMinX2 + 2) % 4];
    } else {
      tr = pts[(indexMinX2 + 2) % 4];
      br = pts[(indexMinX2 + 3) % 4];
    }
  } else {
    bl = pts[indexMinX2];
    tl = pts[indexMinX];
    if (indexMinX2 !== (indexMinX + 1) % 4) {
      tr = pts[(indexMinX + 1) % 4];
      br = pts[(indexMinX + 2) % 4];
    } else {
      tr = pts[(indexMinX + 2) % 4];
      br = pts[(indexMinX + 3) % 4];
    }
  }
  return [tl, tr, br, bl];
}
/**
 *  Calculates distance between points.
 * @param p1 - Point1
 * @param p2 - Point2
 * @returns distance between points.
 */
function distance2Points(p1, p2) {
  return Math.hypot(p1.column - p2.column, p1.row - p2.row);
}

/**
 * Rotate a point around a center by a given angle.
 * @param point - The point to rotate
 * @param rotationCenter - The center of rotation
 * @param angle - The angle of rotation in radians
 * @returns The rotated point
 */
function rotatePoint(point, rotationCenter, angle) {
  const angleCos = Math.cos(angle);
  const angleSin = Math.sin(angle);
  const column = point.column * angleCos - point.row * angleSin + (1 - angleCos) * rotationCenter.column + rotationCenter.row * angleSin;
  const row = point.column * angleSin + point.row * angleCos + (1 - angleCos) * rotationCenter.row - rotationCenter.column * angleSin;
  return {
    column,
    row
  };
}

/**
 * Crop an oriented rectangle from an image.
 * If the rectangle's length or width are not an integers, its dimension is expanded in both directions such as the length and width are integers.
 * @param image - The input image
 * @param points - The points of the rectangle. Points must be circling around the rectangle (clockwise or anti-clockwise). The validity of the points passed is assumed and not checked.
 * @param options - Crop options, see {@link CropRectangleOptions}
 * @returns The cropped image. The orientation of the image is the one closest to the rectangle passed as input.
 */
function cropRectangle(image, points, options) {
  if (points.length !== 4) {
    throw new Error('The points array must contain 4 points');
  }
  // get the smallest possible angle which puts the rectangle in an upright position
  const angle = getSmallestAngle(points);
  const center = {
    row: (points[0].row + points[2].row) / 2,
    column: (points[0].column + points[2].column) / 2
  };
  // Rotated points form an upright rectangle
  const rotatedPoints = points.map(p => rotatePoint(p, center, angle));
  const [p1, p2, p3] = rotatedPoints;
  const originalWidth = Math.max(Math.abs(p1.column - p2.column), Math.abs(p2.column - p3.column));
  const originalHeight = Math.max(Math.abs(p1.row - p2.row), Math.abs(p2.row - p3.row));
  // Deal with numerical imprecision when the rectangle actually had a whole number width or height
  const width = Math.min(Math.ceil(originalWidth), Math.ceil(originalWidth - 1e-10));
  const height = Math.min(Math.ceil(originalHeight), Math.ceil(originalHeight - 1e-10));
  // Top left position of the upright rectangle after normalization of width and height
  const expandedTopLeft = {
    row: Math.min(...rotatedPoints.map(p => p.row)) - (height - originalHeight) / 2,
    column: Math.min(...rotatedPoints.map(p => p.column)) - (width - originalWidth) / 2
  };
  const translation = rotatePoint(expandedTopLeft, center, -angle);
  const angleCos = Math.cos(-angle);
  const angleSin = Math.sin(-angle);
  const matrix = [[angleCos, -angleSin, translation.column], [angleSin, angleCos, translation.row]];
  return transform(image, matrix, {
    inverse: true,
    width,
    height,
    ...options
  });
}
/**
 * Get the smallest angle to put the rectangle in an upright position
 * @param points - 2 points forming a line
 * @returns The angle in radians
 */
function getSmallestAngle(points) {
  // Angle respective to horizontal, -π/2 and π/2
  let angleHorizontal = -getAngle(points[1], points[0]);
  if (angleHorizontal > Math.PI / 2) {
    angleHorizontal -= Math.PI;
  } else if (angleHorizontal < -Math.PI / 2) {
    angleHorizontal += Math.PI;
  }
  // angle is between -π/4 and π/4
  let angle = angleHorizontal;
  if (Math.abs(angleHorizontal) > Math.PI / 4) {
    angle = angleHorizontal > 0 ? -Math.PI / 2 + angleHorizontal : Math.PI / 2 + angleHorizontal;
  }
  return angle;
}

/**
 * Paint a mask onto an image and the given position and with the given color.
 * @param image - Image on which to paint the mask.
 * @param mask - Mask to paint on the image.
 * @param options - Paint mask options.
 * @returns The painted image.
 */
function paintMaskOnImage(image, mask, options = {}) {
  const {
    origin = {
      row: 0,
      column: 0
    },
    color = getDefaultColor(image),
    blend = true
  } = options;
  const {
    column,
    row
  } = origin;
  if (color.length !== image.channels) {
    throw new RangeError('the given color is not compatible with the image');
  }
  checkPointIsInteger(origin, 'Origin');
  const result = getOutputImage(image, options, {
    clone: true
  });
  if (blend) {
    checkColorIsNumberArray(color);
    for (let currentRow = Math.max(row, 0); currentRow < Math.min(mask.height + row, image.height); currentRow++) {
      for (let currentColumn = Math.max(column, 0); currentColumn < Math.min(mask.width + column, image.width); currentColumn++) {
        if (mask.getBit(currentColumn - column, currentRow - row)) {
          setBlendedPixel(result, currentColumn, currentRow, color);
        }
      }
    }
  } else {
    for (let currentRow = Math.max(row, 0); currentRow < Math.min(mask.height + row, image.height); currentRow++) {
      for (let currentColumn = Math.max(column, 0); currentColumn < Math.min(mask.width + column, image.width); currentColumn++) {
        if (mask.getBit(currentColumn - column, currentRow - row)) {
          for (let channel = 0; channel < image.channels; channel++) {
            const currentValue = color[channel];
            if (typeof currentValue === 'number') {
              result.setValue(currentColumn, currentRow, channel, currentValue);
            }
          }
        }
      }
    }
  }
  return result;
}
function checkColorIsNumberArray(color) {
  for (const channel of color) {
    if (typeof channel !== 'number') {
      throw new TypeError('cannot have null channels in color if blend is true');
    }
  }
}

/**
 * Paint a mask onto an image and the given position and with the given color.
 * @param image - Image on which to paint the mask.
 * @param mask - Mask to paint on the image.
 * @param options - Paint mask options.
 * @returns The painted image.
 */
function paintMaskOnMask(image, mask, options = {}) {
  const {
    origin = {
      row: 0,
      column: 0
    },
    value = 1
  } = options;
  const {
    column,
    row
  } = origin;
  checkPointIsInteger(origin, 'Origin');
  const result = maskToOutputMask(image, options, {
    clone: true
  });
  for (let currentRow = Math.max(row, 0); currentRow < Math.min(mask.height + row, image.height); currentRow++) {
    for (let currentColumn = Math.max(column, 0); currentColumn < Math.min(mask.width + column, image.width); currentColumn++) {
      if (mask.getBit(currentColumn - column, currentRow - row)) {
        result.setBit(currentColumn, currentRow, value);
      }
    }
  }
  return result;
}

/**
 * Cast `number` to string. Optionally `digits` specifies significant figures.
 * @param number
 * @param figures
 * @returns - A string representation of `number`.
 */
function maybeToPrecision(number, figures) {
  if (number < 0) {
    number = 0 - number;
    if (typeof figures === 'number') {
      return `- ${number.toPrecision(figures)}`;
    } else {
      return `- ${number.toString()}`;
    }
  } else if (typeof figures === 'number') {
    return number.toPrecision(figures);
  } else {
    return number.toString();
  }
}

/**
 * Check that x and y are arrays with the same length.
 * @param x - first array
 * @param y - second array
 * @throws if x or y are not the same length, or if they are not arrays
 */
function checkArrayLength(input, output) {
  // TODO: This function should be removed and replace by
  // https://github.com/mljs/spectra-processing/blob/main/src/xy/xyCheck.ts
  if (!isAnyArray$1(input.x) || !isAnyArray$1(input.y) || !isAnyArray$1(output)) {
    throw new TypeError('x, y and outputs must be arrays');
  }
  if (input.x.length < 2) {
    throw new RangeError('explanatory variable should be two element per point');
  }
  if (input.x.length !== input.y.length) {
    throw new RangeError('x and y data must have the same length');
  }
  if (input.x.length !== output.length) {
    throw new RangeError('input and outputs must have the same length');
  }
}

class BaseRegression2D {
  constructor() {
    if (new.target === BaseRegression2D) {
      throw new Error('BaseRegression must be subclassed');
    }
  }
  predict(inputs) {
    if (isOnePoint(inputs)) {
      return this._predict(inputs);
    } else if (isAnyArray$1(inputs.x)) {
      const {
        x,
        y
      } = inputs;
      const result = new Float64Array(x.length);
      for (let i = 0; i < x.length; i++) {
        result[i] = this._predict({
          x: x[i],
          y: y[i]
        });
      }
      return result;
    } else {
      throw new TypeError('x must be a number or array');
    }
  }
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  _predict(x) {
    throw new Error('_predict must be implemented');
  }
  train() {
    // Do nothing for this package
  }
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  toString(precision) {
    return '';
  }
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  toLaTeX(precision) {
    return '';
  }
  /**
   * Return the correlation coefficient of determination (r) and chi-square.
   * @param x - explanatory variable
   * @param y - response variable
   * @return - Object with further statistics.
   */
  getScore(input, z) {
    checkArrayLength(input, z);
    const y2 = this.predict(input);
    let xSum = 0;
    let ySum = 0;
    let chi2 = 0;
    let rmsd = 0;
    let xSquared = 0;
    let ySquared = 0;
    let xY = 0;
    const n = z.length;
    for (let i = 0; i < n; i++) {
      xSum += y2[i];
      ySum += z[i];
      xSquared += y2[i] * y2[i];
      ySquared += z[i] * z[i];
      xY += y2[i] * z[i];
      if (z[i] !== 0) {
        chi2 += (z[i] - y2[i]) * (z[i] - y2[i]) / z[i];
      }
      rmsd += (z[i] - y2[i]) * (z[i] - y2[i]);
    }
    const r = (n * xY - xSum * ySum) / Math.sqrt((n * xSquared - xSum * xSum) * (n * ySquared - ySum * ySum));
    return {
      r,
      r2: r * r,
      chi2,
      rmsd: Math.sqrt(rmsd / n)
    };
  }
}
function isOnePoint(input) {
  return !isAnyArray$1(input.x);
}

// Implements the Kernel ridge regression algorithm.
// http://www.ics.uci.edu/~welling/classnotes/papers_class/Kernel-Ridge.pdf
class PolynomialRegression2D extends BaseRegression2D {
  order;
  coefficients;
  score;
  /**
   * Constructor for the 2D polynomial fitting
   *
   * @param inputs - independent or explanatory variable
   * @param outputs - dependent or response variable`
   * @constructor
   */
  constructor(inputs, outputs, options = {}) {
    super();
    // @ts-expect-error internal use only
    if (inputs === true) {
      // @ts-expect-error internal use only
      this.coefficients = Matrix$1.columnVector(outputs.coefficients);
      // @ts-expect-error internal use only
      this.order = outputs.order;
      // @ts-expect-error internal use only
      this.score = outputs.score;
    } else {
      checkArrayLength(inputs, outputs);
      const {
        order = 2
      } = options;
      this.order = order;
      this.coefficients = train(inputs, outputs, order);
      this.score = this.getScore(inputs, outputs);
    }
  }
  _predict(newInputs) {
    const {
      x,
      y
    } = newInputs;
    let z = 0;
    let column = 0;
    for (let i = 0; i <= this.order; i++) {
      for (let j = 0; j <= this.order - i; j++) {
        z += x ** i * y ** j * this.coefficients.get(column, 0);
        column++;
      }
    }
    return z;
  }
  toString(precision) {
    return this._toFormula(precision, false);
  }
  toLaTeX(precision) {
    return this._toFormula(precision, true);
  }
  _toFormula(precision, isLaTeX) {
    let sup = '^';
    let closeSup = '';
    let times = ' * ';
    if (isLaTeX) {
      sup = '^{';
      closeSup = '}';
      times = '';
    }
    let fn = '';
    let str = '';
    let column = 0;
    for (let i = 0; i <= this.order; i++) {
      for (let j = 0; j <= this.order - i; j++) {
        str = '';
        const coefficient = this.coefficients.get(column, 0);
        if (coefficient !== 0) {
          str += maybeToPrecision(coefficient, precision);
          if (i === 1) {
            str += `${times}x`;
          } else if (i > 1) {
            str += `${times}x${sup}${i}${closeSup}`;
          }
          if (j === 1) {
            str += `${times}y`;
          } else if (j > 1) {
            str += `${times}y${sup}${j}${closeSup}`;
          }
          if (coefficient > 0) {
            str = ` + ${str}`;
          } else {
            str = ` ${str}`;
          }
        }
        column++;
        fn = str + fn;
      }
    }
    return `f(x, y) = ${fn.startsWith('+') ? fn.slice(1) : fn}`;
  }
  toJSON() {
    return {
      name: 'polyfit2D',
      order: this.order,
      score: this.score,
      coefficients: this.coefficients
    };
  }
  static load(json) {
    if (json.name !== 'polyfit2D') {
      throw new TypeError('not a polyfit2D model');
    }
    //@ts-expect-error internal use only
    return new PolynomialRegression2D(true, json);
  }
}
/**
 * Function that given a column vector return this: vector^power
 *
 * @param x - Column vector.
 * @param power - Pow number.
 * @return {Matrix}
 */
function powColVector(x, power) {
  const result = x.clone();
  for (let i = 0; i < x.rows; ++i) {
    result.set(i, 0, result.get(i, 0) ** power);
  }
  return result;
}
/**
 * Function that fits the model given the data(x) and predictions(y).
 * The third argument is an object with the following options:
 * * order: order of the polynomial to fit.
 *
 * @param x - A matrix with n rows and 2 columns.
 * @param y - A vector of the prediction values.
 */
function train(input, y, order) {
  if (!Matrix$1.isMatrix(y)) y = Matrix$1.columnVector(y);
  const x = new Matrix$1(y.rows, 2);
  x.setColumn(0, input.x);
  x.setColumn(1, input.y);
  if (y.rows !== x.rows) {
    y = y.transpose();
  }
  if (x.columns !== 2) {
    throw new RangeError(`You give x with ${x.columns} columns and it must be 2`);
  }
  if (x.rows !== y.rows) {
    throw new RangeError('x and y must have the same rows');
  }
  const examples = x.rows;
  const nbCoefficients = (order + 2) * (order + 1) / 2;
  if (examples < nbCoefficients) {
    throw new TypeError('Insufficient number of points to create regression model.');
  }
  const x1 = x.getColumnVector(0);
  const x2 = x.getColumnVector(1);
  const scaleX1 = 1.0 / x1.clone().abs().max();
  const scaleX2 = 1.0 / x2.clone().abs().max();
  const scaleY = 1.0 / y.clone().abs().max();
  x1.mulColumn(0, scaleX1);
  x2.mulColumn(0, scaleX2);
  y.mulColumn(0, scaleY);
  const A = new Matrix$1(examples, nbCoefficients);
  let col = 0;
  for (let i = 0; i <= order; ++i) {
    const limit = order - i;
    for (let j = 0; j <= limit; ++j) {
      const result = powColVector(x1, i).mulColumnVector(powColVector(x2, j));
      A.setColumn(col, result);
      col++;
    }
  }
  const svd = new SVD(A.transpose(), {
    computeLeftSingularVectors: true,
    computeRightSingularVectors: true,
    autoTranspose: false
  });
  let qqs = Matrix$1.rowVector(svd.diagonal);
  qqs = qqs.apply((i, j) => {
    if (qqs.get(i, j) >= 1e-15) qqs.set(i, j, 1 / qqs.get(i, j));else qqs.set(i, j, 0);
  });
  const qqs1 = Matrix$1.zeros(examples, nbCoefficients);
  for (let i = 0; i < nbCoefficients; ++i) {
    qqs1.set(i, i, qqs.get(0, i));
  }
  qqs = qqs1;
  const U = svd.rightSingularVectors;
  const V = svd.leftSingularVectors;
  const coefficients = V.mmul(qqs.transpose()).mmul(U.transpose()).mmul(y);
  for (let i = 0, col = 0; i <= nbCoefficients; ++i) {
    const limit = order - i;
    for (let j = 0; j <= limit; ++j) {
      coefficients.set(col, 0, coefficients.get(col, 0) * scaleX1 ** i * scaleX2 ** j / scaleY);
      col++;
    }
  }
  return coefficients;
}

/**
 * Corrects background from an image for baseline correction.
 * @param image - Image to subtract background from.
 * @param options - CorrectBackgroundOptions.
 * @returns Image with corrected baseline.
 */
function correctBackground(image, options) {
  const {
    background,
    order = 2,
    backgroundKind = 'light'
  } = options;
  checkProcessable$1(image, {
    colorModel: ['GREY']
  });
  const columns = new Array();
  const rows = new Array();
  const values = new Array();
  for (const point of background) {
    columns.push(point.column);
    rows.push(point.row);
    values.push(image.getValueByPoint(point, 0));
  }
  const model = new PolynomialRegression2D({
    x: columns,
    y: rows
  }, values, {
    order
  });
  const points = {
    x: [],
    y: []
  };
  for (let row = 0; row < image.height; row++) {
    for (let column = 0; column < image.width; column++) {
      points.x.push(column);
      points.y.push(row);
    }
  }
  const Y = model.predict(points);
  for (let row = 0; row < image.height; row++) {
    for (let column = 0; column < image.width; column++) {
      const value = Math.abs(image.getValue(column, row, 0) - Y[row * image.width + column]);
      image.setValue(column, row, 0, value);
    }
  }
  if (backgroundKind === 'light') {
    return image.invert();
  } else {
    return image;
  }
}

/**
 * Invert the components of an image.
 * @param image - The image to invert.
 * @param options - Invert options.
 * @returns The inverted image.
 */
function invert(image, options) {
  if (image instanceof Image) {
    const newImage = getOutputImage(image, options);
    if (image.alpha) {
      copyAlpha(image, newImage);
    }
    const {
      maxValue,
      size
    } = newImage;
    for (let i = 0; i < size; i++) {
      for (let component = 0; component < image.components; component++) {
        newImage.setValueByIndex(i, component, maxValue - image.getValueByIndex(i, component));
      }
    }
    return newImage;
  } else {
    const newImage = maskToOutputMask(image, options);
    for (let i = 0; i < newImage.size; i++) {
      newImage.setBitByIndex(i, !image.getBitByIndex(i));
    }
    return newImage;
  }
}

/**
 * Level the image using the optional input and output value. The default options allow to increase the image's contrast.
 * @param image - Image to process.
 * @param options - Level options.
 * @returns The levelled image.
 */
function level(image, options = {}) {
  const minMax = image.minMax();
  let {
    inputMin = minMax.min,
    inputMax = minMax.max,
    outputMin = 0,
    outputMax = image.maxValue,
    gamma = 1
  } = options;
  const {
    channels = new Array(image.components).fill(0).map((value, index) => index)
  } = options;
  validateChannels(channels, image);
  checkProcessable$1(image, {
    bitDepth: [8, 16]
  });
  const newImage = getOutputImage(image, options, {
    clone: true
  });
  const clamp = getClamp(image);
  inputMin = getValueArray(inputMin, image.channels);
  inputMax = getValueArray(inputMax, image.channels);
  outputMin = getValueArray(outputMin, image.channels);
  outputMax = getValueArray(outputMax, image.channels);
  gamma = getValueArray(gamma, image.channels);
  for (let row = 0; row < image.height; row++) {
    for (let column = 0; column < image.width; column++) {
      for (const channel of channels) {
        const currentValue = image.getValue(column, row, channel);
        const clamped = Math.max(Math.min(currentValue, inputMax[channel]), inputMin[channel]);
        let ratio = clamp((clamped - inputMin[channel]) / (inputMax[channel] - inputMin[channel]));
        if (Number.isNaN(ratio)) ratio = 0;
        const result = clamp(ratio ** (1 / gamma[channel]) * (outputMax[channel] - outputMin[channel]) + outputMin[channel]);
        newImage.setValue(column, row, channel, result);
      }
    }
  }
  return newImage;
}
/**
 * Get an array with correct values for each channel to process.
 * @param value - Number or array to transform to the final array.
 * @param imageChannels - Number of channels processed in the level function.
 * @returns Array of values for each channel.
 */
function getValueArray(value, imageChannels) {
  if (Array.isArray(value)) {
    if (value.length === imageChannels) {
      return value;
    } else {
      throw new RangeError('array length is not compatible with channel option');
    }
  } else {
    return new Array(imageChannels).fill(value);
  }
}

/**
 * Perform an OR operation on two masks.
 * @param mask - First mask.
 * @param otherMask - Second mask.
 * @param options - Or options.
 * @returns OR of the two masks.
 */
function or(mask, otherMask, options) {
  const newMask = maskToOutputMask(mask, options);
  if (mask.width !== otherMask.width || mask.height !== otherMask.height) {
    throw new RangeError('both masks must have the same size');
  }
  for (let i = 0; i < newMask.size; i++) {
    if (mask.getBitByIndex(i) || otherMask.getBitByIndex(i)) {
      newMask.setBitByIndex(i, 1);
    } else {
      newMask.setBitByIndex(i, 0);
    }
  }
  return newMask;
}

/**
 * Apply a flipX filter to an image.
 * @param image - Image to process.
 * @returns The processed image.
 */
function flipX(image) {
  checkProcessable$1(image, {
    bitDepth: [8, 16]
  });
  for (let row = 0; row < image.height; row++) {
    for (let column = 0; column < Math.floor(image.width / 2); column++) {
      const currentCol = column;
      const oppositeCol = image.width - column - 1;
      for (let channel = 0; channel < image.channels; channel++) {
        const tmp = image.getValue(currentCol, row, channel);
        image.setValue(currentCol, row, channel, image.getValue(oppositeCol, row, channel));
        image.setValue(oppositeCol, row, channel, tmp);
      }
    }
  }
  return image;
}

/**
 * Apply a flipY filter to an image.
 * @param image - Image to process.
 * @returns The processed image.
 */
function flipY(image) {
  checkProcessable$1(image, {
    bitDepth: [8, 16]
  });
  for (let row = 0; row < Math.floor(image.height / 2); row++) {
    for (let column = 0; column < image.width; column++) {
      const currentRow = row;
      const oppositeRow = image.height - row - 1;
      for (let channel = 0; channel < image.channels; channel++) {
        const tmp = image.getValue(column, currentRow, channel);
        image.setValue(column, currentRow, channel, image.getValue(column, oppositeRow, channel));
        image.setValue(column, oppositeRow, channel, tmp);
      }
    }
  }
  return image;
}

/**
 * Apply a flip filter to an image.
 * @param image - Image to process.
 * @param options - Flip options.
 * @returns - The processed image.
 */
function flip(image, options = {}) {
  const {
    axis = 'horizontal'
  } = options;
  const newImage = getOutputImage(image, options, {
    clone: true
  });
  if (axis === 'horizontal') {
    return flipX(newImage);
  } else if (axis === 'vertical') {
    return flipY(newImage);
  } else {
    return flipY(flipX(newImage));
  }
}

/**
 * Calculate a new image that replaces all pixel values by the median of neighbouring pixels.
 * @param image - Image to be filtered.
 * @param options - MedianFilterOptions
 * @returns Image after median filter.
 */
function medianFilter(image, options = {}) {
  const {
    cellSize = 3,
    borderType = 'reflect101',
    borderValue = getDefaultColor(image)
  } = options;
  checkProcessable$1(image, {
    bitDepth: [8, 16]
  });
  if (cellSize < 1) {
    throw new RangeError(`Invalid property "cellSize". Must be greater than 0. Received ${cellSize}.`);
  }
  if (cellSize % 2 === 0) {
    throw new RangeError(`Invalid property "cellSize". Must be an odd number. Received ${cellSize}.`);
  }
  const interpolateBorder = getBorderInterpolation(borderType, borderValue);
  const newImage = Image.createFrom(image);
  const size = cellSize ** 2;
  const cellValues = new Uint16Array(size);
  const halfCellSize = (cellSize - 1) / 2;
  for (let channel = 0; channel < image.channels; channel++) {
    for (let row = 0; row < image.height; row++) {
      for (let column = 0; column < image.width; column++) {
        let n = 0;
        for (let cellRow = -halfCellSize; cellRow <= halfCellSize; cellRow++) {
          for (let cellColumn = -halfCellSize; cellColumn <= halfCellSize; cellColumn++) {
            cellValues[n++] = interpolateBorder(column + cellColumn, row + cellRow, channel, image);
          }
        }
        newImage.setValue(column, row, channel, xMedian(cellValues));
      }
    }
  }
  return newImage;
}

/**
 * Function to pixelate an image.
 * @param image - Image to be pixelated.
 * @param options - PixelateOptions.
 * @returns Pixelated Image.
 */
function pixelate(image, options) {
  const {
    cellSize,
    algorithm = 'center'
  } = options;
  if (!Number.isInteger(cellSize)) {
    throw new TypeError('cellSize must be an integer');
  }
  if (cellSize < 2) {
    throw new RangeError('cellSize must be greater than 1');
  }
  const newImage = getOutputImage(image, options);
  const getCellValue = getCellValueFunction(algorithm);
  for (let channel = 0; channel < image.channels; channel++) {
    for (let column = 0; column < image.width; column += cellSize) {
      for (let row = 0; row < image.height; row += cellSize) {
        const currentCellWidth = Math.min(cellSize, image.width - column);
        const currentCellHeight = Math.min(cellSize, image.height - row);
        const value = getCellValue(image, channel, {
          width: currentCellWidth,
          height: currentCellHeight,
          origin: {
            column,
            row
          }
        });
        for (let newColumn = column; newColumn < column + currentCellWidth; newColumn++) {
          for (let newRow = row; newRow < row + currentCellHeight; newRow++) {
            newImage.setValue(newColumn, newRow, channel, value);
          }
        }
      }
    }
  }
  return newImage;
}
/**
 * Computes the center value for the current sector
 * @param image - image used for the algorithm
 * @param channel - image channel toto find center value of
 * @param options - GetValueOptions
 * @returns center value
 */
function getCellCenter(image, channel, options) {
  const center = {
    column: Math.floor((options.origin.column + options.origin.column + options.width - 1) / 2),
    row: Math.floor((options.origin.row + options.origin.row + options.height - 1) / 2)
  };
  const value = image.getValue(center.column, center.row, channel);
  return value;
}
/**
 * Computes mean value for the current sector
 * @param image - image used for algorithm
 * @param channel - current channel of an image
 * @param options - GetValueOptions
 * @returns mean value
 */
function getCellMean(image, channel, options) {
  let sum = 0;
  for (let column = options.origin.column; column < options.origin.column + options.width; column++) {
    for (let row = options.origin.row; row < options.origin.row + options.height; row++) {
      sum += image.getValue(column, row, channel);
    }
  }
  return Math.round(sum / (options.width * options.height));
}
/**
 * Computes a median value for the current sector
 * @param image - image used algorithm
 * @param channel - current channel of an image
 * @param options - GetValueOptions
 * @returns median value
 */
function getCellMedian(image, channel, options) {
  const array = [];
  for (let column = options.origin.column; column < options.origin.column + options.width; column++) {
    for (let row = options.origin.row; row < options.origin.row + options.height; row++) {
      array.push(image.getValue(column, row, channel));
    }
  }
  return xMedian(array);
}
/**
 *  Chooses which algorithm to use for pixelization and returns a function to use for computation
 * @param algorithm - string with the name of an algorithm
 * @returns function
 */
function getCellValueFunction(algorithm) {
  switch (algorithm) {
    case 'mean':
      return getCellMean;
    case 'median':
      return getCellMedian;
    case 'center':
      return getCellCenter;
    default:
      assertUnreachable(algorithm);
      break;
  }
}

// TODO: This function could be optimised by following the contour instead of scanning all pixels.
/**
 * Return an array with the coordinates of the pixels that are on the border of the mask.
 * The reference is the top-left corner of the ROI.
 * @param mask - Mask to process.
 * @param options - Get border points options.
 * @returns The array of border pixels.
 */
function getBorderPoints$1(mask, options = {}) {
  const {
    innerBorders = false,
    allowCorners = false
  } = options;
  if (!innerBorders) {
    mask = mask.solidFill();
  }
  const borders = [];
  // first process frame pixels
  for (let column = 0; column < mask.width; column++) {
    if (mask.getBit(column, 0)) {
      borders.push({
        column,
        row: 0
      });
    }
    if (mask.getBit(column, mask.height - 1)) {
      borders.push({
        column,
        row: mask.height - 1
      });
    }
  }
  for (let row = 0; row < mask.height; row++) {
    if (mask.getBit(0, row)) {
      borders.push({
        column: 0,
        row
      });
    }
    if (mask.getBit(mask.width - 1, row)) {
      borders.push({
        column: mask.width - 1,
        row
      });
    }
  }
  for (let row = 1; row < mask.height - 1; row++) {
    for (let column = 1; column < mask.width - 1; column++) {
      if (mask.getBit(column, row)) {
        if (mask.getBit(column - 1, row) === 0 || mask.getBit(column, row - 1) === 0 || mask.getBit(column + 1, row) === 0 || mask.getBit(column, row + 1) === 0) {
          borders.push({
            column,
            row
          });
        }
        if (allowCorners && (mask.getBit(column - 1, row - 1) === 0 || mask.getBit(column - 1, row + 1) === 0 || mask.getBit(column + 1, row - 1) === 0 || mask.getBit(column + 1, row + 1) === 0)) {
          borders.push({
            column,
            row
          });
        }
      }
    }
  }
  return borders;
}

/**
 * Compute the length of a segment defined by two points.
 * @param p1 - First point.
 * @param p2 - Second point.
 * @returns Length of the segment.
 */
function getLineLength(p1, p2) {
  return Math.hypot(p1.column - p2.column, p1.row - p2.row);
}

/**
 * Compute the perimeter of a polygon.
 * @param points - Array of polygon vertices.
 * @returns The perimeter.
 */
function getPolygonPerimeter(points) {
  let perimeter = 0;
  for (let i = 0; i < points.length; i++) {
    perimeter += getLineLength(points[(i + 1) % points.length], points[i]);
  }
  return perimeter;
}
/**
 * Compute the area of a polygon.
 * Based on the algorithm described on
 * @see {@link https://web.archive.org/web/20100405070507/http://valis.cs.uiuc.edu/~sariel/research/CG/compgeom/msg00831.html}
 * @param points - Array of polygon vertices.
 * @returns The area.
 */
function getPolygonArea(points) {
  let area = 0;
  for (let current = 0; current < points.length; current++) {
    const next = (current + 1) % points.length;
    area += points[current].column * points[next].row;
    area -= points[current].row * points[next].column;
  }
  return Math.abs(area / 2);
}

/**
 * Gets point's row and column from their index and mask width.
 * @param index - point's index.
 * @param maskWidth - mask width.
 * @returns array of point's row and column.
 */
function getCoordsFromIndex(index, maskWidth) {
  return [Math.floor(index / maskWidth), index % maskWidth];
}
/**
 * Safely get the bit value at the given column and row in the mask, returning 0 if out of bounds.
 * @param mask - Mask to get the bit from.
 * @param col - Column index.
 * @param row - Row index.
 * @returns the bit value.
 */
function getBitSafe(mask, col, row) {
  if (!isInBounds(mask, col, row)) return 0;
  return mask.getBit(col, row);
}
/**
 * Checks if the given column and row are within the bounds of the mask.
 * @param mask - Mask to check against.
 * @param col - Column index.
 * @param row - Row index.
 * @returns whether the given column and row are within the bounds of the mask.
 */
function isInBounds(mask, col, row) {
  return col >= 0 && col < mask.width && row >= 0 && row < mask.height;
}

/**
 * Possible directions.
 */
const directions = [{
  dc: -1,
  dr: 0
},
// left
{
  dc: -1,
  dr: -1
},
// up-left
{
  dc: 0,
  dr: -1
},
// up
{
  dc: 1,
  dr: -1
},
// up-right
{
  dc: 1,
  dr: 0
},
// right
{
  dc: 1,
  dr: 1
},
// down-right
{
  dc: 0,
  dr: 1
},
// down
{
  dc: -1,
  dr: 1
} // down-left
];
// Lookup table for directions' index.
const directionIndexLookup = new Int8Array(9).fill(-1);
for (let i = 0; i < directions.length; i++) {
  const {
    dc,
    dr
  } = directions[i];
  directionIndexLookup[(dr + 1) * 3 + (dc + 1)] = i;
}
/**
 * Return an array with the coordinates of the pixels that are on the border of the mask using Moore's tracing algorithm.
 * The reference is the top-left corner of the ROI.
 * @param mask - Mask to process.
 * @returns The array of border pixels.
 */
function getContourMoore(mask) {
  let index = 0;
  const contour = [];
  const visited = new Uint8Array(mask.width * mask.height);
  while (mask.getBitByIndex(index) !== 1 && index !== mask.size) {
    index++;
  }
  if (index === mask.size) return contour;
  const [row, col] = getCoordsFromIndex(index, mask.width);
  const startingPoint = {
    column: col,
    row
  };
  let currentPoint = startingPoint;
  visited[index] = 1;
  contour.push(currentPoint);
  const firstNext = findNextPoint(mask, currentPoint, {
    column: col - 1,
    row
  });
  if (!firstNext) {
    return contour;
  }
  let startingBacktrackPoint = firstNext.prevPoint;
  let backtrackPoint = firstNext.prevPoint;
  currentPoint = firstNext.currPoint;
  while (true) {
    index = currentPoint.row * mask.width + currentPoint.column;
    if (!visited[index]) {
      visited[index] = 1;
      contour.push(currentPoint);
    }
    const next = findNextPoint(mask, currentPoint, backtrackPoint);
    assert$1.ok(next, 'Next border point is undefined.');
    backtrackPoint = next.prevPoint;
    currentPoint = next.currPoint;
    if (currentPoint.column === startingPoint.column && currentPoint.row === startingPoint.row) {
      if (backtrackPoint.column === startingBacktrackPoint.column && backtrackPoint.row === startingBacktrackPoint.row) {
        break;
      } else {
        startingBacktrackPoint = backtrackPoint;
      }
    }
  }
  return contour;
}
/**
 * Finds next point to trace.
 * @param mask - Mask in check.
 * @param current - Current border point.
 * @param previous - Last non-border point to start search from.
 * @returns Object with new border point and last non-border point.
 */
function findNextPoint(mask, current, previous) {
  let prevPoint = previous;
  // Vector from current back to previous
  const backDc = previous.column - current.column;
  const backDr = previous.row - current.row;
  const startIndex = directionIndexLookup[(backDr + 1) * 3 + (backDc + 1)];
  // Scan clockwise starting from that index.
  for (let i = 0; i < directions.length; i++) {
    const {
      dc,
      dr
    } = directions.at((startIndex + i) % directions.length);
    const newCol = current.column + dc;
    const newRow = current.row + dr;
    if (getBitSafe(mask, newCol, newRow) === 1) {
      // Stores found border point and last non-border point that
      // was found. Will be used as a starting point in the next
      // iteration.
      return {
        prevPoint,
        currPoint: {
          column: newCol,
          row: newRow
        }
      };
    } else {
      prevPoint = {
        column: newCol,
        row: newRow
      };
    }
  }
  // Is triggered only if the point has no neighbours. So it is undefined
  // only if mask is made of one pixel.
  return undefined;
}

const DR = [-1, 0, 1, 0];
const DC = [0, 1, 0, -1];
function turnLeft(d) {
  return (d + 3) % 4;
}
function turnRight(d) {
  return (d + 1) % 4;
}
/**
 * Return an array with the coordinates of the pixels that are on the
 * external border of the mask using Theo Pavlidis's tracing algorithm.
 * The reference is the top-left corner of the ROI.
 * @param mask - Mask to process.
 * @returns The array of external border pixels.
 */
function getContourPavlidis(mask) {
  let index = 0;
  while (index < mask.size && mask.getBitByIndex(index) !== 1) {
    index++;
  }
  if (index === mask.size) return [];
  const [row, col] = getCoordsFromIndex(index, mask.width);
  return traceFrom(mask, col, row);
}
/**
 * Traces contour using Pavlidis algorithm.
 * @param mask - Mask in check.
 * @param startCol - Starting column.
 * @param startRow - Starting row.
 * @returns Array of contour points.
 */
function traceFrom(mask, startCol, startRow) {
  let row = startRow;
  let column = startCol;
  let dir = 2;
  let inPlaceTurns = 0;
  const seen = new Uint8Array(mask.width * mask.height);
  const contour = [];
  let visits = 0;
  while (true) {
    const idx = row * mask.width + column;
    if (!seen[idx]) {
      seen[idx] = 1;
      contour.push({
        row,
        column
      });
    } else if (row === startRow && column === startCol) {
      if (visits === 2) {
        break;
      } else {
        visits++;
      }
    }
    const left = turnLeft(dir);
    const right = turnRight(dir);
    const c1r = row + DR[left];
    const c1c = column + DC[left];
    const c2r = row + DR[dir];
    const c2c = column + DC[dir];
    const c3r = row + DR[right];
    const c3c = column + DC[right];
    if (getBitSafe(mask, c1c, c1r) === 1) {
      dir = left;
      row = c1r;
      column = c1c;
      inPlaceTurns = 0;
    } else if (getBitSafe(mask, c2c, c2r) === 1) {
      row = c2r;
      column = c2c;
      inPlaceTurns = 0;
    } else if (getBitSafe(mask, c3c, c3r) === 1) {
      dir = right;
      row = c3r;
      column = c3c;
      inPlaceTurns = 0;
    } else {
      dir = right;
      inPlaceTurns++;
      if (inPlaceTurns >= 4) break;
    }
  }
  return contour;
}

/**
 * Finds external contour of the mask.
 * @param mask - Mask to find contours from.
 * @param options - GetExternalContourOptions.
 * @returns Array of contour points.
 */
function getExternalContour$1(mask, options = {}) {
  const {
    allowCorners = false
  } = options;
  if (allowCorners) {
    return getContourPavlidis(mask);
  } else {
    return getContourMoore(mask);
  }
}

/**
 * Get the pixels that surround an ROI. The pixels include the top and left borders,
 * but extend the right and bottom one by one pixel.
 * This allows to compute the minimum bounding rectangle with the correct surface.
 * This method is only used to calculate minimalBoundRectangle and convexHull.
 * @param mask - The ROI for which to get the extended border points.
 * @returns - The array of points.
 */
function getExtendedBorderPoints(mask) {
  const borderPoints = getExternalContour$1(mask);
  const result = [];
  for (const point of borderPoints) {
    result.push(point, {
      column: point.column + 1,
      row: point.row
    }, {
      column: point.column + 1,
      row: point.row + 1
    }, {
      column: point.column,
      row: point.row + 1
    });
  }
  return result;
}

/**
 * Computes the convex hull of a binary image using Andrew's Monotone Chain Algorithm
 * @see {@link http://www.algorithmist.com/index.php/Monotone_Chain_Convex_Hull}
 * @param points - An array of points.
 * @param options - MCCH Algorithm options.
 * @returns Coordinates of the convex hull in clockwise order.
 */
function monotoneChainConvexHull(points, options = {}) {
  const {
    sorted = false
  } = options;
  if (!sorted) {
    points = points.slice();
    points.sort(byXThenY);
  }
  const n = points.length;
  const result = new Array(n * 2);
  let k = 0;
  for (let i = 0; i < n; i++) {
    const point = points[i];
    while (k >= 2 && cw(result[k - 2], result[k - 1], point) <= 0) {
      k--;
    }
    result[k++] = point;
  }
  const t = k + 1;
  for (let i = n - 2; i >= 0; i--) {
    const point = points[i];
    while (k >= t && cw(result[k - 2], result[k - 1], point) <= 0) {
      k--;
    }
    result[k++] = point;
  }
  return result.slice(0, k - 1);
}
function cw(p1, p2, p3) {
  return (p2.row - p1.row) * (p3.column - p1.column) - (p2.column - p1.column) * (p3.row - p1.row);
}
function byXThenY(point1, point2) {
  if (point1.column === point2.column) {
    return point1.row - point2.row;
  }
  return point1.column - point2.column;
}
// 0 -> column, 1 -> row

/**
 * Get the vertices of the convex Hull polygon of a mask.
 * @param mask - Mask to process.
 * @returns Array of the vertices of the convex Hull in clockwise order.
 */
function getConvexHull(mask) {
  const borderPoints = getExtendedBorderPoints(mask);
  if (borderPoints.length === 0) {
    return {
      points: [],
      surface: 0,
      perimeter: 0
    };
  }
  const points = monotoneChainConvexHull(borderPoints);
  const perimeter = getPolygonPerimeter(points);
  const surface = getPolygonArea(points);
  return {
    points,
    perimeter,
    surface
  };
}

/**
 * Computes the Feret diameters.
 * @see {@link https://www.sympatec.com/en/particle-measurement/glossary/particle-shape/#}
 * @see {@link http://portal.s2nano.org:8282/files/TEM_protocol_NANoREG.pdf}
 * @param mask - The mask of the ROI.
 * @returns The Feret diameters.
 */
function getFeret(mask) {
  const hull = mask.getConvexHull();
  const hullPoints = hull.points;
  if (hull.surface === 0) {
    return {
      minDiameter: {
        length: 0,
        points: [{
          column: 0,
          row: 0
        }, {
          column: 0,
          row: 0
        }],
        angle: 0,
        calliperLines: [[{
          column: 0,
          row: 0
        }, {
          column: 0,
          row: 0
        }], [{
          column: 0,
          row: 0
        }, {
          column: 0,
          row: 0
        }]]
      },
      maxDiameter: {
        length: 0,
        points: [{
          column: 0,
          row: 0
        }, {
          column: 0,
          row: 0
        }],
        angle: 0,
        calliperLines: [[{
          column: 0,
          row: 0
        }, {
          column: 0,
          row: 0
        }], [{
          column: 0,
          row: 0
        }, {
          column: 0,
          row: 0
        }]]
      },
      aspectRatio: 1
    };
  }
  // Compute minimum diameter
  let minWidth = Number.POSITIVE_INFINITY;
  let minWidthAngle = 0;
  let minLinePoints = [];
  let minLines;
  for (let i = 0; i < hullPoints.length; i++) {
    const angle = getAngle(hullPoints[i], hullPoints[(i + 1) % hullPoints.length]);
    // We rotate so that it is parallel to X axis.
    const rotatedPoints = rotate$1(-angle, hullPoints);
    let currentWidth = 0;
    let currentMinLinePoints = [];
    for (let j = 0; j < hullPoints.length; j++) {
      const absWidth = Math.abs(rotatedPoints[i].row - rotatedPoints[j].row);
      if (absWidth > currentWidth) {
        currentWidth = absWidth;
        currentMinLinePoints = [rotatedPoints[i], rotatedPoints[j]];
      }
    }
    if (currentWidth < minWidth) {
      minWidth = currentWidth;
      minWidthAngle = angle;
      minLinePoints = currentMinLinePoints;
      const {
        minIndex: currentMin,
        maxIndex: currentMax
      } = findPointIndexesOfExtremeColumns(rotatedPoints);
      minLines = getMinLines(minWidthAngle, currentMin, currentMax, rotatedPoints, minLinePoints);
    }
  }
  const minDiameter = {
    points: rotate$1(minWidthAngle, minLinePoints),
    length: minWidth,
    angle: toDegrees(minWidthAngle),
    calliperLines: minLines
  };
  // Compute maximum diameter
  let maxLinePoints = [];
  let maxSquaredWidth = 0;
  let maxLineIndex = [];
  for (let i = 0; i < hullPoints.length - 1; i++) {
    for (let j = i + 1; j < hullPoints.length; j++) {
      const currentSquaredWidth = (hullPoints[i].column - hullPoints[j].column) ** 2 + (hullPoints[i].row - hullPoints[j].row) ** 2;
      if (currentSquaredWidth > maxSquaredWidth) {
        maxSquaredWidth = currentSquaredWidth;
        maxLinePoints = [hullPoints[i], hullPoints[j]];
        maxLineIndex = [i, j];
      }
    }
  }
  const maxAngle = getAngle(maxLinePoints[0], maxLinePoints[1]);
  const rotatedMaxPoints = rotate$1(-maxAngle, hullPoints);
  const {
    minIndex: currentMin,
    maxIndex: currentMax
  } = findPointsIndexesOfExtremeRows(rotatedMaxPoints);
  const maxLines = getMaxLines(maxAngle, currentMin, currentMax, rotatedMaxPoints, maxLineIndex);
  const maxDiameter = {
    length: Math.sqrt(maxSquaredWidth),
    angle: toDegrees(getAngle(maxLinePoints[0], maxLinePoints[1])),
    points: maxLinePoints,
    calliperLines: maxLines
  };
  return {
    minDiameter,
    maxDiameter,
    aspectRatio: minDiameter.length / maxDiameter.length
  };
}
function findPointIndexesOfExtremeColumns(points) {
  let maxIndex = 0;
  let minIndex = 0;
  for (let i = 0; i < points.length; i++) {
    if (points[i].column > points[maxIndex].column) {
      maxIndex = i;
    }
    if (points[i].column < points[minIndex].column) {
      minIndex = i;
    }
  }
  return {
    minIndex,
    maxIndex
  };
}
function findPointsIndexesOfExtremeRows(points) {
  let maxIndex = 0;
  let minIndex = 0;
  for (let i = 0; i < points.length; i++) {
    if (points[i].row > points[maxIndex].row) {
      maxIndex = i;
    }
    if (points[i].row < points[minIndex].row) {
      minIndex = i;
    }
  }
  return {
    minIndex,
    maxIndex
  };
}
function getMinLines(angle, min, max, rotatedPoints, feretPoints) {
  const minLine1 = [{
    column: rotatedPoints[min].column,
    row: feretPoints[0].row
  }, {
    column: rotatedPoints[max].column,
    row: feretPoints[0].row
  }];
  const minLine2 = [{
    column: rotatedPoints[min].column,
    row: feretPoints[1].row
  }, {
    column: rotatedPoints[max].column,
    row: feretPoints[1].row
  }];
  return [rotate$1(angle, minLine1), rotate$1(angle, minLine2)];
}
function getMaxLines(angle, min, max, rotatedPoints, index) {
  const maxLine1 = [{
    column: rotatedPoints[index[0]].column,
    row: rotatedPoints[min].row
  }, {
    column: rotatedPoints[index[0]].column,
    row: rotatedPoints[max].row
  }];
  const maxLine2 = [{
    column: rotatedPoints[index[1]].column,
    row: rotatedPoints[min].row
  }, {
    column: rotatedPoints[index[1]].column,
    row: rotatedPoints[max].row
  }];
  return [rotate$1(angle, maxLine1), rotate$1(angle, maxLine2)];
}

const leftFirst = (mbrPoint1, mbrPoint2) => mbrPoint1.column <= mbrPoint2.column ? -1 : 1;
const topFirst = (mbrPoint1, mbrPoint2) => mbrPoint1.row >= mbrPoint2.row ? -1 : 1;
/**
 * Get the anti-clockwise angle in degrees between the MBR and a horizontal line.
 * @param mbr - MBR to process.
 * @returns The angle in degrees.
 */
function getMbrAngle(mbr) {
  const sorted = mbr.slice();
  sorted.sort(leftFirst);
  const left = sorted.slice(0, 2);
  const right = sorted.slice(2, 4);
  left.sort(topFirst);
  right.sort(topFirst);
  const topLeft = left[0];
  const topRight = right[0];
  return -toDegrees(getAngle(topLeft, topRight));
}

/**
 * Get the four corners of the minimum bounding rectangle from a set of points defining a simple convex polygon.
 * @see {@link https://www.researchgate.net/profile/Lennert_Den_Boer2/publication/303783472_A_Fast_Algorithm_for_Generating_a_Minimal_Bounding_Rectangle/links/5751a14108ae6807fafb2aa5.pdf}
 * @param points - Points from which to compute the MBR.
 * @returns The array of corners.
 */
function getMbrFromPoints(points) {
  if (points.length === 0) {
    return {
      points: [],
      angle: 0,
      width: 0,
      height: 0,
      surface: 0,
      perimeter: 0,
      aspectRatio: 0
    };
  }
  if (points.length === 1) {
    return {
      points: [points[0], points[0], points[0], points[0]],
      perimeter: 0,
      surface: 0,
      angle: 0,
      width: 0,
      height: 0,
      aspectRatio: 1
    };
  }
  let rotatedVertices = [];
  let minSurface = Number.POSITIVE_INFINITY;
  let minSurfaceAngle = 0;
  let mbr = [];
  for (let i = 0; i < points.length; i++) {
    const angle = getAngle(points[i], points[(i + 1) % points.length]);
    rotatedVertices = rotate$1(-angle, points);
    // Rotate and translate so that this segment is at the bottom.
    const aX = rotatedVertices[i].column;
    const aY = rotatedVertices[i].row;
    const bX = rotatedVertices[(i + 1) % rotatedVertices.length].column;
    const bY = rotatedVertices[(i + 1) % rotatedVertices.length].row;
    let tUndefined = true;
    let tMin = 0;
    let tMax = 0;
    let maxWidth = 0;
    for (const point of rotatedVertices) {
      const cX = point.column;
      const cY = point.row;
      const t = (cX - aX) / (bX - aX);
      if (tUndefined) {
        tUndefined = false;
        tMin = t;
        tMax = t;
      } else {
        if (t < tMin) tMin = t;
        if (t > tMax) tMax = t;
      }
      const width = (-(bX - aX) * cY + bX * aY - bY * aX) / (bX - aX);
      if (Math.abs(width) > Math.abs(maxWidth)) {
        maxWidth = width;
      }
    }
    const minPoint = {
      column: aX + tMin * (bX - aX),
      row: aY
    };
    const maxPoint = {
      column: aX + tMax * (bX - aX),
      row: aY
    };
    const currentSurface = Math.abs(maxWidth * (tMin - tMax) * (bX - aX));
    if (currentSurface < minSurface) {
      minSurfaceAngle = angle;
      minSurface = currentSurface;
      mbr = [maxPoint, minPoint, {
        column: minPoint.column,
        row: minPoint.row - maxWidth
      }, {
        column: maxPoint.column,
        row: maxPoint.row - maxWidth
      }];
    }
  }
  const mbrRotated = rotate$1(minSurfaceAngle, mbr);
  const sides = [Math.hypot(mbr[0].column - mbr[1].column, mbr[0].row - mbr[1].row), Math.hypot(mbr[0].column - mbr[3].column, mbr[0].row - mbr[3].row)];
  const maxSide = Math.max(...sides);
  const minSide = Math.min(...sides);
  const mbrAngle = getMbrAngle(mbrRotated);
  const ratio = minSide / maxSide;
  return {
    points: mbrRotated,
    surface: minSurface,
    angle: mbrAngle,
    width: maxSide,
    height: minSide,
    perimeter: 2 * maxSide + 2 * minSide,
    aspectRatio: ratio
  };
}

/**
 * Get the four corners of the minimum bounding rectangle of an ROI.
 * @param mask - The ROI to process.
 * @returns The array of corners.
 */
function getMbr(mask) {
  const vertices = monotoneChainConvexHull(getExtendedBorderPoints(mask));
  return getMbrFromPoints(vertices);
}

/**
 * Checks the that the dimensions of the kernel are odd.
 * @param kernel - Kernel passed to a morphology function.
 */
function checkKernel(kernel) {
  if (kernel.length % 2 === 0 || kernel[0].length % 2 === 0) {
    throw new TypeError('the number of rows and columns of the kernel must be odd');
  }
}

/**
 * Erosion is one of two fundamental operations (with dilatation) in morphological
 * Image processing from which all other morphological operations are based (from Wikipedia).
 * Replaces each value with it's local minimum among the pixels with a kernel value of 1.
 * @see {@link http://docs.opencv.org/2.4/doc/tutorials/imgproc/erosion_dilatation/erosion_dilatation.html}
 * @see {@link https://en.wikipedia.org/wiki/Erosion_(morphology)}
 * @param image - The image to erode.
 * @param options - Erode options.
 * @returns - The eroded image.
 */
function erode(image, options = {}) {
  let defaultKernel = false;
  if (options.kernel === undefined) {
    defaultKernel = true;
  }
  const {
    kernel = [[1, 1, 1], [1, 1, 1], [1, 1, 1]],
    iterations = 1
  } = options;
  if (image instanceof Image) {
    checkProcessable$1(image, {
      bitDepth: [1, 8, 16],
      components: 1,
      alpha: false
    });
  }
  checkKernel(kernel);
  let onlyOnes = true;
  if (!defaultKernel) {
    outer: for (const row of kernel) {
      for (const bit of row) {
        if (bit !== 1) {
          onlyOnes = false;
          break outer;
        }
      }
    }
  }
  let result = image;
  for (let i = 0; i < iterations; i++) {
    if (result instanceof Mask) {
      if (onlyOnes) {
        const newImage = result.clone();
        result = erodeMaskOnlyOnes(result, newImage, kernel[0].length, kernel.length);
      } else {
        const newImage = Mask.createFrom(image);
        result = erodeMask(result, newImage, kernel);
      }
    } else if (onlyOnes) {
      const newImage = Image.createFrom(image);
      result = erodeGreyOnlyOnes(result, newImage, kernel[0].length, kernel.length);
    } else {
      const newImage = Image.createFrom(image);
      result = erodeGrey(result, newImage, kernel);
    }
  }
  return result;
}
function erodeGrey(img, newImage, kernel) {
  const kernelWidth = kernel[0].length;
  const kernelHeight = kernel.length;
  const radiusX = (kernelWidth - 1) / 2;
  const radiusY = (kernelHeight - 1) / 2;
  for (let row = 0; row < img.height; row++) {
    for (let column = 0; column < img.width; column++) {
      let min = img.maxValue;
      for (let kernelRow = 0; kernelRow < kernelHeight; kernelRow++) {
        for (let kernelColumn = 0; kernelColumn < kernelWidth; kernelColumn++) {
          if (kernel[kernelRow][kernelColumn] !== 1) continue;
          const currentColumn = kernelColumn - radiusX + column;
          const currentRow = kernelRow - radiusY + row;
          if (currentColumn < 0 || currentRow < 0 || currentColumn >= img.width || currentRow >= img.height) {
            continue;
          }
          const value = img.getValue(currentColumn, currentRow, 0);
          if (value < min) min = value;
        }
      }
      newImage.setValue(column, row, 0, min);
    }
  }
  return newImage;
}
function erodeGreyOnlyOnes(image, newImage, kernelWidth, kernelHeight) {
  const radiusX = (kernelWidth - 1) / 2;
  const radiusY = (kernelHeight - 1) / 2;
  const minList = [];
  for (let column = 0; column < image.width; column++) {
    minList.push(0);
  }
  for (let row = 0; row < image.height; row++) {
    for (let column = 0; column < image.width; column++) {
      let min = image.maxValue;
      for (let h = Math.max(0, row - radiusY); h < Math.min(image.height, row + radiusY + 1); h++) {
        const value = image.getValue(column, h, 0);
        if (value < min) {
          min = value;
        }
      }
      minList[column] = min;
    }
    for (let column = 0; column < image.width; column++) {
      let min = image.maxValue;
      for (let i = Math.max(0, column - radiusX); i < Math.min(image.width, column + radiusX + 1); i++) {
        if (minList[i] < min) {
          min = minList[i];
        }
      }
      newImage.setValue(column, row, 0, min);
    }
  }
  return newImage;
}
function erodeMask(mask, newMask, kernel) {
  const kernelWidth = kernel[0].length;
  const kernelHeight = kernel.length;
  const radiusX = (kernelWidth - 1) / 2;
  const radiusY = (kernelHeight - 1) / 2;
  for (let row = 0; row < mask.height; row++) {
    for (let column = 0; column < mask.width; column++) {
      let min = 1;
      for (let kernelRow = 0; kernelRow < kernelHeight; kernelRow++) {
        for (let kernelColumn = 0; kernelColumn < kernelWidth; kernelColumn++) {
          if (kernel[kernelRow][kernelColumn] !== 1) continue;
          const currentColumn = kernelColumn - radiusX + column;
          const currentRow = kernelRow - radiusY + row;
          if (currentRow < 0 || currentColumn < 0 || currentColumn >= mask.width || currentRow >= mask.height) {
            continue;
          }
          const value = mask.getBit(currentColumn, currentRow);
          if (value === 0) {
            min = 0;
            break;
          }
        }
      }
      if (min === 1) {
        newMask.setBit(column, row, 1);
      }
    }
  }
  return newMask;
}
function erodeMaskOnlyOnes(mask, newMask, kernelWidth, kernelHeight) {
  const radiusX = (kernelWidth - 1) / 2;
  const radiusY = (kernelHeight - 1) / 2;
  const minList = [];
  for (let column = 0; column < mask.width; column++) {
    minList.push(0);
  }
  for (let row = 0; row < mask.height; row++) {
    for (let column = 0; column < mask.width; column++) {
      minList[column] = 1;
      for (let h = Math.max(0, row - radiusY); h < Math.min(mask.height, row + radiusY + 1); h++) {
        if (mask.getBit(column, h) === 0) {
          minList[column] = 0;
          break;
        }
      }
    }
    for (let column = 0; column < mask.width; column++) {
      if (newMask.getBit(column, row) === 0) continue;
      for (let i = Math.max(0, column - radiusX); i < Math.min(mask.width, column + radiusX + 1); i++) {
        if (minList[i] === 0) {
          newMask.setBit(column, row, 0);
          break;
        }
      }
    }
  }
  return newMask;
}

/**
 * Dilatation is one of two fundamental operations (with erosion) in morphological
 * image processing from which all other morphological operations are based (from Wikipedia).
 * Replaces each value with it's local maximum among the pixels with a kernel value of 1.
 * @see {@link http://docs.opencv.org/2.4/doc/tutorials/imgproc/erosion_dilatation/erosion_dilatation.html}
 * @see {@link https://en.wikipedia.org/wiki/Dilation_(morphology)}
 * @param image - Image to dilate.
 * @param options - Dilate options.
 * @returns Dilated image.
 */
function dilate(image, options = {}) {
  let defaultKernel = false;
  if (options.kernel === undefined) {
    defaultKernel = true;
  }
  const {
    kernel = [[1, 1, 1], [1, 1, 1], [1, 1, 1]],
    iterations = 1
  } = options;
  if (image instanceof Image) {
    checkProcessable$1(image, {
      bitDepth: [1, 8, 16],
      components: 1,
      alpha: false
    });
  }
  checkKernel(kernel);
  let onlyOnes = true;
  if (!defaultKernel) {
    outer: for (const row of kernel) {
      for (const value of row) {
        if (value !== 1) {
          onlyOnes = false;
          break outer;
        }
      }
    }
  }
  let result = image;
  for (let i = 0; i < iterations; i++) {
    if (result instanceof Mask) {
      if (onlyOnes) {
        const newMask = result.clone();
        result = dilatMaskOnlyOnes(result, newMask, kernel[0].length, kernel.length);
      } else {
        const newMask = Mask.createFrom(result);
        result = dilateMask(result, newMask, kernel);
      }
    } else if (onlyOnes) {
      const newImage = Image.createFrom(result);
      result = dilateGreyOnlyOnes(result, newImage, kernel[0].length, kernel.length);
    } else {
      const newImage = Image.createFrom(result);
      result = dilateGrey(result, newImage, kernel);
    }
  }
  return result;
}
function dilateGrey(image, newImage, kernel) {
  const kernelWidth = kernel[0].length;
  const kernelHeight = kernel.length;
  const radiusX = (kernelWidth - 1) / 2;
  const radiusY = (kernelHeight - 1) / 2;
  for (let row = 0; row < image.height; row++) {
    for (let column = 0; column < image.width; column++) {
      let max = 0;
      for (let kernelRow = 0; kernelRow < kernelHeight; kernelRow++) {
        for (let kernelColumn = 0; kernelColumn < kernelWidth; kernelColumn++) {
          if (kernel[kernelRow][kernelColumn] !== 1) continue;
          const currentColumn = kernelColumn - radiusX + column;
          const currentRow = kernelRow - radiusY + row;
          if (currentColumn < 0 || currentRow < 0 || currentColumn >= image.width || currentRow >= image.height) {
            continue;
          }
          const value = image.getValue(currentColumn, currentRow, 0);
          if (value > max) max = value;
        }
      }
      newImage.setValue(column, row, 0, max);
    }
  }
  return newImage;
}
function dilateGreyOnlyOnes(image, newImage, kernelWidth, kernelHeight) {
  const radiusX = (kernelWidth - 1) / 2;
  const radiusY = (kernelHeight - 1) / 2;
  const maxList = [];
  for (let column = 0; column < image.width; column++) {
    maxList.push(0);
  }
  for (let row = 0; row < image.height; row++) {
    for (let column = 0; column < image.width; column++) {
      let max = 0;
      for (let h = Math.max(0, row - radiusY); h < Math.min(image.height, row + radiusY + 1); h++) {
        const value = image.getValue(column, h, 0);
        if (value > max) {
          max = value;
        }
      }
      maxList[column] = max;
    }
    for (let column = 0; column < image.width; column++) {
      let max = 0;
      for (let i = Math.max(0, column - radiusX); i < Math.min(image.width, column + radiusX + 1); i++) {
        if (maxList[i] > max) {
          max = maxList[i];
        }
      }
      newImage.setValue(column, row, 0, max);
    }
  }
  return newImage;
}
function dilateMask(mask, newMask, kernel) {
  const kernelWidth = kernel[0].length;
  const kernelHeight = kernel.length;
  const radiusX = (kernelWidth - 1) / 2;
  const radiusY = (kernelHeight - 1) / 2;
  for (let row = 0; row < mask.height; row++) {
    for (let column = 0; column < mask.width; column++) {
      let max = 0;
      for (let kernelRow = 0; kernelRow < kernelHeight; kernelRow++) {
        for (let kernelColumn = 0; kernelColumn < kernelWidth; kernelColumn++) {
          if (kernel[kernelRow][kernelColumn] !== 1) continue;
          const currentColumn = kernelColumn - radiusX + column;
          const currentRow = kernelRow - radiusY + row;
          if (currentRow < 0 || currentColumn < 0 || currentColumn >= mask.width || currentRow >= mask.height) {
            continue;
          }
          const value = mask.getBit(currentColumn, currentRow);
          if (value === 1) {
            max = 1;
            break;
          }
        }
      }
      if (max === 1) {
        newMask.setBit(column, row, 1);
      }
    }
  }
  return newMask;
}
function dilatMaskOnlyOnes(mask, newMask, kernelWidth, kernelHeight) {
  const radiusX = (kernelWidth - 1) / 2;
  const radiusY = (kernelHeight - 1) / 2;
  const maxList = [];
  for (let column = 0; column < mask.width; column++) {
    maxList.push(1);
  }
  for (let row = 0; row < mask.height; row++) {
    for (let column = 0; column < mask.width; column++) {
      maxList[column] = 0;
      for (let h = Math.max(0, row - radiusY); h < Math.min(mask.height, row + radiusY + 1); h++) {
        if (mask.getBit(column, h) === 1) {
          maxList[column] = 1;
          break;
        }
      }
    }
    for (let column = 0; column < mask.width; column++) {
      if (newMask.getBit(column, row) === 1) continue;
      for (let i = Math.max(0, column - radiusX); i < Math.min(mask.width, column + radiusX + 1); i++) {
        if (maxList[i] === 1) {
          newMask.setBit(column, row, 1);
          break;
        }
      }
    }
  }
  return newMask;
}

/**
 * In mathematical morphology, opening is the dilation of the erosion of a set A by a structuring element B.
 * Together with closing, the opening serves in computer vision and image processing as a basic workhorse of morphological noise removal.
 * Opening removes small objects from the foreground (usually taken as the bright pixels) of an image,
 * placing them in the background, while closing removes small holes in the foreground, changing small islands of background into foreground. (Wikipedia)
 * @see {@link http://docs.opencv.org/2.4/doc/tutorials/imgproc/opening_closing_hats/opening_closing_hats.html}
 * @param image - Image to process.
 * @param options - Open options.
 * @returns The opened image.
 */
function open(image, options = {}) {
  const {
    kernel = [[1, 1, 1], [1, 1, 1], [1, 1, 1]],
    iterations = 1
  } = options;
  if (image instanceof Image) {
    checkProcessable$1(image, {
      bitDepth: [1, 8, 16],
      components: 1,
      alpha: false
    });
  }
  checkKernel(kernel);
  let newImage = image;
  for (let i = 0; i < iterations; i++) {
    newImage = newImage.erode({
      kernel
    });
    newImage = newImage.dilate({
      kernel
    });
  }
  return newImage;
}

/**
 * In mathematical morphology, the closing of a set A by a structuring element B is the erosion of the dilation of that set (Wikipedia).
 * In image processing, closing is, together with opening, the basic workhorse of morphological noise removal.
 * Opening removes small objects, while closing removes small holes.
 * @see {@link http://docs.opencv.org/2.4/doc/tutorials/imgproc/opening_closing_hats/opening_closing_hats.html}
 * @param image - Image to process.
 * @param options - Close options.
 * @returns Closed image.
 */
function close(image, options = {}) {
  const {
    kernel = [[1, 1, 1], [1, 1, 1], [1, 1, 1]],
    iterations = 1
  } = options;
  if (image instanceof Image) {
    checkProcessable$1(image, {
      bitDepth: [1, 8, 16],
      components: 1,
      alpha: false
    });
  }
  checkKernel(kernel);
  let newImage = image;
  for (let i = 0; i < iterations; i++) {
    newImage = newImage.dilate({
      kernel
    }).erode({
      kernel
    });
  }
  return newImage;
}

/**
 * This function is the white top hat (also called top hat). In mathematical morphology and digital image processing,
 * top-hat transform is an operation that extracts small elements and details from given images.
 * The white top-hat transform is defined as the difference between the input image and its opening by some structuring element.
 * Top-hat transforms are used for various image processing tasks, such as feature extraction, background equalization, image enhancement, and others. (Wikipedia)
 * @see {@link http://docs.opencv.org/2.4/doc/tutorials/imgproc/opening_closing_hats/opening_closing_hats.html}
 * @param image - Image to process.
 * @param options - Top hat options.
 * @returns The top-hatted image.
 */
function topHat(image, options = {}) {
  const {
    kernel = [[1, 1, 1], [1, 1, 1], [1, 1, 1]],
    iterations = 1
  } = options;
  if (image instanceof Image) {
    checkProcessable$1(image, {
      bitDepth: [1, 8, 16],
      components: 1,
      alpha: false
    });
  }
  checkKernel(kernel);
  let newImage = image;
  for (let i = 0; i < iterations; i++) {
    const openImage = newImage.open({
      kernel
    });
    newImage = subtract(openImage, newImage, {
      absolute: true
    });
  }
  return newImage;
}

/**
 * This function is the black top hat (also called bottom hat).
 * In mathematical morphology and digital image processing,
 * top-hat transform is an operation that extracts small elements and details from given images.
 * The black top-hat transform is defined dually as the difference between the closed and the input image.
 * Top-hat transforms are used for various image processing tasks, such as feature extraction, background equalization,
 * image enhancement, and others. (Wikipedia)
 * @see {@link http://docs.opencv.org/2.4/doc/tutorials/imgproc/opening_closing_hats/opening_closing_hats.html}
 * @param image - Image to process.
 * @param options - Bottom hat options.
 * @returns The bottom-hatted image.
 */
function bottomHat(image, options = {}) {
  const {
    kernel = [[1, 1, 1], [1, 1, 1], [1, 1, 1]],
    iterations = 1
  } = options;
  if (image instanceof Image) {
    checkProcessable$1(image, {
      bitDepth: [1, 8, 16],
      components: 1,
      alpha: false
    });
  }
  checkKernel(kernel);
  let newImage = image;
  for (let i = 0; i < iterations; i++) {
    const openImage = newImage.close({
      kernel
    });
    newImage = subtract(openImage, newImage, {
      absolute: true
    });
  }
  return newImage;
}

/**
 * In mathematical morphology and digital image processing, a morphological gradient is the difference between the dilation and the erosion of a given image. It is an image where each pixel value (typically non-negative) indicates the contrast intensity in the close neighborhood of that pixel. It is useful for edge detection and segmentation applications.
 * @see {@link http://docs.opencv.org/2.4/doc/tutorials/imgproc/opening_closing_hats/opening_closing_hats.html}
 * @param image - Image to process.
 * @param options - Morphological gradient hat options.
 * @returns The processed image.
 */
function morphologicalGradient(image, options = {}) {
  const {
    kernel = [[1, 1, 1], [1, 1, 1], [1, 1, 1]],
    iterations = 1
  } = options;
  if (image instanceof Image) {
    checkProcessable$1(image, {
      bitDepth: [1, 8, 16],
      components: 1,
      alpha: false
    });
  }
  checkKernel(kernel);
  let newImage = image;
  for (let i = 0; i < iterations; i++) {
    const dilatedImage = newImage.dilate({
      kernel
    });
    const erodedImage = newImage.erode({
      kernel
    });
    newImage = subtract(dilatedImage, erodedImage, {
      absolute: true
    });
  }
  return newImage;
}

/**
 * Create function that allows to iterate on the pixels of the border of an image.
 * @param image - Image for which to create the border iterator.
 * @yields - Index of the border pixel.
 */
function* borderIterator(image) {
  for (let col = 0; col < image.width; col++) {
    yield col;
  }
  for (let row = 2; row < image.height; row++) {
    yield row * image.width - 1;
  }
  for (let col = 0; col < image.width; col++) {
    yield image.width * image.height - col - 1;
  }
  for (let row = image.height - 2; row >= 1; row--) {
    yield row * image.width;
  }
}

const MAX_ARRAY = 65536; // 65536 should be enough for most of the cases
const toProcess = new Uint32Array(MAX_ARRAY);
/**
 * Set the pixels connected to the border of the mask to zero. You can chose to allow corner connection of not with the `allowCorners` option.
 * @param mask - The mask to process.
 * @param options - Clear border options.
 * @returns The image with cleared borders.
 */
function multipleFloodFill(mask, options = {}) {
  const {
    startPixels = [0],
    startPixelValue = 0,
    newPixelValue = 1,
    allowCorners = false
  } = options;
  const newMask = maskToOutputMask(mask, options, {
    clone: true
  });
  const alreadyConsidered = Mask.createFrom(mask);
  let from = 0;
  let to = 0;
  // const startPixelValue = mask.getBitByIndex(startPixels[0]);
  // find relevant border pixels
  for (const pixelIndex of startPixels) {
    if (newMask.getBitByIndex(pixelIndex) === startPixelValue) {
      toProcess[to++ % MAX_ARRAY] = pixelIndex;
      alreadyConsidered.setBitByIndex(pixelIndex, 1);
      newMask.setBitByIndex(pixelIndex, newPixelValue);
    }
  }
  // find pixels connected to the border pixels
  while (from < to) {
    assert(to - from <= MAX_ARRAY);
    const currentPixel = toProcess[from++ % MAX_ARRAY];
    newMask.setBitByIndex(currentPixel, newPixelValue);
    // check if pixel is on a border
    const topBorder = currentPixel < mask.width;
    const leftBorder = currentPixel % mask.width === 0;
    const rightBorder = currentPixel % mask.width === mask.width - 1;
    const bottomBorder = currentPixel > mask.size - mask.width;
    // check neighbors
    if (!bottomBorder) {
      const bottom = currentPixel + mask.width;
      addToProcess(bottom);
    }
    if (!leftBorder) {
      const left = currentPixel - 1;
      addToProcess(left);
    }
    if (!topBorder) {
      const top = currentPixel - mask.width;
      addToProcess(top);
    }
    if (!rightBorder) {
      const right = currentPixel + 1;
      addToProcess(right);
    }
    if (allowCorners) {
      if (!topBorder) {
        if (!leftBorder) {
          const topLeft = currentPixel - mask.width - 1;
          addToProcess(topLeft);
        }
        if (!rightBorder) {
          const topRight = currentPixel - mask.width + 1;
          addToProcess(topRight);
        }
      }
      if (!bottomBorder) {
        if (!leftBorder) {
          const bottomLeft = currentPixel + mask.width - 1;
          addToProcess(bottomLeft);
        }
        if (!rightBorder) {
          const bottomRight = currentPixel + mask.width + 1;
          addToProcess(bottomRight);
        }
      }
    }
  }
  function addToProcess(pixel) {
    if (alreadyConsidered.getBitByIndex(pixel)) return;
    if (newMask.getBitByIndex(pixel) === startPixelValue) {
      toProcess[to++ % MAX_ARRAY] = pixel;
      alreadyConsidered.setBitByIndex(pixel, 1);
    }
  }
  return newMask;
}

/**
 * Set the pixels connected to the border of the mask to zero. You can chose to allow corner connection of not with the `allowCorners` option.
 * @param mask - The mask to process.
 * @param options - Clear border options.
 * @returns The image with cleared borders.
 */
function clearBorder(mask, options = {}) {
  const {
    allowCorners = false,
    out,
    color = 'white'
  } = options;
  return multipleFloodFill(mask, {
    startPixels: borderIterator(mask),
    startPixelValue: color === 'white' ? 1 : 0,
    newPixelValue: color === 'white' ? 0 : 1,
    allowCorners,
    out
  });
}

const kernelX = [[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]];
const kernelY = [[-1, -2, -1], [0, 0, 0], [1, 2, 1]];
/**
 * Apply Canny edge detection to an image.
 * @param image - Image to process.
 * @param options - Canny edge detection options.
 * @returns The processed image.
 */
function cannyEdgeDetector(image, options = {}) {
  const {
    hysteresis = true,
    lowThreshold = 0.04,
    highThreshold = 0.1,
    gaussianBlurOptions = {
      sigma: 1
    }
  } = options;
  const minValue = lowThreshold * image.maxValue;
  const maxValue = highThreshold * image.maxValue;
  checkProcessable$1(image, {
    colorModel: 'GREY'
  });
  const width = image.width;
  const height = image.height;
  const blurred = image.gaussianBlur(gaussianBlurOptions);
  const gradientX = blurred.rawDirectConvolution(kernelY);
  const gradientY = blurred.rawDirectConvolution(kernelX);
  const gradient = new Float64Array(image.size);
  for (let i = 0; i < image.size; i++) {
    gradient[i] = Math.hypot(gradientX[i], gradientY[i]);
  }
  const nonMaxSuppression = new Float64Array(image.size);
  const edges = new Float64Array(image.size);
  const finalImage = imageToOutputMask(image, options);
  // Non-Maximum suppression
  for (let column = 1; column < width - 1; column++) {
    for (let row = 1; row < height - 1; row++) {
      const currentGradientX = gradientX[getIndex(column, row, image, 0)];
      const currentGradientY = gradientY[getIndex(column, row, image, 0)];
      const direction = getDirection(currentGradientX, currentGradientY);
      const currentGradient = gradient[getIndex(column, row, image, 0)];
      if (
      // horizontal
      direction === 0 && currentGradient >= gradient[getIndex(column, row - 1, image, 0)] && currentGradient >= gradient[getIndex(column, row + 1, image, 0)] ||
      // upward slope
      direction === 1 && currentGradient >= gradient[getIndex(column - 1, row - 1, image, 0)] && currentGradient >= gradient[getIndex(column + 1, row + 1, image, 0)] ||
      // vertical
      direction === 2 && currentGradient >= gradient[getIndex(column - 1, row, image, 0)] && currentGradient >= gradient[getIndex(column + 1, row, image, 0)] ||
      // downward slope
      direction === 3 && currentGradient >= gradient[getIndex(column - 1, row + 1, image, 0)] && currentGradient >= gradient[getIndex(column + 1, row - 1, image, 0)]) {
        // pixels to remove from the final image
        nonMaxSuppression[getIndex(column, row, image, 0)] = currentGradient;
      }
    }
  }
  for (let i = 0; i < width * height; ++i) {
    const currentNms = nonMaxSuppression[i];
    let currentEdge = 0;
    if (currentNms > maxValue) {
      currentEdge++;
      finalImage.setBitByIndex(i, 1);
    }
    if (currentNms > minValue) {
      currentEdge++;
    }
    edges[i] = currentEdge;
  }
  // Hysteresis: first pass
  if (hysteresis) {
    let currentPixels = [];
    for (let column = 1; column < width - 1; ++column) {
      for (let row = 1; row < height - 1; ++row) {
        if (edges[getIndex(column, row, image, 0)] !== 1) {
          continue;
        }
        outer: for (let hystColumn = column - 1; hystColumn < column + 2; ++hystColumn) {
          for (let hystRow = row - 1; hystRow < row + 2; ++hystRow) {
            if (edges[getIndex(hystColumn, hystRow, image, 0)] === 2) {
              currentPixels.push([column, row]);
              finalImage.setValue(column, row, 0, 1);
              break outer;
            }
          }
        }
      }
    }
    // Hysteresis: second pass
    while (currentPixels.length > 0) {
      const newPixels = [];
      for (const currentPixel of currentPixels) {
        for (let j = -1; j < 2; ++j) {
          for (let k = -1; k < 2; ++k) {
            if (j === 0 && k === 0) {
              continue;
            }
            const row = currentPixel[0] + j;
            const column = currentPixel[1] + k;
            if (
            // there could be an error here
            edges[getIndex(column, row, image, 0)] === 1 && finalImage.getValue(column, row, 0) === 0) {
              newPixels.push([row, column]);
              finalImage.setValue(column, row, 0, 1);
            }
          }
        }
      }
      currentPixels = newPixels;
    }
  }
  return finalImage;
  /* Function for debug
  import { Matrix } from 'ml-matrix';
     function printArray(array: Float64Array): void {
    // @ts-expect-error: only for debug
    const matrix = Matrix.from1DArray(height, width, array);
    console.log(matrix);
  }
  */
}
/**
 * Return a 0 to 3 value indicating the four main directions (horizontal, upward diagonal, vertical, downward diagonal).
 * @param x - The x coordinate.
 * @param y - The y coordinate.
 * @returns The direction as a 0 to 4 value.
 */
function getDirection(x, y) {
  return (Math.round(Math.atan2(y, x) * (4 / Math.PI)) + 4) % 4;
}

/**
 * Apply a flood fill algorithm to an image.
 * @param mask - Mask to process.
 * @param options - Flood fill options.
 * @returns The filled mask.
 */
function floodFill(mask, options = {}) {
  const {
    origin = {
      row: 0,
      column: 0
    },
    allowCorners = false,
    out
  } = options;
  const startPixel = getIndex(origin.column, origin.row, mask);
  return multipleFloodFill(mask, {
    startPixels: [startPixel],
    allowCorners,
    out
  });
}

/**
 * Fill holes in regions of interest.
 * @param mask - Mask to process.
 * @param options - Flood fill options.
 * @returns The filled mask.
 */
function solidFill(mask, options = {}) {
  const {
    allowCorners = false
  } = options;
  const newImage = maskToOutputMask(mask, options, {
    clone: true
  });
  const inverted = mask.invert();
  const cleared = inverted.clearBorder({
    allowCorners
  });
  return newImage.or(cleared, {
    out: newImage
  });
}

/**
 * Converts a bit value to the corresponding number.
 * @param value - The bit to convert.
 * @returns The bit value as a number.
 */
function boolToNumber(value) {
  let result;
  if (typeof value === 'boolean') {
    result = value ? 1 : 0;
  } else {
    result = value;
  }
  return result;
}

class Mask {
  /**
   * The number of columns of the mask.
   */
  width;
  /**
   * The number of rows of the mask.
   */
  height;
  /**
   * The total number of bits in the mask (width × height).
   */
  size;
  /**
   * The number of bits per value in each channel (always 1).
   */
  bitDepth;
  /**
   * The color model of the mask (always BINARY).
   */
  colorModel;
  /**
   * The number of color channels in the image, excluding the alpha channel (always 1).
   */
  components;
  /**
   * The number of channels in the mask, including the alpha channel (always 1).
   */
  channels;
  /**
   * Specifying that the mask has no an alpha channel.
   */
  alpha;
  /**
   * The maximum value that a pixel channel can have.
   */
  maxValue;
  /**
   * Origin of the image relative to a the parent image.
   */
  origin;
  /**
   * Typed array holding the mask data.
   */
  data;
  /**
   * Construct a new Mask knowing its dimensions.
   * @param width - Image width.
   * @param height - Image height.
   * @param options - Image options.
   */
  constructor(width, height, options = {}) {
    const {
      data,
      origin = {
        row: 0,
        column: 0
      }
    } = options;
    if (width < 1 || !Number.isInteger(width)) {
      throw new RangeError(`width must be an integer and at least 1. Received ${width}`);
    }
    if (height < 1 || !Number.isInteger(height)) {
      throw new RangeError(`height must be an integer and at least 1. Received ${height}`);
    }
    this.width = width;
    this.height = height;
    this.size = width * height;
    this.bitDepth = 1;
    this.colorModel = 'BINARY';
    this.origin = origin;
    const colorModelDef = colorModels[this.colorModel];
    this.components = colorModelDef.components;
    this.alpha = colorModelDef.alpha;
    this.channels = colorModelDef.channels;
    this.maxValue = 1;
    if (data === undefined) {
      this.data = new Uint8Array(this.size);
    } else {
      const expectedLength = this.size * this.channels;
      if (data.length !== expectedLength) {
        throw new RangeError(`incorrect data size: ${data.length}. Expected ${expectedLength}`);
      }
      this.data = data;
    }
  }
  /**
   * Create a new Mask based on the properties of an existing one.
   * @param other - Reference Mask.
   * @param options - Mask options.
   * @returns New mask.
   */
  static createFrom(other, options = {}) {
    const {
      width = other.width,
      height = other.height,
      origin = other.origin
    } = options;
    return new Mask(width, height, {
      origin,
      ...options
    });
  }
  /**
   * Get a pixel of the mask.
   * @param column - Column index.
   * @param row - Row index.
   * @returns The pixel.
   */
  getPixel(column, row) {
    const result = [];
    const index = row * this.width + column;
    result.push(this.data[index]);
    return result;
  }
  /**
   * Set a pixel.
   * @param column - Column index.
   * @param row - Row index.
   * @param value - The pixel value.
   */
  setPixel(column, row, value) {
    const index = row * this.width + column;
    this.data[index] = value[0];
  }
  /**
   * Set a pixel to a given value if the coordinates are inside the mask.
   * @param column - Column index.
   * @param row - Row index.
   * @param value - New color of the pixel to set.
   */
  setVisiblePixel(column, row, value) {
    if (column >= 0 && column < this.width && row >= 0 && row < this.height) {
      this.setPixel(column, row, value);
    }
  }
  /**
   * Get a pixel using its index.
   * @param index - Index of the pixel.
   * @returns The pixel.
   */
  getPixelByIndex(index) {
    return [this.data[index]];
  }
  /**
   * Set a pixel using its index.
   * @param index - Index of the pixel.
   * @param value - New value of the pixel to set.
   */
  setPixelByIndex(index, value) {
    this.data[index] = value[0];
  }
  /**
   * Create a mask from an array of points.
   * @param width - Width of the mask.
   * @param height - Height of the mask.
   * @param points - Reference Mask.
   * @returns New mask.
   */
  static fromPoints(width, height, points) {
    const mask = new Mask(width, height);
    for (const point of points) {
      mask.setBit(point.column, point.row, 1);
    }
    return mask;
  }
  /**
   * Create a copy of this mask.
   * @returns The mask clone.
   */
  clone() {
    return Mask.createFrom(this, {
      data: this.data.slice()
    });
  }
  /**
   * Get the value of a bit.
   * @param column - Column index.
   * @param row - Row index.
   * @returns The bit value.
   */
  getBit(column, row) {
    const index = row * this.width + column;
    return this.data[index];
  }
  /**
   * Set the value of a bit.
   * @param column - Column index.
   * @param row - Row index.
   * @param value - New bit value.
   */
  setBit(column, row, value) {
    const index = row * this.width + column;
    // @ts-expect-error: we know that value is a boolean
    this.data[index] = value;
  }
  /**
   * Get the value of a bit using index.
   * @param index - Index of the pixel.
   * @returns Value of the bit.
   */
  getBitByIndex(index) {
    return this.data[index * this.channels];
  }
  /**
   * Set the value of a bit using index.
   * @param index - Index of the pixel.
   * @param value - Value to set.
   */
  setBitByIndex(index, value) {
    this.data[index * this.channels] = boolToNumber(value);
  }
  /**
   * Get the number of pixels that do not have the value 0.
   * @returns The number of non-zero pixels.
   */
  getNbNonZeroPixels() {
    let count = 0;
    for (const datum of this.data) {
      if (datum) {
        count++;
      }
    }
    return count;
  }
  /**
   * Get the value of a bit. Function exists for compatibility with Image.
   * @param column - Column index.
   * @param row - Row index.
   * @param channel - Index of the channel, must be zero.
   * @returns The bit value.
   */
  getValue(column, row, channel) {
    checkChannel(channel);
    return this.getBit(column, row);
  }
  /**
   * Set the value of a bit. Function exists for compatibility with Image.
   * @param column - Column index.
   * @param row - Row index.
   * @param channel - Index of the channel, must be zero.
   * @param value - New bit value.
   */
  setValue(column, row, channel, value) {
    checkChannel(channel);
    this.setBit(column, row, value);
  }
  /**
   * Get the value of a bit using index. Function exists for compatibility with Image.
   * @param index - Index of the pixel.
   * @param channel - Index of the channel, must be zero.
   * @returns Value of the bit.
   */
  getValueByIndex(index, channel) {
    checkChannel(channel);
    return this.getBitByIndex(index);
  }
  /**
   * Set the value of a bit using index. Function exists for compatibility with Image.
   * @param index - Index of the pixel.
   * @param channel - Index of the channel, must be zero.
   * @param value - Value to set.
   */
  setValueByIndex(index, channel, value) {
    checkChannel(channel);
    this.setBitByIndex(index, value);
  }
  /**
   * Get the value of a specific bit. Select bit using a point.
   * @param point - Coordinates of the desired biz.
   * @returns Value of the bit.
   */
  getValueByPoint(point) {
    return this.getValue(point.column, point.row, 0);
  }
  /**
   * Set the value of a specific bit. Select bit using a point.
   * @param point - Coordinates of the bit.
   * @param value - Value to set.
   */
  setValueByPoint(point, value) {
    this.setValue(point.column, point.row, 0, value);
  }
  /**
   * Return the raw mask data.
   * @returns The raw data.
   */
  getRawImage() {
    return {
      width: this.width,
      height: this.height,
      data: this.data
    };
  }
  [Symbol.for('nodejs.util.inspect.custom')]() {
    let dataString;
    if (this.height > 20 || this.width > 20) {
      dataString = '[...]';
    } else {
      dataString = printData$1(this);
    }
    return `Mask {
  width: ${this.width}
  height: ${this.height}
  data: ${dataString}
}`;
  }
  /**
   * Fill the mask with a value.
   * @param value - Value of the bit.
   * @returns The mask instance.
   */
  fill(value) {
    const result = boolToNumber(value);
    this.data.fill(result);
    return this;
  }
  convertColor(colorModel) {
    return convertColor(this, colorModel);
  }
  // FILTERS
  /**
   * Invert the colors of the mask.
   * @param options - Inversion options.
   * @returns The inverted mask.
   */
  invert(options) {
    return invert(this, options);
  }
  /**
   * Subtract other from a mask.
   * @param other - Image to subtract.
   * @param options - Inversion options.
   * @returns The subtracted mask.
   */
  subtract(other, options) {
    return subtract(this, other, options);
  }
  /**
   * Perform an AND operation on two masks.
   * @param other - Second mask.
   * @param options - And options.
   * @returns AND of the two masks.
   */
  and(other, options) {
    return and(this, other, options);
  }
  /**
   * Perform an OR operation on two masks.
   * @param other - Second mask.
   * @param options - And options.
   * @returns OR of the two masks.
   */
  or(other, options) {
    return or(this, other, options);
  }
  // MASK ANALYSIS
  /**
   * Get the coordinates of the points on the border of a shape defined in a mask.
   * @param options - Get border points options.
   * @returns Array of border points.
   */
  getBorderPoints(options) {
    return getBorderPoints$1(this, options);
  }
  /**
   * Returns external contour of the mask. Unlike border points, returned points
   * follow the shape of the mask.
   * @param options - Get external contour options.
   * @returns Array of contour points.
   */
  getExternalContour(options) {
    return getExternalContour$1(this, options);
  }
  /**
   * Get the vertices of the convex Hull polygon of a mask.
   * @returns Array of the vertices of the convex Hull in clockwise order.
   */
  getConvexHull() {
    return getConvexHull(this);
  }
  /**
   * Get the corners of the minimum bounding rectangle of a shape defined in a mask.
   * @returns Array of border points.
   */
  getMbr() {
    return getMbr(this);
  }
  /**
   * Computes the Feret data.
   * @returns The Feret diameters.
   */
  getFeret() {
    return getFeret(this);
  }
  // MORPHOLOGY
  /**
   * Erode a Mask.
   * @param options - Erode options.
   * @returns The eroded mask.
   */
  erode(options) {
    return erode(this, options);
  }
  /**
   * Dilate an image.
   * @param options - Dilate options.
   * @returns The dilated image.
   */
  dilate(options) {
    return dilate(this, options);
  }
  /**
   * Open an image.
   * @param options - Open options.
   * @returns The opened image.
   */
  open(options) {
    return open(this, options);
  }
  /**
   * Close an image.
   * @param options - Close options.
   * @returns The closed image.
   */
  close(options) {
    return close(this, options);
  }
  /**
   * Top hat of an image.
   * @param options - Top hat options.
   * @returns The top-hatted image.
   */
  topHat(options) {
    return topHat(this, options);
  }
  /**
   * Bottom hat of an image.
   * @param options - Bottom hat options.
   * @returns The bottom-hatted image.
   */
  bottomHat(options) {
    return bottomHat(this, options);
  }
  /**
   * Apply morphological gradient to an image.
   * @param options - Morphological gradient options.
   * @returns The processed image.
   */
  morphologicalGradient(options) {
    return morphologicalGradient(this, options);
  }
  /**
   * Remove elements connected to the borders of an image.
   * @param options - Clear border options.
   * @returns The processed image.
   */
  clearBorder(options) {
    return clearBorder(this, options);
  }
  /**
   * Apply flood fill algorithm from a given starting point.
   * @param options - Flood fill options.
   * @returns The filled mask.
   */
  floodFill(options) {
    return floodFill(this, options);
  }
  /**
   * Fill holes in regions of interest.
   * @param options - Flood fill options.
   * @returns The filled mask.
   */
  solidFill(options) {
    return solidFill(this, options);
  }
  // DRAW
  /**
   * Draw a set of points on a mask.
   * @param points - Array of points.
   * @param options - Draw points on Image options.
   * @returns New mask.
   */
  drawPoints(points, options = {}) {
    return drawPoints(this, points, options);
  }
  /**
   * Draw a line defined by two points onto a mask.
   * @param from - Line starting point.
   * @param to - Line ending point.
   * @param options - Draw Line options.
   * @returns The mask with the line drawing.
   */
  drawLine(from, to, options = {}) {
    return drawLineOnMask(this, from, to, options);
  }
  /**
   * Draw a polyline defined by an array of points on a mask.
   * @param points - Polyline array of points.
   * @param options - Draw polyline options.
   * @returns The mask with the polyline drawing.
   */
  drawPolyline(points, options = {}) {
    return drawPolylineOnMask(this, points, options);
  }
  /**
   * Draw a polygon defined by an array of points onto an mask.
   * @param points - Polygon vertices.
   * @param options - Draw Line options.
   * @returns The mask with the polygon drawing.
   */
  drawPolygon(points, options = {}) {
    return drawPolygonOnMask(this, points, options);
  }
  /**
   * Draw a rectangle defined by position of the top-left corner, width and height.
   * @param options - Draw rectangle options.
   * @returns The image with the rectangle drawing.
   */
  drawRectangle(options = {}) {
    return drawRectangle(this, options);
  }
  // OPERATIONS
  /**
   * Copy the mask to another one by specifying the location in the target mask.
   * @param target - The target mask.
   * @param options - Options.
   * @returns The target with the source copied to it.
   */
  copyTo(target, options = {}) {
    return copyTo(this, target, options);
  }
  /**
   * Paint a mask onto another mask and the given position and with the given value.
   * @param mask - Mask to paint.
   * @param options - Paint mask options.
   * @returns The painted mask.
   */
  paintMask(mask, options) {
    return paintMaskOnMask(this, mask, options);
  }
}
/**
 * Returns all values of a mask as a string.
 * @param mask - Input mask.
 * @returns Formatted string with all values of a mask.
 */
function printData$1(mask) {
  const result = [];
  for (let row = 0; row < mask.height; row++) {
    const line = [];
    for (let column = 0; column < mask.width; column++) {
      line.push(String(mask.getBit(column, row)));
    }
    result.push(`[${line.join(' ')}]`);
  }
  return result.join('\n        ');
}
/**
 * Verify the channel value of a mask.
 * @param channel - The channel value.
 */
function checkChannel(channel) {
  if (channel !== 0) {
    throw new RangeError(`channel value must be 0 on type Mask. Received ${channel}`);
  }
}

/**
 * Calculate a new image that is the subtraction between the current image and the otherImage.
 * @param image - Image from which to subtract.
 * @param otherImage - Image to subtract.
 * @param options - Subtract options.
 * @returns The subtracted image.
 */
function subtract(image, otherImage, options = {}) {
  const {
    absolute = false
  } = options;
  if (image instanceof Image) {
    checkProcessable$1(image, {
      bitDepth: [1, 8, 16],
      components: [1, 3],
      alpha: false
    });
  }
  validateForComparison(image, otherImage);
  const newImage = image.clone();
  if (newImage instanceof Image) {
    for (let index = 0; index < image.size; index++) {
      for (let channel = 0; channel < image.channels; channel++) {
        const value = image.getValueByIndex(index, channel) - otherImage.getValueByIndex(index, channel);
        if (absolute) {
          if (value < 0) {
            newImage.setValueByIndex(index, channel, -value);
          } else {
            newImage.setValueByIndex(index, channel, value);
          }
        } else if (value < 0) {
          newImage.setValueByIndex(index, channel, 0);
        } else {
          newImage.setValueByIndex(index, channel, value);
        }
      }
    }
  } else if (image instanceof Mask && otherImage instanceof Mask) {
    for (let index = 0; index < image.size; index++) {
      const value = image.getBitByIndex(index) - otherImage.getBitByIndex(index);
      if (absolute) {
        newImage.setBitByIndex(index, value ? 1 : 0);
      } else {
        newImage.setBitByIndex(index, value > 0 ? 1 : 0);
      }
    }
  }
  return newImage;
}

/**
 *
 * Calculate a new image that is the sum between the current image and the otherImage.
 * @param image - Image to which to add.
 * @param otherImage - Image to add.
 * @returns The summed image.
 */
function add(image, otherImage) {
  if (image instanceof Image) {
    checkProcessable$1(image, {
      bitDepth: [8, 16],
      components: [1, 3],
      alpha: false
    });
  }
  validateForComparison(image, otherImage);
  const newImage = image.clone();
  const clamp = getClamp(image);
  for (let index = 0; index < image.size; index++) {
    for (let channel = 0; channel < image.channels; channel++) {
      const value = image.getValueByIndex(index, channel) + otherImage.getValueByIndex(index, channel);
      newImage.setValueByIndex(index, channel, clamp(value));
    }
  }
  return newImage;
}

/**
 *
 * Multiplies points by a certain value.
 * @param image - image to which multiplication will be applied.
 * @param value - Value by which each pixel will be multiplied.
 * @param options - Multiply options
 * @returns image.
 */
function multiply(image, value, options = {}) {
  const {
    channels = new Array(image.channels).fill(0).map((value, index) => index)
  } = options;
  validateChannels(channels, image);
  const newImage = getOutputImage(image, options, {
    clone: true
  });
  if (channels.length === 0) {
    return newImage;
  }
  for (const channel of channels) {
    for (let row = 0; row < newImage.height; row++) {
      for (let column = 0; column < newImage.width; column++) {
        const newIntensity = newImage.getValue(column, row, channel) * value;
        newImage.setClampedValue(column, row, channel, newIntensity);
      }
    }
  }
  return newImage;
}

/**
 * Compute the mean of an image. The mean can be either computed on each channel
 * individually or on the whole image.
 * @param image - Image to process.
 * @param options - Mean options.
 * @returns The mean pixel.
 */
function mean(image, options) {
  const pixelSum = new Array(image.channels).fill(0);
  const nbValues = options ? options.points.length : image.size;
  if (nbValues === 0) throw new RangeError('Array of coordinates is empty.');
  if (options) {
    for (const point of options.points) {
      for (let channel = 0; channel < image.channels; channel++) {
        if (point.column < 0 || point.column >= image.width || point.row < 0 || point.row >= image.height) {
          throw new RangeError(`Invalid coordinate: {column: ${point.column}, row: ${point.row}}.`);
        }
        pixelSum[channel] += image.getValueByPoint(point, channel);
      }
    }
  } else {
    for (let row = 0; row < image.height; row++) {
      for (let column = 0; column < image.width; column++) {
        for (let channel = 0; channel < image.channels; channel++) {
          pixelSum[channel] += image.getValue(column, row, channel);
        }
      }
    }
  }
  return pixelSum.map(channelSum => channelSum / nbValues);
}

/**
 * Returns a histogram of pixel intensities.
 * @param image - The original image.
 * @param options - Histogram options.
 * @returns - The histogram.
 */
function histogram$1(image, options = {}) {
  let {
    channel
  } = options;
  const {
    slots = 2 ** image.bitDepth
  } = options;
  if (!(slots !== 0 && (slots & slots - 1) === 0)) {
    throw new RangeError('slots must be a power of 2, for example: 64, 256, 1024');
  }
  if (typeof channel !== 'number') {
    if (image.channels !== 1) {
      throw new TypeError('channel option is mandatory for multi-channel images');
    }
    channel = 0;
  }
  validateChannel(channel, image);
  const hist = new Uint32Array(slots);
  let bitShift = 0;
  const bitSlots = Math.log2(slots);
  bitShift = image.bitDepth - bitSlots;
  for (let i = 0; i < image.size; i++) {
    hist[image.getValueByIndex(i, channel) >> bitShift]++;
  }
  return hist;
}

// @ts-expect-error: median-quisckselect has no types
/**
 * Returns the median pixel of the image. The median is computed on each channel individually.
 * @param image - Image to process.
 * @param options - Median options.
 * @returns Median pixel.
 */
function median(image, options) {
  const pixel = new Array(image.channels).fill(0);
  if (options) {
    if (options.points.length === 0) {
      throw new RangeError('Array of coordinates is empty.');
    }
    for (let i = 0; i < image.channels; i++) {
      const channel = [];
      for (const point of options.points) {
        if (point.column < 0 || point.column >= image.width || point.row < 0 || point.row >= image.height) {
          throw new RangeError(`Invalid coordinate: {column: ${point.column}, row: ${point.row}}.`);
        }
        channel.push(image.getValueByPoint(point, i));
      }
      pixel[i] = quickMedian(channel);
    }
  } else {
    for (let i = 0; i < image.channels; i++) {
      const channel = image.getChannel(i);
      pixel[i] = quickMedian(channel);
    }
  }
  return pixel;
}

/**
 * Checks the surrounding values of a point. If they are all bigger or smaller than the pixel in question then this point is considered an extremum.
 * @param image - Image to find extrema from.
 * @param options - ExtremaOptions
 * @returns Array of Points.
 */
function getExtrema(image, options) {
  const {
    kind = 'maximum',
    mask,
    algorithm = 'star',
    maxEquals = 2
  } = options;
  checkProcessable$1(image, {
    bitDepth: [8, 16]
  });
  const searchingMinimum = kind === 'minimum';
  const maskExpectedValue = searchingMinimum ? 0 : 1;
  const dx = [1, 0, -1, 0, 1, 1, -1, -1, 2, 0, -2, 0, 2, 2, -2, -2];
  const dy = [0, 1, 0, -1, 1, -1, 1, -1, 0, 2, 0, -2, 2, -2, 2, -2];
  switch (algorithm) {
    case 'cross':
      dx.length = 4;
      dy.length = 4;
      break;
    case 'square':
      dx.length = 8;
      dy.length = 8;
      break;
    case 'star':
      break;
    default:
      assertUnreachable(algorithm);
  }
  const shift = dx.length <= 8 ? 1 : 2; // deal with borders
  const points = [];
  for (let channel = 0; channel < image.channels; channel++) {
    for (let currentY = shift; currentY < image.height - shift; currentY++) {
      for (let currentX = shift; currentX < image.width - shift; currentX++) {
        if (mask && mask.getBit(currentX, currentY) !== maskExpectedValue) {
          continue;
        }
        let counter = 0;
        let nbEquals = 0;
        const currentValue = image.getValue(currentX, currentY, channel);
        for (let dir = 0; dir < dx.length; dir++) {
          const currentAroundValue = image.getValue(currentX + dx[dir], currentY + dy[dir], channel);
          if (searchingMinimum) {
            // we search for minima
            if (currentAroundValue > currentValue) {
              counter++;
            }
          } else if (currentAroundValue < currentValue) {
            counter++;
          }
          if (currentAroundValue === currentValue) {
            nbEquals++;
          }
        }
        if (counter + nbEquals === dx.length && nbEquals <= maxEquals) {
          points.push({
            column: currentX,
            row: currentY
          });
        }
      }
    }
  }
  // TODO How to make a more performant and general way
  // we don't deal correctly here with groups of points that should be grouped if at the
  // beginning one of them is closer to another
  // Seems that we would ened to calculate a matrix and then split this matrix in 'independant matrices'
  // Or to assign a cluster to each point and regroup them if 2 clusters are close to each other
  // later approach seems much better
  return points;
}

/**
 * Compute the variance of each channel of an image.
 * @see {@link https://en.wikipedia.org/wiki/Variance}
 * @param image - Image to process.
 * @param options - Variance options.
 * @returns The variance of the channels of the image.
 */
function variance(image, options) {
  const mean = image.mean(options);
  const sum = new Array(image.channels).fill(0);
  if (options) {
    for (const point of options.points) {
      for (let channel = 0; channel < image.channels; channel++) {
        sum[channel] += (image.getValue(point.column, point.row, channel) - mean[channel]) ** 2;
      }
    }
  } else {
    for (let i = 0; i < image.size; i++) {
      for (let channel = 0; channel < image.channels; channel++) {
        sum[channel] += (image.getValueByIndex(i, channel) - mean[channel]) ** 2;
      }
    }
  }
  const nbValues = options ? options.points.length * image.channels : image.size * image.channels;
  return sum.map(channel => channel / nbValues);
}

class MultivariateLinearRegression {
  constructor(x, y, options = {}) {
    const {
      intercept = true,
      statistics = true
    } = options;
    this.statistics = statistics;
    if (x === true) {
      this.weights = y.weights;
      this.inputs = y.inputs;
      this.outputs = y.outputs;
      this.intercept = y.intercept;
    } else {
      x = new Matrix$1(x);
      y = new Matrix$1(y);
      if (intercept) {
        x.addColumn(new Array(x.rows).fill(1));
      }
      let xt = x.transpose();
      const xx = xt.mmul(x);
      const xy = xt.mmul(y);
      const invxx = new SVD(xx).inverse();
      const beta = xy.transpose().mmul(invxx).transpose();
      this.weights = beta.to2DArray();
      this.inputs = x.columns;
      this.outputs = y.columns;
      if (intercept) this.inputs--;
      this.intercept = intercept;
      if (statistics) {
        /*
         * Let's add some basic statistics about the beta's to be able to interpret them.
         * source: http://dept.stat.lsa.umich.edu/~kshedden/Courses/Stat401/Notes/401-multreg.pdf
         * validated against Excel Regression AddIn
         * test: "datamining statistics test"
         */
        const fittedValues = x.mmul(beta);
        const residuals = y.clone().addM(fittedValues.neg());
        const variance = residuals.to2DArray().map(ri => Math.pow(ri[0], 2)).reduce((a, b) => a + b) / (y.rows - x.columns);
        this.stdError = Math.sqrt(variance);
        this.stdErrorMatrix = pseudoInverse(xx).mul(variance);
        this.stdErrors = this.stdErrorMatrix.diagonal().map(d => Math.sqrt(d));
        this.tStats = this.weights.map((d, i) => this.stdErrors[i] === 0 ? 0 : d[0] / this.stdErrors[i]);
      }
    }
  }
  predict(x) {
    if (Array.isArray(x)) {
      if (typeof x[0] === 'number') {
        return this._predict(x);
      } else if (Array.isArray(x[0])) {
        const y = new Array(x.length);
        for (let i = 0; i < x.length; i++) {
          y[i] = this._predict(x[i]);
        }
        return y;
      }
    } else if (Matrix$1.isMatrix(x)) {
      const y = new Matrix$1(x.rows, this.outputs);
      for (let i = 0; i < x.rows; i++) {
        y.setRow(i, this._predict(x.getRow(i)));
      }
      return y;
    }
    throw new TypeError('x must be a matrix or array of numbers');
  }
  _predict(x) {
    const result = new Array(this.outputs);
    if (this.intercept) {
      for (let i = 0; i < this.outputs; i++) {
        result[i] = this.weights[this.inputs][i];
      }
    } else {
      result.fill(0);
    }
    for (let i = 0; i < this.inputs; i++) {
      for (let j = 0; j < this.outputs; j++) {
        result[j] += this.weights[i][j] * x[i];
      }
    }
    return result;
  }
  score() {
    throw new Error('score method is not implemented yet');
  }
  toJSON() {
    return {
      name: 'multivariateLinearRegression',
      weights: this.weights,
      inputs: this.inputs,
      outputs: this.outputs,
      intercept: this.intercept,
      summary: this.statistics ? {
        regressionStatistics: {
          standardError: this.stdError,
          observations: this.outputs
        },
        variables: this.weights.map((d, i) => {
          return {
            label: i === this.weights.length - 1 ? 'Intercept' : `X Variable ${i + 1}`,
            coefficients: d,
            standardError: this.stdErrors[i],
            tStat: this.tStats[i]
          };
        })
      } : undefined
    };
  }
  static load(model) {
    if (model.name !== 'multivariateLinearRegression') {
      throw new Error('not a MLR model');
    }
    return new MultivariateLinearRegression(true, model);
  }
}

var r$1 = {
    grad: .9,
    turn: 360,
    rad: 360 / (2 * Math.PI)
  },
  t$1 = function (r) {
    return "string" == typeof r ? r.length > 0 : "number" == typeof r;
  },
  n$1 = function (r, t, n) {
    return void 0 === t && (t = 0), void 0 === n && (n = Math.pow(10, t)), Math.round(n * r) / n + 0;
  },
  e$1 = function (r, t, n) {
    return void 0 === t && (t = 0), void 0 === n && (n = 1), r > n ? n : r > t ? r : t;
  },
  u$1 = function (r) {
    return (r = isFinite(r) ? r % 360 : 0) > 0 ? r : r + 360;
  },
  a$1 = function (r) {
    return {
      r: e$1(r.r, 0, 255),
      g: e$1(r.g, 0, 255),
      b: e$1(r.b, 0, 255),
      a: e$1(r.a)
    };
  },
  o$1 = function (r) {
    return {
      r: n$1(r.r),
      g: n$1(r.g),
      b: n$1(r.b),
      a: n$1(r.a, 3)
    };
  },
  i$2 = /^#([0-9a-f]{3,8})$/i,
  s = function (r) {
    var t = r.toString(16);
    return t.length < 2 ? "0" + t : t;
  },
  h$1 = function (r) {
    var t = r.r,
      n = r.g,
      e = r.b,
      u = r.a,
      a = Math.max(t, n, e),
      o = a - Math.min(t, n, e),
      i = o ? a === t ? (n - e) / o : a === n ? 2 + (e - t) / o : 4 + (t - n) / o : 0;
    return {
      h: 60 * (i < 0 ? i + 6 : i),
      s: a ? o / a * 100 : 0,
      v: a / 255 * 100,
      a: u
    };
  },
  b$1 = function (r) {
    var t = r.h,
      n = r.s,
      e = r.v,
      u = r.a;
    t = t / 360 * 6, n /= 100, e /= 100;
    var a = Math.floor(t),
      o = e * (1 - n),
      i = e * (1 - (t - a) * n),
      s = e * (1 - (1 - t + a) * n),
      h = a % 6;
    return {
      r: 255 * [e, i, o, o, s, e][h],
      g: 255 * [s, e, e, i, o, o][h],
      b: 255 * [o, o, s, e, e, i][h],
      a: u
    };
  },
  g = function (r) {
    return {
      h: u$1(r.h),
      s: e$1(r.s, 0, 100),
      l: e$1(r.l, 0, 100),
      a: e$1(r.a)
    };
  },
  d = function (r) {
    return {
      h: n$1(r.h),
      s: n$1(r.s),
      l: n$1(r.l),
      a: n$1(r.a, 3)
    };
  },
  f = function (r) {
    return b$1((n = (t = r).s, {
      h: t.h,
      s: (n *= ((e = t.l) < 50 ? e : 100 - e) / 100) > 0 ? 2 * n / (e + n) * 100 : 0,
      v: e + n,
      a: t.a
    }));
    var t, n, e;
  },
  c = function (r) {
    return {
      h: (t = h$1(r)).h,
      s: (u = (200 - (n = t.s)) * (e = t.v) / 100) > 0 && u < 200 ? n * e / 100 / (u <= 100 ? u : 200 - u) * 100 : 0,
      l: u / 2,
      a: t.a
    };
    var t, n, e, u;
  },
  l$1 = /^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s*,\s*([+-]?\d*\.?\d+)%\s*,\s*([+-]?\d*\.?\d+)%\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,
  p$1 = /^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s+([+-]?\d*\.?\d+)%\s+([+-]?\d*\.?\d+)%\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,
  v = /^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,
  m = /^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,
  y = {
    string: [[function (r) {
      var t = i$2.exec(r);
      return t ? (r = t[1]).length <= 4 ? {
        r: parseInt(r[0] + r[0], 16),
        g: parseInt(r[1] + r[1], 16),
        b: parseInt(r[2] + r[2], 16),
        a: 4 === r.length ? n$1(parseInt(r[3] + r[3], 16) / 255, 2) : 1
      } : 6 === r.length || 8 === r.length ? {
        r: parseInt(r.substr(0, 2), 16),
        g: parseInt(r.substr(2, 2), 16),
        b: parseInt(r.substr(4, 2), 16),
        a: 8 === r.length ? n$1(parseInt(r.substr(6, 2), 16) / 255, 2) : 1
      } : null : null;
    }, "hex"], [function (r) {
      var t = v.exec(r) || m.exec(r);
      return t ? t[2] !== t[4] || t[4] !== t[6] ? null : a$1({
        r: Number(t[1]) / (t[2] ? 100 / 255 : 1),
        g: Number(t[3]) / (t[4] ? 100 / 255 : 1),
        b: Number(t[5]) / (t[6] ? 100 / 255 : 1),
        a: void 0 === t[7] ? 1 : Number(t[7]) / (t[8] ? 100 : 1)
      }) : null;
    }, "rgb"], [function (t) {
      var n = l$1.exec(t) || p$1.exec(t);
      if (!n) return null;
      var e,
        u,
        a = g({
          h: (e = n[1], u = n[2], void 0 === u && (u = "deg"), Number(e) * (r$1[u] || 1)),
          s: Number(n[3]),
          l: Number(n[4]),
          a: void 0 === n[5] ? 1 : Number(n[5]) / (n[6] ? 100 : 1)
        });
      return f(a);
    }, "hsl"]],
    object: [[function (r) {
      var n = r.r,
        e = r.g,
        u = r.b,
        o = r.a,
        i = void 0 === o ? 1 : o;
      return t$1(n) && t$1(e) && t$1(u) ? a$1({
        r: Number(n),
        g: Number(e),
        b: Number(u),
        a: Number(i)
      }) : null;
    }, "rgb"], [function (r) {
      var n = r.h,
        e = r.s,
        u = r.l,
        a = r.a,
        o = void 0 === a ? 1 : a;
      if (!t$1(n) || !t$1(e) || !t$1(u)) return null;
      var i = g({
        h: Number(n),
        s: Number(e),
        l: Number(u),
        a: Number(o)
      });
      return f(i);
    }, "hsl"], [function (r) {
      var n = r.h,
        a = r.s,
        o = r.v,
        i = r.a,
        s = void 0 === i ? 1 : i;
      if (!t$1(n) || !t$1(a) || !t$1(o)) return null;
      var h = function (r) {
        return {
          h: u$1(r.h),
          s: e$1(r.s, 0, 100),
          v: e$1(r.v, 0, 100),
          a: e$1(r.a)
        };
      }({
        h: Number(n),
        s: Number(a),
        v: Number(o),
        a: Number(s)
      });
      return b$1(h);
    }, "hsv"]]
  },
  N = function (r, t) {
    for (var n = 0; n < t.length; n++) {
      var e = t[n][0](r);
      if (e) return [e, t[n][1]];
    }
    return [null, void 0];
  },
  x$1 = function (r) {
    return "string" == typeof r ? N(r.trim(), y.string) : "object" == typeof r && null !== r ? N(r, y.object) : [null, void 0];
  },
  M$1 = function (r, t) {
    var n = c(r);
    return {
      h: n.h,
      s: e$1(n.s + 100 * t, 0, 100),
      l: n.l,
      a: n.a
    };
  },
  H = function (r) {
    return (299 * r.r + 587 * r.g + 114 * r.b) / 1e3 / 255;
  },
  $ = function (r, t) {
    var n = c(r);
    return {
      h: n.h,
      s: n.s,
      l: e$1(n.l + 100 * t, 0, 100),
      a: n.a
    };
  },
  j = function () {
    function r(r) {
      this.parsed = x$1(r)[0], this.rgba = this.parsed || {
        r: 0,
        g: 0,
        b: 0,
        a: 1
      };
    }
    return r.prototype.isValid = function () {
      return null !== this.parsed;
    }, r.prototype.brightness = function () {
      return n$1(H(this.rgba), 2);
    }, r.prototype.isDark = function () {
      return H(this.rgba) < .5;
    }, r.prototype.isLight = function () {
      return H(this.rgba) >= .5;
    }, r.prototype.toHex = function () {
      return r = o$1(this.rgba), t = r.r, e = r.g, u = r.b, i = (a = r.a) < 1 ? s(n$1(255 * a)) : "", "#" + s(t) + s(e) + s(u) + i;
      var r, t, e, u, a, i;
    }, r.prototype.toRgb = function () {
      return o$1(this.rgba);
    }, r.prototype.toRgbString = function () {
      return r = o$1(this.rgba), t = r.r, n = r.g, e = r.b, (u = r.a) < 1 ? "rgba(" + t + ", " + n + ", " + e + ", " + u + ")" : "rgb(" + t + ", " + n + ", " + e + ")";
      var r, t, n, e, u;
    }, r.prototype.toHsl = function () {
      return d(c(this.rgba));
    }, r.prototype.toHslString = function () {
      return r = d(c(this.rgba)), t = r.h, n = r.s, e = r.l, (u = r.a) < 1 ? "hsla(" + t + ", " + n + "%, " + e + "%, " + u + ")" : "hsl(" + t + ", " + n + "%, " + e + "%)";
      var r, t, n, e, u;
    }, r.prototype.toHsv = function () {
      return r = h$1(this.rgba), {
        h: n$1(r.h),
        s: n$1(r.s),
        v: n$1(r.v),
        a: n$1(r.a, 3)
      };
      var r;
    }, r.prototype.invert = function () {
      return w$1({
        r: 255 - (r = this.rgba).r,
        g: 255 - r.g,
        b: 255 - r.b,
        a: r.a
      });
      var r;
    }, r.prototype.saturate = function (r) {
      return void 0 === r && (r = .1), w$1(M$1(this.rgba, r));
    }, r.prototype.desaturate = function (r) {
      return void 0 === r && (r = .1), w$1(M$1(this.rgba, -r));
    }, r.prototype.grayscale = function () {
      return w$1(M$1(this.rgba, -1));
    }, r.prototype.lighten = function (r) {
      return void 0 === r && (r = .1), w$1($(this.rgba, r));
    }, r.prototype.darken = function (r) {
      return void 0 === r && (r = .1), w$1($(this.rgba, -r));
    }, r.prototype.rotate = function (r) {
      return void 0 === r && (r = 15), this.hue(this.hue() + r);
    }, r.prototype.alpha = function (r) {
      return "number" == typeof r ? w$1({
        r: (t = this.rgba).r,
        g: t.g,
        b: t.b,
        a: r
      }) : n$1(this.rgba.a, 3);
      var t;
    }, r.prototype.hue = function (r) {
      var t = c(this.rgba);
      return "number" == typeof r ? w$1({
        h: r,
        s: t.s,
        l: t.l,
        a: t.a
      }) : n$1(t.h);
    }, r.prototype.isEqual = function (r) {
      return this.toHex() === w$1(r).toHex();
    }, r;
  }(),
  w$1 = function (r) {
    return r instanceof j ? r : new j(r);
  },
  S = [],
  k = function (r) {
    r.forEach(function (r) {
      S.indexOf(r) < 0 && (r(j, y), S.push(r));
    });
  };

var a = function (a) {
    return "string" == typeof a ? a.length > 0 : "number" == typeof a;
  },
  t = function (a, t, o) {
    return void 0 === t && (t = 0), void 0 === o && (o = Math.pow(10, t)), Math.round(o * a) / o + 0;
  },
  o = function (a, t, o) {
    return void 0 === t && (t = 0), void 0 === o && (o = 1), a > o ? o : a > t ? a : t;
  },
  r = function (a) {
    var t = a / 255;
    return t < .04045 ? t / 12.92 : Math.pow((t + .055) / 1.055, 2.4);
  },
  h = function (a) {
    return 255 * (a > .0031308 ? 1.055 * Math.pow(a, 1 / 2.4) - .055 : 12.92 * a);
  },
  n = 96.422,
  p = 100,
  M = 82.521,
  u = function (a) {
    var t,
      r,
      n = {
        x: .9555766 * (t = a).x + -0.0230393 * t.y + .0631636 * t.z,
        y: -0.0282895 * t.x + 1.0099416 * t.y + .0210077 * t.z,
        z: .0122982 * t.x + -0.020483 * t.y + 1.3299098 * t.z
      };
    return r = {
      r: h(.032404542 * n.x - .015371385 * n.y - .004985314 * n.z),
      g: h(-969266e-8 * n.x + .018760108 * n.y + 41556e-8 * n.z),
      b: h(556434e-9 * n.x - .002040259 * n.y + .010572252 * n.z),
      a: a.a
    }, {
      r: o(r.r, 0, 255),
      g: o(r.g, 0, 255),
      b: o(r.b, 0, 255),
      a: o(r.a)
    };
  },
  e = function (a) {
    var t = r(a.r),
      h = r(a.g),
      u = r(a.b);
    return function (a) {
      return {
        x: o(a.x, 0, n),
        y: o(a.y, 0, p),
        z: o(a.z, 0, M),
        a: o(a.a)
      };
    }(function (a) {
      return {
        x: 1.0478112 * a.x + .0228866 * a.y + -0.050127 * a.z,
        y: .0295424 * a.x + .9904844 * a.y + -0.0170491 * a.z,
        z: -92345e-7 * a.x + .0150436 * a.y + .7521316 * a.z,
        a: a.a
      };
    }({
      x: 100 * (.4124564 * t + .3575761 * h + .1804375 * u),
      y: 100 * (.2126729 * t + .7151522 * h + .072175 * u),
      z: 100 * (.0193339 * t + .119192 * h + .9503041 * u),
      a: a.a
    }));
  },
  w = 216 / 24389,
  b = 24389 / 27,
  i$1 = function (t) {
    var r = t.l,
      h = t.a,
      n = t.b,
      p = t.alpha,
      M = void 0 === p ? 1 : p;
    if (!a(r) || !a(h) || !a(n)) return null;
    var u = function (a) {
      return {
        l: o(a.l, 0, 400),
        a: a.a,
        b: a.b,
        alpha: o(a.alpha)
      };
    }({
      l: Number(r),
      a: Number(h),
      b: Number(n),
      alpha: Number(M)
    });
    return l(u);
  },
  l = function (a) {
    var t = (a.l + 16) / 116,
      o = a.a / 500 + t,
      r = t - a.b / 200;
    return u({
      x: (Math.pow(o, 3) > w ? Math.pow(o, 3) : (116 * o - 16) / b) * n,
      y: (a.l > 8 ? Math.pow((a.l + 16) / 116, 3) : a.l / b) * p,
      z: (Math.pow(r, 3) > w ? Math.pow(r, 3) : (116 * r - 16) / b) * M,
      a: a.alpha
    });
  };
function labPlugin (a, r) {
  a.prototype.toLab = function () {
    return o = e(this.rgba), h = o.y / p, u = o.z / M, r = (r = o.x / n) > w ? Math.cbrt(r) : (b * r + 16) / 116, a = {
      l: 116 * (h = h > w ? Math.cbrt(h) : (b * h + 16) / 116) - 16,
      a: 500 * (r - h),
      b: 200 * (h - (u = u > w ? Math.cbrt(u) : (b * u + 16) / 116)),
      alpha: o.a
    }, {
      l: t(a.l, 2),
      a: t(a.a, 2),
      b: t(a.b, 2),
      alpha: t(a.alpha, 3)
    };
    var a, o, r, h, u;
  }, a.prototype.delta = function (r) {
    void 0 === r && (r = "#FFF");
    var h = r instanceof a ? r : new a(r),
      n = function (a, t) {
        var o = a.l,
          r = a.a,
          h = a.b,
          n = t.l,
          p = t.a,
          M = t.b,
          u = 180 / Math.PI,
          e = Math.PI / 180,
          w = Math.pow(Math.pow(r, 2) + Math.pow(h, 2), .5),
          b = Math.pow(Math.pow(p, 2) + Math.pow(M, 2), .5),
          i = (o + n) / 2,
          l = Math.pow((w + b) / 2, 7),
          c = .5 * (1 - Math.pow(l / (l + Math.pow(25, 7)), .5)),
          f = r * (1 + c),
          y = p * (1 + c),
          v = Math.pow(Math.pow(f, 2) + Math.pow(h, 2), .5),
          x = Math.pow(Math.pow(y, 2) + Math.pow(M, 2), .5),
          z = (v + x) / 2,
          s = 0 === f && 0 === h ? 0 : Math.atan2(h, f) * u,
          d = 0 === y && 0 === M ? 0 : Math.atan2(M, y) * u;
        s < 0 && (s += 360), d < 0 && (d += 360);
        var g = d - s,
          m = Math.abs(d - s);
        m > 180 && d <= s ? g += 360 : m > 180 && d > s && (g -= 360);
        var N = s + d;
        m <= 180 ? N /= 2 : N = (s + d < 360 ? N + 360 : N - 360) / 2;
        var F = 1 - .17 * Math.cos(e * (N - 30)) + .24 * Math.cos(2 * e * N) + .32 * Math.cos(e * (3 * N + 6)) - .2 * Math.cos(e * (4 * N - 63)),
          L = n - o,
          I = x - v,
          P = 2 * Math.sin(e * g / 2) * Math.pow(v * x, .5),
          j = 1 + .015 * Math.pow(i - 50, 2) / Math.pow(20 + Math.pow(i - 50, 2), .5),
          k = 1 + .045 * z,
          q = 1 + .015 * z * F,
          A = 30 * Math.exp(-1 * Math.pow((N - 275) / 25, 2)),
          B = -2 * Math.pow(l / (l + Math.pow(25, 7)), .5) * Math.sin(2 * e * A);
        return Math.pow(Math.pow(L / 1 / j, 2) + Math.pow(I / 1 / k, 2) + Math.pow(P / 1 / q, 2) + B * I * P / (1 * k * 1 * q), .5);
      }(this.toLab(), h.toLab()) / 100;
    return o(t(n, 3));
  }, r.object.push([i$1, "lab"]);
}

// We can't use ts-expect-error because it's not an error when compiling for CJS.
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore Module exports are not correctly typed.
k([labPlugin]);
/**
 * Format and normalize data from a QP card to use as a reference in a multivariate linear regression.
 * @param referenceColors - Array of RGB colors used as a reference.
 * @param maxValue - Maximal acceptable value for the image to process.
 * @returns The formatted data.
 */
function formatReferenceForMlr(referenceColors, maxValue) {
  const referenceData = {
    r: [],
    g: [],
    b: []
  };
  for (const color of referenceColors) {
    referenceData.r.push([color.r / maxValue]);
    referenceData.g.push([color.g / maxValue]);
    referenceData.b.push([color.b / maxValue]);
  }
  return referenceData;
}
/**
 * Compute the variables for the multivariate linear regression based on the the input colors. Values are normalized between 0 and 1.
 * @param inputColors - The input colors as an array of rgb objects.
 * @param maxValue - Maximal acceptable value for the image to process.
 * @returns The formatted input data for the regression.
 */
function formatInputForMlr(inputColors, maxValue) {
  const inputData = [];
  for (const color of inputColors) {
    inputData.push(getRegressionVariables(color.r, color.g, color.b, maxValue));
  }
  return inputData;
}

/**
 * Correct the colors in an image using the reference colors.
 * Algorithm is based on the paper "Color correction using improved linear regression algorithm".
 * DOI: 10.1109/ICTS.2015.7379874.
 * @param image - Image to process.
 * @param measuredColors - Colors from the image, which will be compared to the reference.
 * @param referenceColors - Reference colors.
 * @returns Image with the colors corrected.
 */
function correctColor(image, measuredColors, referenceColors) {
  checkProcessable$1(image, {
    colorModel: ['RGB', 'RGBA']
  });
  if (measuredColors.length !== referenceColors.length) {
    throw new RangeError('number of measured colors and reference colors must be the same');
  }
  const inputData = formatInputForMlr(measuredColors, image.maxValue);
  const referenceData = formatReferenceForMlr(referenceColors, image.maxValue);
  const mlrRed = new MultivariateLinearRegression(inputData, referenceData.r);
  const mlrGreen = new MultivariateLinearRegression(inputData, referenceData.g);
  const mlrBlue = new MultivariateLinearRegression(inputData, referenceData.b);
  const result = Image.createFrom(image);
  for (let row = 0; row < image.height; row++) {
    for (let column = 0; column < image.width; column++) {
      const pixel = image.getPixel(column, row);
      const variables = getRegressionVariables(pixel[0], pixel[1], pixel[2], image.maxValue);
      const clamp = getClamp(image);
      const newPixel = [0, 0, 0];
      const red = mlrRed.predict(variables)[0] * image.maxValue;
      const green = mlrGreen.predict(variables)[0] * image.maxValue;
      const blue = mlrBlue.predict(variables)[0] * image.maxValue;
      newPixel[0] = clamp(red);
      newPixel[1] = clamp(green);
      newPixel[2] = clamp(blue);
      if (image.alpha) {
        newPixel[3] = image.getValue(column, row, 3);
      }
      result.setPixel(column, row, newPixel);
    }
  }
  return result;
}
/**
 * Compute the third order variables for the regression from an RGB color.
 * @param r - Red component.
 * @param g - Green component.
 * @param b - Blue component.
 * @param maxValue - Maximal acceptable value for the image to process.
 * @returns The variables for the multivariate linear regression.
 */
function getRegressionVariables(r, g, b, maxValue) {
  r /= maxValue;
  g /= maxValue;
  b /= maxValue;
  return [r, g, b, r ** 2, g ** 2, b ** 2, r ** 3, g ** 3, b ** 3, r * g, r * b, b * g];
}

/**
 * Find the min and max values of each channel of the image.
 * @param image - Image to process.
 * @returns An object with arrays of the min and max values.
 */
function getMinMax(image) {
  const min = new Array(image.channels).fill(image.maxValue);
  const max = new Array(image.channels).fill(0);
  for (let row = 0; row < image.height; row++) {
    for (let column = 0; column < image.width; column++) {
      for (let channel = 0; channel < image.channels; channel++) {
        const currentValue = image.getValue(column, row, channel);
        if (currentValue < min[channel]) {
          min[channel] = currentValue;
        }
        if (currentValue > max[channel]) {
          max[channel] = currentValue;
        }
      }
    }
  }
  return {
    min,
    max
  };
}

const ImageCoordinates = {
  CENTER: 'center',
  TOP_LEFT: 'top-left',
  TOP_RIGHT: 'top-right',
  BOTTOM_LEFT: 'bottom-left',
  BOTTOM_RIGHT: 'bottom-right'
};
class Image {
  /**
   * The number of columns of the image.
   */
  width;
  /**
   * The number of rows of the image.
   */
  height;
  /**
   * The total number of pixels in the image (width × height).
   */
  size;
  /**
   * The number of bits per value in each channel.
   */
  bitDepth;
  /**
   * The color model of the image.
   */
  colorModel;
  /**
   * The number of color channels in the image, excluding the alpha channel.
   * A GREY image has 1 component. An RGB image has 3 components.
   */
  components;
  /**
   * The total number of channels in the image, including the alpha channel.
   */
  channels;
  /**
   * Whether the image has an alpha channel or not.
   */
  alpha;
  /**
   * The maximum value that a pixel channel can have.
   */
  maxValue;
  /**
   * Origin of the image relative to a the parent image.
   */
  origin;
  /**
   * Original image resolution.
   */
  originalResolution;
  meta;
  /**
   * Typed array holding the image data.
   */
  data;
  /**
   * Construct a new Image knowing its dimensions.
   * @param width - Image width.
   * @param height - Image height.
   * @param options - Image options.
   */
  constructor(width, height, options = {}) {
    const {
      bitDepth = 8,
      data,
      colorModel = 'RGB',
      origin = {
        row: 0,
        column: 0
      },
      meta,
      resolution
    } = options;
    if (width < 1 || !Number.isInteger(width)) {
      throw new RangeError(`width must be an integer and at least 1. Received ${width}`);
    }
    if (height < 1 || !Number.isInteger(height)) {
      throw new RangeError(`height must be an integer and at least 1. Received ${height}`);
    }
    this.width = width;
    this.height = height;
    this.size = width * height;
    this.bitDepth = bitDepth;
    this.colorModel = colorModel;
    this.origin = origin;
    this.meta = meta;
    this.originalResolution = resolution;
    const colorModelDef = colorModels[colorModel];
    this.components = colorModelDef.components;
    this.alpha = colorModelDef.alpha;
    this.channels = colorModelDef.channels;
    this.maxValue = 2 ** bitDepth - 1;
    if (data === undefined) {
      this.data = createPixelArray(this.size, this.channels, this.alpha, this.bitDepth, this.maxValue);
    } else {
      if (bitDepth === 8 && data instanceof Uint16Array) {
        throw new RangeError(`bitDepth is ${bitDepth} but data is Uint16Array`);
      } else if (bitDepth === 16 && data instanceof Uint8Array) {
        throw new RangeError(`bitDepth is ${bitDepth} but data is Uint8Array`);
      }
      const expectedLength = this.size * this.channels;
      if (data.length !== expectedLength) {
        throw new RangeError(`incorrect data size: ${data.length}. Expected ${expectedLength}`);
      }
      this.data = data;
    }
  }
  /**
   * Returns normalized resolution in pixels per centimeter. If resolution unit is unknown, return null.
   * @returns Object with x and y resolutions in pixel/cm.
   */
  get normalizedResolution() {
    if (!this.originalResolution) {
      return undefined;
    }
    const centimetersPerInch = 2.54;
    const centimetersPerMeter = 100;
    switch (this.originalResolution.unit) {
      case 'inch':
        return {
          x: this.originalResolution.x / centimetersPerInch,
          y: this.originalResolution.y / centimetersPerInch
        };
      case 'centimeter':
        return {
          x: this.originalResolution.x,
          y: this.originalResolution.y
        };
      case 'meter':
        return {
          x: this.originalResolution.x / centimetersPerMeter,
          y: this.originalResolution.y / centimetersPerMeter
        };
      case 'unknown':
        return null;
      default:
        throw new Error('Unknown resolution unit.');
    }
  }
  /**
   * Create a new Image based on the properties of an existing one.
   * @param other - Reference image.
   * @param options - Image options.
   * @returns New image.
   */
  static createFrom(other, options = {}) {
    const {
      width = other.width,
      height = other.height
    } = options;
    let bitDepth;
    if (other instanceof Image) {
      bitDepth = other.bitDepth;
    } else {
      bitDepth = 8;
    }
    return new Image(width, height, {
      bitDepth,
      colorModel: other.colorModel,
      origin: other.origin,
      ...options
    });
  }
  /**
   * Get all the channels of a pixel.
   * @param column - Column index.
   * @param row - Row index.
   * @returns Channels of the pixel.
   */
  getPixel(column, row) {
    const result = [];
    const start = (row * this.width + column) * this.channels;
    for (let i = 0; i < this.channels; i++) {
      result.push(this.data[start + i]);
    }
    return result;
  }
  getColumn(column) {
    const columnValues = [];
    for (let i = 0; i < this.channels; i++) {
      const channelValues = [];
      for (let j = 0; j < this.height; j++) {
        channelValues.push(this.getValue(column, j, i));
      }
      columnValues.push(channelValues);
    }
    return columnValues;
  }
  getRow(row) {
    const rowValues = [];
    for (let i = 0; i < this.channels; i++) {
      const channelValues = [];
      for (let j = 0; j < this.width; j++) {
        channelValues.push(this.getValue(j, row, i));
      }
      rowValues.push(channelValues);
    }
    return rowValues;
  }
  /**
   * Set all the channels of a pixel.
   * @param column - Column index.
   * @param row - Row index.
   * @param value - New color of the pixel to set.
   */
  setPixel(column, row, value) {
    const start = (row * this.width + column) * this.channels;
    for (let i = 0; i < this.channels; i++) {
      this.data[start + i] = value[i];
    }
  }
  /**
   * Set all the channels of a pixel if the coordinates are inside the image.
   * @param column - Column index.
   * @param row - Row index.
   * @param value - New color of the pixel to set.
   */
  setVisiblePixel(column, row, value) {
    if (column >= 0 && column < this.width && row >= 0 && row < this.height) {
      this.setPixel(column, row, value);
    }
  }
  /**
   * Get all the channels of a pixel using its index.
   * @param index - Index of the pixel.
   * @returns Channels of the pixel.
   */
  getPixelByIndex(index) {
    const result = [];
    const start = index * this.channels;
    for (let i = 0; i < this.channels; i++) {
      result.push(this.data[start + i]);
    }
    return result;
  }
  /**
   * Set all the channels of a pixel using its index.
   * @param index - Index of the pixel.
   * @param value - New channel values of the pixel to set.
   */
  setPixelByIndex(index, value) {
    const start = index * this.channels;
    for (let i = 0; i < this.channels; i++) {
      this.data[start + i] = value[i];
    }
  }
  /**
   * Get the value of a specific pixel channel. Select pixel using coordinates.
   * @param column - Column index.
   * @param row - Row index.
   * @param channel - Channel index.
   * @returns Value of the specified channel of one pixel.
   */
  getValue(column, row, channel) {
    return this.data[(row * this.width + column) * this.channels + channel];
  }
  /**
   * Set the value of a specific pixel channel. Select pixel using coordinates.
   * @param column - Column index.
   * @param row - Row index.
   * @param channel - Channel index.
   * @param value - Value to set.
   */
  setValue(column, row, channel, value) {
    this.data[(row * this.width + column) * this.channels + channel] = value;
  }
  /**
   * Set the value of a specific pixel channel. Select pixel using coordinates.
   * If the value is out of range it is set to the closest extremety.
   * @param column - Column index.
   * @param row - Row index.
   * @param channel - Channel index.
   * @param value - Value to set.
   */
  setClampedValue(column, row, channel, value) {
    if (value < 0) value = 0;else if (value > this.maxValue) value = this.maxValue;
    this.data[(row * this.width + column) * this.channels + channel] = value;
  }
  /**
   * Get the value of a specific pixel channel. Select pixel using index.
   * @param index - Index of the pixel.
   * @param channel - Channel index.
   * @returns Value of the channel of the pixel.
   */
  getValueByIndex(index, channel) {
    return this.data[index * this.channels + channel];
  }
  /**
   * Set the value of a specific pixel channel. Select pixel using index.
   * @param index - Index of the pixel.
   * @param channel - Channel index.
   * @param value - Value to set.
   */
  setValueByIndex(index, channel, value) {
    this.data[index * this.channels + channel] = value;
  }
  /**
   * Set the value of a specific pixel channel. Select pixel using index.
   * If the value is out of range it is set to the closest extremety.
   * @param index - Index of the pixel.
   * @param channel - Channel index.
   * @param value - Value to set.
   */
  setClampedValueByIndex(index, channel, value) {
    if (value < 0) value = 0;else if (value > this.maxValue) value = this.maxValue;
    this.data[index * this.channels + channel] = value;
  }
  /**
   * Get the value of a specific pixel channel. Select pixel using a point.
   * @param point - Coordinates of the desired pixel.
   * @param channel - Channel index.
   * @returns Value of the channel of the pixel.
   */
  getValueByPoint(point, channel) {
    return this.getValue(point.column, point.row, channel);
  }
  /**
   * Set the value of a specific pixel channel. Select pixel using a point.
   * @param point - Coordinates of the pixel.
   * @param channel - Channel index.
   * @param value - Value to set.
   */
  setValueByPoint(point, channel, value) {
    this.setValue(point.column, point.row, channel, value);
  }
  /**
   * Find the min and max values of each channel of the image.
   * @returns An object with arrays of the min and max values.
   */
  minMax() {
    return getMinMax(this);
  }
  /**
   * Return the raw image data.
   * @returns The raw data.
   */
  getRawImage() {
    return {
      width: this.width,
      height: this.height,
      data: this.data,
      channels: this.channels,
      bitDepth: this.bitDepth
    };
  }
  [Symbol.for('nodejs.util.inspect.custom')]() {
    let dataString;
    if (this.height > 20 || this.width > 20) {
      dataString = '[...]';
    } else {
      dataString = printData(this);
    }
    return `Image {
  width: ${this.width}
  height: ${this.height}
  bitDepth: ${this.bitDepth}
  colorModel: ${this.colorModel}
  channels: ${this.channels}
  data: ${dataString}
}`;
  }
  /**
   * Fill the image with a value or a color.
   * @param value - Value or color.
   * @returns The image instance.
   */
  fill(value) {
    if (typeof value === 'number') {
      validateValue(value, this);
      this.data.fill(value);
      return this;
    } else {
      if (value.length !== this.channels) {
        throw new RangeError(`the size of value must match the number of channels (${this.channels}). Received ${value.length}`);
      }
      for (const val of value) validateValue(val, this);
      for (let i = 0; i < this.data.length; i += this.channels) {
        for (let j = 0; j <= this.channels; j++) {
          this.data[i + j] = value[j];
        }
      }
      return this;
    }
  }
  /**
   * Fill one channel with a value.
   * @param channel - The channel to fill.
   * @param value - The new value.
   * @returns The image instance.
   */
  fillChannel(channel, value) {
    validateChannel(channel, this);
    validateValue(value, this);
    for (let i = channel; i < this.data.length; i += this.channels) {
      this.data[i] = value;
    }
    return this;
  }
  /**
   * Get one channel of the image as an array.
   * @param channel - The channel to fill.
   * @returns Array with the channel values.
   */
  getChannel(channel) {
    validateChannel(channel, this);
    const result = new Array(this.size);
    for (let i = 0; i < this.size; i++) {
      result[i] = this.data[channel + i * this.channels];
    }
    return result;
  }
  /**
   * Fill the alpha channel with the specified value.
   * @param value - New channel value.
   * @returns The image instance.
   */
  fillAlpha(value) {
    validateValue(value, this);
    if (!this.alpha) {
      throw new TypeError('fillAlpha can only be called if the image has an alpha channel');
    }
    const alphaIndex = this.channels - 1;
    return this.fillChannel(alphaIndex, value);
  }
  /**
   * Create a copy of this image.
   * @returns The image clone.
   */
  clone() {
    return Image.createFrom(this, {
      data: this.data.slice()
    });
  }
  /**
   * Modify all the values of the image using the given callback.
   * @param cb - Callback that modifies a given value.
   */
  changeEach(cb) {
    for (let i = 0; i < this.data.length; i++) {
      this.data[i] = cb(this.data[i]);
    }
  }
  /**
   * Get the coordinates of a point in the image. The reference is the top-left corner.
   * @param coordinates - The point for which you want the coordinates.
   * @param round - Whether the coordinates should be rounded. This is useful when you want the center of the image.
   * @returns Coordinates of the point in the format [column, row].
   */
  getCoordinates(coordinates, round = false) {
    return M$2(coordinates).with('center', () => {
      const centerX = (this.width - 1) / 2;
      const centerY = (this.height - 1) / 2;
      if (round) {
        return {
          column: Math.round(centerX),
          row: Math.round(centerY)
        };
      } else {
        return {
          column: centerX,
          row: centerY
        };
      }
    }).with('top-left', () => ({
      column: 0,
      row: 0
    })).with('top-right', () => ({
      column: this.width - 1,
      row: 0
    })).with('bottom-left', () => ({
      column: 0,
      row: this.height - 1
    })).with('bottom-right', () => ({
      column: this.width - 1,
      row: this.height - 1
    })).exhaustive();
  }
  // COMPARE
  /**
   * Subtract other from an image.
   * @param other - Image to subtract.
   * @param options - Inversion options.
   * @returns The subtracted image.
   */
  subtract(other, options = {}) {
    return subtract(this, other, options);
  }
  add(other) {
    return add(this, other);
  }
  /**
   *  Multiply image pixels by a constant.
   * @param value - Value which pixels will be multiplied to.
   * @param options - Multiply options.
   * @returns Multiplied image.
   */
  multiply(value, options = {}) {
    return multiply(this, value, options);
  }
  /**
   *  Divide image pixels by a constant.
   * @param value - Value which pixels will be divided to.
   * @param options - Divide options.
   * @returns Divided image.
   */
  divide(value, options = {}) {
    return divide(this, value, options);
  }
  // COMPUTE
  histogram(options) {
    return histogram$1(this, options);
  }
  /**
   * Compute the mean pixel of an image.
   * @param options - Mean options.
   * @returns The mean pixel.
   */
  mean(options) {
    return mean(this, options);
  }
  /**
   * Compute the median pixel of an image.
   * @param options - Median options.
   * @returns The median pixel.
   */
  median(options) {
    return median(this, options);
  }
  /**
   * Compute the variance of each channel of an image.
   * @param options - Variance options.
   * @returns The variance of the channels of the image.
   */
  variance(options) {
    return variance(this, options);
  }
  // DRAW
  /**
   * Draw a set of points on an image.
   * @param points - Array of points.
   * @param options - Draw points on Image options.
   * @returns New mask.
   */
  drawPoints(points, options = {}) {
    return drawPoints(this, points, options);
  }
  /**
   * Draw a line defined by two points onto an image.
   * @param from - Line starting point.
   * @param to - Line ending point.
   * @param options - Draw Line options.
   * @returns The mask with the line drawing.
   */
  drawLine(from, to, options = {}) {
    return drawLineOnImage(this, from, to, options);
  }
  /**
   * Draw a rectangle defined by position of the top-left corner, width and height.
   * @param options - Draw rectangle options.
   * @returns The image with the rectangle drawing.
   */
  drawRectangle(options = {}) {
    return drawRectangle(this, options);
  }
  /**
   * Draw a polyline defined by an array of points on an image.
   * @param points - Polyline array of points.
   * @param options - Draw polyline options.
   * @returns The image with the polyline drawing.
   */
  drawPolyline(points, options = {}) {
    return drawPolylineOnImage(this, points, options);
  }
  /**
   * Draw a polygon defined by an array of points onto an image.
   * @param points - Polygon vertices.
   * @param options - Draw Line options.
   * @returns The image with the polygon drawing.
   */
  drawPolygon(points, options = {}) {
    return drawPolygonOnImage(this, points, options);
  }
  /**
   * Draw a circle defined by center and radius onto an image.
   * @param center - Circle center.
   * @param radius - Circle radius.
   * @param options - Draw circle options.
   * @returns The image with the circle drawing.
   */
  drawCircle(center, radius, options = {}) {
    return drawCircleOnImage(this, center, radius, options);
  }
  /**
   * Draw a marker on the image.
   * @param point - Marker center point.
   * @param options - Draw marker options.
   * @returns The image with the marker drawing.
   */
  drawMarker(point, options = {}) {
    return drawMarker(this, point, options);
  }
  /**
   * Draw markers on the image.
   * @param points - Markers center points.
   * @param options - Draw marker options.
   * @returns The image with the markers drawing.
   */
  drawMarkers(points, options = {}) {
    return drawMarkers(this, points, options);
  }
  // OPERATIONS
  split() {
    return split(this);
  }
  convertColor(colorModel, options) {
    return convertColor(this, colorModel, options);
  }
  convertBitDepth(newDepth, options) {
    return convertBitDepth(this, newDepth, options);
  }
  grey(options) {
    return grey(this, options);
  }
  copyTo(target, options = {}) {
    return copyTo(this, target, options);
  }
  threshold(options = {}) {
    return threshold(this, options);
  }
  /**
   * Crop the input image to a desired size.
   * @param [options] - Crop options.
   * @returns The new cropped image.
   */
  crop(options) {
    return crop(this, options);
  }
  /**
   * Crop an oriented rectangle from the image.
   * If the rectangle's length or width are not an integers, its dimension is expanded in both directions such as the length and width are integers.
   * @param points - The points of the rectangle. Points must be circling around the rectangle (clockwise or anti-clockwise)
   * @param options - Crop options, see {@link CropRectangleOptions}
   * @returns The cropped image. The orientation of the image is the one closest to the rectangle passed as input.
   */
  cropRectangle(points, options) {
    return cropRectangle(this, points, options);
  }
  /**
   * Crops the image based on the alpha channel
   * This removes lines and columns where the alpha channel is lower than a threshold value.
   * @param options - Crop alpha options.
   * @returns The cropped image.
   */
  cropAlpha(options = {}) {
    return cropAlpha(this, options);
  }
  /**
   * Extract the pixels of an image, as specified in a mask.
   * @param mask - The mask defining which pixels to keep.
   * @param options - Extract options.
   * @returns The extracted image.
   */
  extract(mask, options) {
    return extract(this, mask, options);
  }
  /**
   * Paint a mask onto an image and the given position and with the given color.
   * @param mask - Mask to paint on the image.
   * @param options - Paint mask options.
   * @returns The painted image.
   */
  paintMask(mask, options) {
    return paintMaskOnImage(this, mask, options);
  }
  // FILTERS
  blur(options) {
    return blur(this, options);
  }
  pixelate(options) {
    return pixelate(this, options);
  }
  directConvolution(kernel, options) {
    return directConvolution(this, kernel, options);
  }
  /**
   * Compute direct convolution of an image and return an array with the raw values.
   * @param kernel - Kernel used for the convolution.
   * @param options - Convolution options.
   * @returns Array with the raw convoluted values.
   */
  rawDirectConvolution(kernel, options) {
    return rawDirectConvolution(this, kernel, options);
  }
  separableConvolution(kernelX, kernelY, options) {
    return separableConvolution(this, kernelX, kernelY, options);
  }
  /**
   * Apply a gaussian filter to an image.
   * @param options - Gaussian blur options.
   * @returns The blurred image.
   */
  gaussianBlur(options) {
    return gaussianBlur(this, options);
  }
  /**
   * Flip the image.
   * @param options - Flip options.
   * @returns The flipped image.
   */
  flip(options) {
    return flip(this, options);
  }
  /**
   *   Invert the colors of the image.
   * @param options - Inversion options.
   * @returns The inverted image.
   */
  invert(options) {
    return invert(this, options);
  }
  /**
   * Calculate a new image that is the hypotenuse between the current image and the other.
   * @param other - Other image.
   * @param options - Hypotenuse options.
   * @returns Hypotenuse of the two images.
   */
  hypotenuse(other, options) {
    return hypotenuse(this, other, options);
  }
  /**
   * Apply a gradient filter to an image.
   * @param options - Gradient filter options.
   * @returns The gradient image.
   */
  gradientFilter(options) {
    return gradientFilter(this, options);
  }
  /**
   * Apply a derivative filter to an image.
   * @param options - Derivative filter options.
   * @returns The processed image.
   */
  derivativeFilter(options) {
    return derivativeFilter(this, options);
  }
  /**
   * Level the image using the optional input and output value. This function allows you to enhance the image's contrast.
   * @param options - Level options.
   * @returns The levelled image.
   */
  level(options) {
    return level(this, options);
  }
  /**
   * Increase the contrast of an image by spanning each channel on the range [0, image.maxValue].
   * @param options - Increase contrast options.
   * @returns The enhanced image.
   */
  increaseContrast(options = {}) {
    return increaseContrast(this, options);
  }
  /**
   * Correct the colors in an image using the reference colors.
   * @param measuredColors - Colors from the image, which will be compared to the reference.
   * @param referenceColors - Reference colors.
   * @returns Image with the colors corrected.
   */
  correctColor(measuredColors, referenceColors) {
    return correctColor(this, measuredColors, referenceColors);
  }
  /**
   * Apply a median filter to the image.
   * @param options - Options to apply for median filter.
   * @returns Image after median filter.
   */
  medianFilter(options) {
    return medianFilter(this, options);
  }
  // GEOMETRY
  resize(options) {
    return resize(this, options);
  }
  rotate(angle) {
    return rotate(this, angle);
  }
  transform(transformMatrix, options) {
    return transform(this, transformMatrix, options);
  }
  transformRotate(angle, options) {
    return transformRotate(this, angle, options);
  }
  // MORPHOLOGY
  /**
   * Erode an image.
   * @param options - Erode options.
   * @returns The eroded image.
   */
  erode(options) {
    return erode(this, options);
  }
  /**
   * Dilate an image.
   * @param options - Dilate options.
   * @returns The dilated image.
   */
  dilate(options) {
    return dilate(this, options);
  }
  /**
   * Open an image.
   * @param options - Open options.
   * @returns The opened image.
   */
  open(options) {
    return open(this, options);
  }
  /**
   * Close an image.
   * @param options - Close options.
   * @returns The closed image.
   */
  close(options) {
    return close(this, options);
  }
  /**
   * Top hat of an image.
   * @param options - Top hat options.
   * @returns The top-hatted image.
   */
  topHat(options) {
    return topHat(this, options);
  }
  /**
   * Bottom hat of an image.
   * @param options - Bottom hat options.
   * @returns The bottom-hatted image.
   */
  bottomHat(options) {
    return bottomHat(this, options);
  }
  /**
   * Apply morphological gradient to an image.
   * @param options - Morphological gradient options.
   * @returns The processed image.
   */
  morphologicalGradient(options) {
    return morphologicalGradient(this, options);
  }
  /**
   * Apply Canny edge detection to an image.
   * @param options - Canny edge detection options.
   * @returns The processed image.
   */
  cannyEdgeDetector(options) {
    return cannyEdgeDetector(this, options);
  }
}
/**
 * Create data array and set alpha channel to max value if applicable.
 * @param size - Number of pixels.
 * @param channels - Number of channels.
 * @param alpha - Specify if there is alpha channel.
 * @param bitDepth - Number of bits per channel.
 * @param maxValue - Maximal acceptable value for the channels.
 * @returns The new pixel array.
 */
function createPixelArray(size, channels, alpha, bitDepth, maxValue) {
  const length = channels * size;
  const arr = M$2(bitDepth).with(8, () => new Uint8Array(length)).with(16, () => new Uint16Array(length)).otherwise(() => {
    throw new RangeError(`invalid bitDepth: ${bitDepth}`);
  });
  // Alpha channel is 100% by default.
  if (alpha) {
    for (let i = channels - 1; i < length; i += channels) {
      arr[i] = maxValue;
    }
  }
  return arr;
}
/**
 * Returns the image data as a formatted string.
 * @param img - The image instance.
 * @returns Formatted string containing the image data.
 */
function printData(img) {
  const result = [];
  const padding = img.bitDepth === 8 ? 3 : 5;
  for (let row = 0; row < img.height; row++) {
    const currentRow = [];
    for (let column = 0; column < img.width; column++) {
      for (let channel = 0; channel < img.channels; channel++) {
        currentRow.push(String(img.getValue(column, row, channel)).padStart(padding, ' '));
      }
    }
    result.push(`[${currentRow.join(' ')}]`);
  }
  return `{
    [\n     ${result.join('\n     ')}\n    ]
  }`;
}

/**
 * Copy the data of an source to the target image.
 * @param source - Image which data is copied.
 * @param target - Image to which the data must be copied.
 */
function copyData(source, target) {
  if (target.width !== source.width || target.height !== source.height || target.colorModel !== source.colorModel) {
    throw new RangeError('images width, height or color model is different');
  }
  // @ts-expect-error Accessing data, which is private
  target.data = source.data.slice();
}

/**
 * Use this function to support getting the output image of an algorithm from
 * user-supplied options.
 * @param thisImage - Current image on which the algorithm is applied.
 * @param options - Options object received by the algorithm.
 * @param internalOptions - Some additional private options.
 * @returns The output image.
 */
function getOutputImage(thisImage, options = {}, internalOptions = {}) {
  const {
    out
  } = options;
  const {
    newParameters,
    clone
  } = internalOptions;
  if (out === undefined) {
    if (clone) {
      return thisImage.clone();
    } else {
      return Image.createFrom(thisImage, newParameters);
    }
  } else {
    if (!(out instanceof Image)) {
      throw new TypeError('out must be an Image');
    }
    const requirements = {
      width: thisImage.width,
      height: thisImage.height,
      bitDepth: thisImage.bitDepth,
      colorModel: thisImage.colorModel,
      ...newParameters
    };
    checkRequirements(requirements, out);
    if (clone && thisImage !== out) {
      copyData(thisImage, out);
    }
    return out;
  }
}
/**
 * Use this function to support getting the output image of an algorithm from
 * user-supplied options when the input is a mask.
 * @param mask - Current mask on which the algorithm is applied.
 * @param options - Options object received by the algorithm.
 * @returns The output image.
 */
function maskToOutputImage(mask, options = {}) {
  const {
    out
  } = options;
  if (out === undefined) {
    return Image.createFrom(mask, {
      colorModel: 'GREY'
    });
  } else {
    if (!(out instanceof Image)) {
      throw new TypeError('out must be an Image');
    }
    const requirements = {
      width: mask.width,
      height: mask.height,
      bitDepth: 8,
      colorModel: 'GREY'
    };
    checkRequirements(requirements, out);
    return out;
  }
}
/**
 * Use this function to support getting the output mask of an algorithm from
 * user-supplied options when the input is an image.
 * @param image - Current image on which the algorithm is applied.
 * @param options - Options object received by the algorithm.
 * @returns The output mask.
 */
function imageToOutputMask(image, options = {}) {
  const {
    out
  } = options;
  if (out === undefined) {
    return Mask.createFrom(image);
  } else {
    if (!(out instanceof Mask)) {
      throw new TypeError('out must be a Mask');
    }
    const requirements = {
      width: image.width,
      height: image.height,
      bitDepth: 1,
      colorModel: 'BINARY'
    };
    checkRequirements(requirements, out);
    return out;
  }
}
function checkRequirements(requirements, out) {
  for (const property in requirements) {
    const prop = property;
    if (out[prop] !== requirements[prop]) {
      throw new RangeError(`cannot use out image. Its ${property} property must be ${requirements[prop]}. Received ${out[prop]}`);
    }
  }
}
/**
 * Use this function to support getting the output mask of an algorithm from
 * user-supplied options when the input is an mask.
 * @param mask - Current mask on which the algorithm is applied.
 * @param options - Options object received by the algorithm.
 * @param internalOptions - Additional private options.
 * @returns The output mask.
 */
function maskToOutputMask(mask, options = {}, internalOptions = {}) {
  const {
    out
  } = options;
  const {
    newParameters,
    clone
  } = internalOptions;
  if (out === undefined) {
    if (clone) {
      return mask.clone();
    } else {
      return Mask.createFrom(mask, newParameters);
    }
  } else {
    if (!(out instanceof Mask)) {
      throw new TypeError('out must be a Mask');
    }
    const requirements = {
      width: mask.width,
      height: mask.height,
      bitDepth: 1,
      colorModel: 'BINARY'
    };
    checkRequirements(requirements, out);
    if (clone && mask !== out) {
      copyData(mask, out);
    }
    return out;
  }
}

/**
 * Generate an array of colors to draw the keypoints depending on their score or the matches depending on the distance.
 * @param image - The source image.
 * @param baseColor - The desired shade for the colors.
 * @param options - Get score colors options.
 * @returns Array of colors.
 */
function getColors(image, baseColor, options = {}) {
  const {
    nbShades = 6,
    minValueFactor = 0.2
  } = options;
  const maxValue = Math.max(...baseColor);
  const minValue = maxValue * minValueFactor;
  const interval = Math.floor((maxValue - minValue) / (nbShades - 1));
  const clamp = getClampFromTo(0, image.maxValue);
  const colors = [];
  for (let i = 0; i < nbShades; i++) {
    const color = [];
    for (const channel of baseColor) {
      color.push(clamp(channel - i * interval));
    }
    colors.push(color);
  }
  return colors;
}

/**
 * Get the shade the keypoint with given index should have (the color is an indicator
 * of the score). The keypoints should be sorted with highest score first.
 * @param keypoints - The sorted keypoints.
 * @param index - Index of the keypoint.
 * @param colors - The colors from which to pick (sorted from brightest to darkest).
 * @returns The color the keypoint should have.
 */
function getKeypointColor(keypoints, index, colors) {
  const maxScore = keypoints[0].score;
  const minScore = keypoints.at(-1).score;
  if (minScore === maxScore) {
    return colors[0];
  }
  const score = keypoints[index].score;
  const colorIndex = colors.length - 1 - Math.floor((colors.length - 1) * (score - minScore) / (maxScore - minScore));
  return colors[colorIndex];
}

/**
 * Draw keypoints on an image.
 * @param image - The source image of the keypoints.
 * @param keypoints - The FAST keypoints.
 * @param options - Draw keypoints options.
 * @returns The image with the keypoints indicated by empty circles.
 */
function drawKeypoints(image, keypoints, options = {}) {
  const {
    markerSize = 10,
    fill = false,
    showScore = false,
    origin = {
      row: 0,
      column: 0
    },
    showScoreOptions
  } = options;
  let {
    maxNbKeypoints = keypoints.length
  } = options;
  const {
    strokeColor = [255, 0, 0]
  } = options;
  if (maxNbKeypoints > keypoints.length) {
    maxNbKeypoints = keypoints.length;
  }
  let newImage = getOutputImage(image, options, {
    clone: true
  });
  if (image.colorModel !== 'RGB') {
    newImage = newImage.convertColor('RGB');
  }
  const colors = getColors(image, strokeColor, showScoreOptions);
  const radius = Math.ceil(markerSize / 2);
  for (let i = 0; i < maxNbKeypoints; i++) {
    const keypoint = keypoints[i];
    let keypointColor = strokeColor;
    if (showScore) {
      keypointColor = getKeypointColor(keypoints, i, colors);
    }
    const fillColor = fill ? keypointColor : undefined;
    const absoluteOrigin = sum$1(keypoint.origin, origin);
    newImage.drawCircle(absoluteOrigin, radius, {
      fillColor,
      strokeColor: keypointColor,
      out: newImage
    });
    if (isOrientedFastKeypoint(keypoint) && options.showOrientation) {
      const angle = keypoint.angle;
      const from = absoluteOrigin;
      const radAngle = angle * Math.PI / 180;
      const to = {
        column: from.column + Math.round(radius * Math.cos(radAngle)),
        row: from.row - Math.round(radius * Math.sin(radAngle))
      };
      newImage.drawLine(from, to, {
        strokeColor: keypointColor,
        out: newImage
      });
    }
  }
  return newImage;
}
function isOrientedFastKeypoint(kpt) {
  return 'angle' in kpt && typeof kpt.angle === 'number';
}

/**
 * Get the shade of the match with given index (the color is an indicator
 * of the distance). The matches should be sorted with smallest distance first.
 * @param matches - The sorted keypoints.
 * @param index - Index of the keypoint.
 * @param colors - The colors from which to pick (sorted from brightest to darkest).
 * @returns The color the keypoint should have.
 */
function getMatchColor(matches, index, colors) {
  const maxDistance = matches.at(-1).distance;
  const minDistance = matches[0].distance;
  if (minDistance === maxDistance) {
    return colors[0];
  }
  const distance = matches[index].distance;
  const colorIndex = Math.floor((colors.length - 1) * (distance - minDistance) / (maxDistance - minDistance));
  return colors[colorIndex];
}

/**
 * Source array of matches by ascending distance.
 * @param matches - Array of matches to sort.
 * @returns Sorted copy of the array of matches.
 */
function sortByDistance(matches) {
  const sorted = matches.slice();
  sorted.sort((match1, match2) => {
    return match1.distance - match2.distance;
  });
  return sorted;
}

/**
 * Scales the coordinates of the keypoints.
 * @param keypoints - Keypoints to scale.
 * @param scale - Scalar by which to multiply the coordinates.
 * @returns Scaled keypoints (copy of the original array).
 */
function scaleKeypoints(keypoints, scale) {
  if (scale === 1) return keypoints.slice();
  return keypoints.map(kpt => {
    return {
      origin: {
        row: kpt.origin.row * scale,
        column: kpt.origin.column * scale
      },
      score: kpt.score
    };
  });
}

/**
 * Draw the the matches between two images on their montage.
 * @param montage - The montage of two images to match.
 * @param matches - The matches between source and destination.
 * @param sourceKeypoints - Source keypoints.
 * @param destinationKeypoints - Destination keypoints.
 * @param options - Draw matches options.
 * @returns The comparison image.
 */
function drawMatches(montage, matches, sourceKeypoints, destinationKeypoints, options = {}) {
  const {
    circleDiameter = 10,
    strokeColor = [255, 0, 0],
    showDistance = false,
    showDistanceOptions
  } = options;
  let {
    maxNbMatches = matches.length
  } = options;
  if (maxNbMatches > matches.length) {
    maxNbMatches = matches.length;
  }
  const scaledSource = scaleKeypoints(sourceKeypoints, montage.scale);
  const scaledDestination = scaleKeypoints(destinationKeypoints, montage.scale);
  const result = montage.image;
  const colors = getColors(result, strokeColor, showDistanceOptions);
  const radius = Math.ceil(circleDiameter / 2);
  const matchesSortedByDistance = sortByDistance(matches);
  for (let i = 0; i < maxNbMatches; i++) {
    let matchColor = strokeColor;
    if (showDistance) {
      matchColor = getMatchColor(matchesSortedByDistance, i, colors);
    }
    const sourcePoint = scaledSource[matches[i].sourceIndex].origin;
    result.drawCircle(sourcePoint, radius, {
      strokeColor: matchColor,
      out: result
    });
    const relativeDestinationPoint = scaledDestination[matches[i].destinationIndex].origin;
    const destinationPoint = {
      column: relativeDestinationPoint.column + montage.destinationOrigin.column,
      row: relativeDestinationPoint.row + montage.destinationOrigin.row
    };
    result.drawCircle(destinationPoint, radius, {
      strokeColor: matchColor,
      out: result
    });
    result.drawLine(sourcePoint, destinationPoint, {
      out: result,
      strokeColor: matchColor
    });
  }
  return result;
}

const MontageDisposition = {
  HORIZONTAL: 'horizontal',
  VERTICAL: 'vertical'
};
class Montage {
  /**
   * Scaled width of the first image.
   */
  sourceWidth;
  /**
   * Scaled height of the first image.
   */
  sourceHeight;
  /**
   * Scaled width of the second image.
   */
  destinationWidth;
  /**
   * Scaled height of the second image.
   */
  destinationHeight;
  /**
   * Origin of the destination / second image relative to top-left corner of the Montage.
   */
  destinationOrigin;
  /**
   * Width of the Montage.
   */
  width;
  /**
   * Height of the Montage.
   */
  height;
  /**
   * Factor by which to scale the images are scaled in the montage.
   */
  scale;
  disposition;
  /**
   * Image of the Montage.
   */
  image;
  /**
   * Create a Montage of two images. The two images are placed side by side for comparison.
   * @param source - First image.
   * @param destination - Second image.
   * @param options  - Montage options.
   */
  constructor(source, destination, options = {}) {
    const {
      scale = 1,
      disposition = 'horizontal'
    } = options;
    if (!Number.isInteger(scale)) {
      throw new TypeError('scale must be an integer');
    }
    this.scale = scale;
    this.disposition = disposition;
    this.sourceWidth = scale * source.width;
    this.destinationWidth = scale * destination.width;
    this.sourceHeight = scale * source.height;
    this.destinationHeight = scale * destination.height;
    if (disposition === 'horizontal') {
      this.destinationOrigin = {
        row: 0,
        column: this.sourceWidth
      };
      this.width = this.sourceWidth + this.destinationWidth;
      this.height = Math.max(this.sourceHeight, this.destinationHeight);
    } else if (disposition === 'vertical') {
      this.destinationOrigin = {
        row: this.sourceHeight,
        column: 0
      };
      this.width = Math.max(this.sourceWidth, this.destinationWidth);
      this.height = this.sourceHeight + this.destinationHeight;
    } else {
      throw new RangeError(`invalid disposition type: ${disposition}`);
    }
    if (source.colorModel !== 'RGB') {
      source = source.convertColor('RGB');
    }
    if (destination.colorModel !== 'RGB') {
      destination = destination.convertColor('RGB');
    }
    const image = new Image(this.width, this.height);
    source.resize({
      xFactor: scale,
      yFactor: scale
    }).copyTo(image, {
      out: image
    });
    destination.resize({
      xFactor: scale,
      yFactor: scale
    }).copyTo(image, {
      out: image,
      origin: this.destinationOrigin
    });
    this.image = image;
  }
  /**
   * Draw keypoints on the Montage.
   * @param keypoints - Keypoints to draw.
   * @param options - Draw keypoints options.
   */
  drawKeypoints(keypoints, options = {}) {
    const scaledKeypoints = scaleKeypoints(keypoints, this.scale);
    this.image = drawKeypoints(this.image, scaledKeypoints, options);
  }
  /**
   * Draw the matches between source and destination keypoints.
   * @param matches - Matches to draw.
   * @param sourceKeypoints - Source keypoints.
   * @param destinationKeypoints  - Destination keypoints.
   * @param options - Draw matches options.
   */
  drawMatches(matches, sourceKeypoints, destinationKeypoints, options = {}) {
    this.image = drawMatches(this, matches, sourceKeypoints, destinationKeypoints, options);
  }
}

/**
 * Overlap two images and specify. The first image can be translated,
 * rotated and scaled to match the second one.
 * The first image is drawn in red and the second one in green.
 * @param image1 - First image.
 * @param image2 - Second image.
 * @param options - Overlap image options.
 * @returns The overlapping images.
 */
function overlapImages(image1, image2, options = {}) {
  const {
    origin = {
      row: 0,
      column: 0
    },
    angle = 0,
    scale = 1
  } = options;
  if (scale === 0) {
    throw new Error('Scale cannot be 0');
  }
  if (image1.colorModel !== ImageColorModel.GREY) {
    image1 = image1.grey();
  }
  if (image2.colorModel !== ImageColorModel.GREY) {
    image2 = image2.grey();
  }
  const inverted1 = image1.invert();
  const inverted2 = image2.invert();
  const rotated = inverted1.transformRotate(angle, {
    center: ImageCoordinates.TOP_LEFT
  });
  const scaled = rotated.resize({
    xFactor: scale,
    yFactor: scale
  });
  const empty = Image.createFrom(inverted2);
  const alignedGrey1 = scaled.copyTo(empty, {
    origin
  });
  const result = merge([alignedGrey1, inverted2, empty]);
  return result;
}

/**
 * Use this function to only keep the match from source to destination with
 * the smallest distance (score) for each destination keypoint.
 * @param matches - Matches from source to destination.
 * @param sourceKeypoints - Source keypoints.
 * @param destinationKeypoints - Destination keypoints.
 * @param options - Filter smallest distance matches options.
 * @returns Only the matches from source to destination with the smallest distance.
 */
function filterEuclideanDistance(matches, sourceKeypoints, destinationKeypoints, options = {}) {
  const {
    origin = {
      column: 0,
      row: 0
    }
  } = options;
  const sorted = matches.slice();
  sorted.sort((a, b) => a.destinationIndex - b.destinationIndex);
  const result = [];
  let sameDestMatches = [];
  let currentIndex = sorted[0].destinationIndex;
  for (const match of sorted) {
    if (match.destinationIndex === currentIndex) {
      sameDestMatches.push(match);
    } else {
      sameDestMatches.sort((a, b) => distanceSquared(a) - distanceSquared(b));
      result.push(...sameDestMatches.slice(0, 1));
      currentIndex = match.destinationIndex;
      sameDestMatches = [match];
    }
  }
  sameDestMatches.sort((a, b) => distanceSquared(a) - distanceSquared(b));
  result.push(...sameDestMatches.slice(0, 1));
  return result;
  function distanceSquared(match) {
    return (sourceKeypoints[match.sourceIndex].origin.row - (destinationKeypoints[match.destinationIndex].origin.row - origin.row)) ** 2 + (sourceKeypoints[match.sourceIndex].origin.column - destinationKeypoints[match.destinationIndex].origin.column - origin.column) ** 2;
  }
}

/**
 * Decode bytes to text
 * @param bytes - Bytes to decode
 * @param encoding - Text encoding
 * @returns The decoded text
 */
function decode$4(bytes, encoding = 'utf8') {
  const decoder = new TextDecoder(encoding);
  return decoder.decode(bytes);
}
const encoder$1 = new TextEncoder();
/**
 * Encode text to utf8
 * @param str - Text to encode
 * @returns The encoded bytes
 */
function encode$3(str) {
  return encoder$1.encode(str);
}

const defaultByteLength = 1024 * 8;
const hostBigEndian = (() => {
  const array = new Uint8Array(4);
  const view = new Uint32Array(array.buffer);
  return !((view[0] = 1) & array[0]);
})();
const typedArrays = {
  int8: globalThis.Int8Array,
  uint8: globalThis.Uint8Array,
  int16: globalThis.Int16Array,
  uint16: globalThis.Uint16Array,
  int32: globalThis.Int32Array,
  uint32: globalThis.Uint32Array,
  uint64: globalThis.BigUint64Array,
  int64: globalThis.BigInt64Array,
  float32: globalThis.Float32Array,
  float64: globalThis.Float64Array
};
class IOBuffer {
  /**
   * Reference to the internal ArrayBuffer object.
   */
  buffer;
  /**
   * Byte length of the internal ArrayBuffer.
   */
  byteLength;
  /**
   * Byte offset of the internal ArrayBuffer.
   */
  byteOffset;
  /**
   * Byte length of the internal ArrayBuffer.
   */
  length;
  /**
   * The current offset of the buffer's pointer.
   */
  offset;
  lastWrittenByte;
  littleEndian;
  _data;
  _mark;
  _marks;
  /**
   * Create a new IOBuffer.
   * @param data - The data to construct the IOBuffer with.
   * If data is a number, it will be the new buffer's length<br>
   * If data is `undefined`, the buffer will be initialized with a default length of 8Kb<br>
   * If data is an ArrayBuffer, SharedArrayBuffer, an ArrayBufferView (Typed Array), an IOBuffer instance,
   * or a Node.js Buffer, a view will be created over the underlying ArrayBuffer.
   * @param options - An object for the options.
   * @returns A new IOBuffer instance.
   */
  constructor(data = defaultByteLength, options = {}) {
    let dataIsGiven = false;
    if (typeof data === 'number') {
      data = new ArrayBuffer(data);
    } else {
      dataIsGiven = true;
      this.lastWrittenByte = data.byteLength;
    }
    const offset = options.offset ? options.offset >>> 0 : 0;
    const byteLength = data.byteLength - offset;
    let dvOffset = offset;
    if (ArrayBuffer.isView(data) || data instanceof IOBuffer) {
      if (data.byteLength !== data.buffer.byteLength) {
        dvOffset = data.byteOffset + offset;
      }
      data = data.buffer;
    }
    if (dataIsGiven) {
      this.lastWrittenByte = byteLength;
    } else {
      this.lastWrittenByte = 0;
    }
    this.buffer = data;
    this.length = byteLength;
    this.byteLength = byteLength;
    this.byteOffset = dvOffset;
    this.offset = 0;
    this.littleEndian = true;
    this._data = new DataView(this.buffer, dvOffset, byteLength);
    this._mark = 0;
    this._marks = [];
  }
  /**
   * Checks if the memory allocated to the buffer is sufficient to store more
   * bytes after the offset.
   * @param byteLength - The needed memory in bytes.
   * @returns `true` if there is sufficient space and `false` otherwise.
   */
  available(byteLength = 1) {
    return this.offset + byteLength <= this.length;
  }
  /**
   * Check if little-endian mode is used for reading and writing multi-byte
   * values.
   * @returns `true` if little-endian mode is used, `false` otherwise.
   */
  isLittleEndian() {
    return this.littleEndian;
  }
  /**
   * Set little-endian mode for reading and writing multi-byte values.
   * @returns This.
   */
  setLittleEndian() {
    this.littleEndian = true;
    return this;
  }
  /**
   * Check if big-endian mode is used for reading and writing multi-byte values.
   * @returns `true` if big-endian mode is used, `false` otherwise.
   */
  isBigEndian() {
    return !this.littleEndian;
  }
  /**
   * Switches to big-endian mode for reading and writing multi-byte values.
   * @returns This.
   */
  setBigEndian() {
    this.littleEndian = false;
    return this;
  }
  /**
   * Move the pointer n bytes forward.
   * @param n - Number of bytes to skip.
   * @returns This.
   */
  skip(n = 1) {
    this.offset += n;
    return this;
  }
  /**
   * Move the pointer n bytes backward.
   * @param n - Number of bytes to move back.
   * @returns This.
   */
  back(n = 1) {
    this.offset -= n;
    return this;
  }
  /**
   * Move the pointer to the given offset.
   * @param offset - The offset to move to.
   * @returns This.
   */
  seek(offset) {
    this.offset = offset;
    return this;
  }
  /**
   * Store the current pointer offset.
   * @see {@link IOBuffer#reset}
   * @returns This.
   */
  mark() {
    this._mark = this.offset;
    return this;
  }
  /**
   * Move the pointer back to the last pointer offset set by mark.
   * @see {@link IOBuffer#mark}
   * @returns This.
   */
  reset() {
    this.offset = this._mark;
    return this;
  }
  /**
   * Push the current pointer offset to the mark stack.
   * @see {@link IOBuffer#popMark}
   * @returns This.
   */
  pushMark() {
    this._marks.push(this.offset);
    return this;
  }
  /**
   * Pop the last pointer offset from the mark stack, and set the current
   * pointer offset to the popped value.
   * @see {@link IOBuffer#pushMark}
   * @returns This.
   */
  popMark() {
    const offset = this._marks.pop();
    if (offset === undefined) {
      throw new Error('Mark stack empty');
    }
    this.seek(offset);
    return this;
  }
  /**
   * Move the pointer offset back to 0.
   * @returns This.
   */
  rewind() {
    this.offset = 0;
    return this;
  }
  /**
   * Make sure the buffer has sufficient memory to write a given byteLength at
   * the current pointer offset.
   * If the buffer's memory is insufficient, this method will create a new
   * buffer (a copy) with a length that is twice (byteLength + current offset).
   * @param byteLength - The needed memory in bytes.
   * @returns This.
   */
  ensureAvailable(byteLength = 1) {
    if (!this.available(byteLength)) {
      const lengthNeeded = this.offset + byteLength;
      const newLength = lengthNeeded * 2;
      const newArray = new Uint8Array(newLength);
      newArray.set(new Uint8Array(this.buffer));
      this.buffer = newArray.buffer;
      this.length = newLength;
      this.byteLength = newLength;
      this._data = new DataView(this.buffer);
    }
    return this;
  }
  /**
   * Read a byte and return false if the byte's value is 0, or true otherwise.
   * Moves pointer forward by one byte.
   * @returns The read boolean.
   */
  readBoolean() {
    return this.readUint8() !== 0;
  }
  /**
   * Read a signed 8-bit integer and move pointer forward by 1 byte.
   * @returns The read byte.
   */
  readInt8() {
    return this._data.getInt8(this.offset++);
  }
  /**
   * Read an unsigned 8-bit integer and move pointer forward by 1 byte.
   * @returns The read byte.
   */
  readUint8() {
    return this._data.getUint8(this.offset++);
  }
  /**
   * Alias for {@link IOBuffer#readUint8}.
   * @returns The read byte.
   */
  readByte() {
    return this.readUint8();
  }
  /**
   * Read `n` bytes and move pointer forward by `n` bytes.
   * @param n - Number of bytes to read.
   * @returns The read bytes.
   */
  readBytes(n = 1) {
    return this.readArray(n, 'uint8');
  }
  /**
   * Creates an array of corresponding to the type `type` and size `size`.
   * For example, type `uint8` will create a `Uint8Array`.
   * @param size - size of the resulting array
   * @param type - number type of elements to read
   * @returns The read array.
   */
  readArray(size, type) {
    const bytes = typedArrays[type].BYTES_PER_ELEMENT * size;
    const offset = this.byteOffset + this.offset;
    const slice = this.buffer.slice(offset, offset + bytes);
    if (this.littleEndian === hostBigEndian && type !== 'uint8' && type !== 'int8') {
      const slice = new Uint8Array(this.buffer.slice(offset, offset + bytes));
      slice.reverse();
      const returnArray = new typedArrays[type](slice.buffer);
      this.offset += bytes;
      returnArray.reverse();
      return returnArray;
    }
    const returnArray = new typedArrays[type](slice);
    this.offset += bytes;
    return returnArray;
  }
  /**
   * Read a 16-bit signed integer and move pointer forward by 2 bytes.
   * @returns The read value.
   */
  readInt16() {
    const value = this._data.getInt16(this.offset, this.littleEndian);
    this.offset += 2;
    return value;
  }
  /**
   * Read a 16-bit unsigned integer and move pointer forward by 2 bytes.
   * @returns The read value.
   */
  readUint16() {
    const value = this._data.getUint16(this.offset, this.littleEndian);
    this.offset += 2;
    return value;
  }
  /**
   * Read a 32-bit signed integer and move pointer forward by 4 bytes.
   * @returns The read value.
   */
  readInt32() {
    const value = this._data.getInt32(this.offset, this.littleEndian);
    this.offset += 4;
    return value;
  }
  /**
   * Read a 32-bit unsigned integer and move pointer forward by 4 bytes.
   * @returns The read value.
   */
  readUint32() {
    const value = this._data.getUint32(this.offset, this.littleEndian);
    this.offset += 4;
    return value;
  }
  /**
   * Read a 32-bit floating number and move pointer forward by 4 bytes.
   * @returns The read value.
   */
  readFloat32() {
    const value = this._data.getFloat32(this.offset, this.littleEndian);
    this.offset += 4;
    return value;
  }
  /**
   * Read a 64-bit floating number and move pointer forward by 8 bytes.
   * @returns The read value.
   */
  readFloat64() {
    const value = this._data.getFloat64(this.offset, this.littleEndian);
    this.offset += 8;
    return value;
  }
  /**
   * Read a 64-bit signed integer number and move pointer forward by 8 bytes.
   * @returns The read value.
   */
  readBigInt64() {
    const value = this._data.getBigInt64(this.offset, this.littleEndian);
    this.offset += 8;
    return value;
  }
  /**
   * Read a 64-bit unsigned integer number and move pointer forward by 8 bytes.
   * @returns The read value.
   */
  readBigUint64() {
    const value = this._data.getBigUint64(this.offset, this.littleEndian);
    this.offset += 8;
    return value;
  }
  /**
   * Read a 1-byte ASCII character and move pointer forward by 1 byte.
   * @returns The read character.
   */
  readChar() {
    // eslint-disable-next-line unicorn/prefer-code-point
    return String.fromCharCode(this.readInt8());
  }
  /**
   * Read `n` 1-byte ASCII characters and move pointer forward by `n` bytes.
   * @param n - Number of characters to read.
   * @returns The read characters.
   */
  readChars(n = 1) {
    let result = '';
    for (let i = 0; i < n; i++) {
      result += this.readChar();
    }
    return result;
  }
  /**
   * Read the next `n` bytes, return a UTF-8 decoded string and move pointer
   * forward by `n` bytes.
   * @param n - Number of bytes to read.
   * @returns The decoded string.
   */
  readUtf8(n = 1) {
    return decode$4(this.readBytes(n));
  }
  /**
   * Read the next `n` bytes, return a string decoded with `encoding` and move pointer
   * forward by `n` bytes.
   * If no encoding is passed, the function is equivalent to @see {@link IOBuffer#readUtf8}
   * @param n - Number of bytes to read.
   * @param encoding - The encoding to use. Default is 'utf8'.
   * @returns The decoded string.
   */
  decodeText(n = 1, encoding = 'utf8') {
    return decode$4(this.readBytes(n), encoding);
  }
  /**
   * Write 0xff if the passed value is truthy, 0x00 otherwise and move pointer
   * forward by 1 byte.
   * @param value - The value to write.
   * @returns This.
   */
  writeBoolean(value) {
    this.writeUint8(value ? 0xff : 0x00);
    return this;
  }
  /**
   * Write `value` as an 8-bit signed integer and move pointer forward by 1 byte.
   * @param value - The value to write.
   * @returns This.
   */
  writeInt8(value) {
    this.ensureAvailable(1);
    this._data.setInt8(this.offset++, value);
    this._updateLastWrittenByte();
    return this;
  }
  /**
   * Write `value` as an 8-bit unsigned integer and move pointer forward by 1
   * byte.
   * @param value - The value to write.
   * @returns This.
   */
  writeUint8(value) {
    this.ensureAvailable(1);
    this._data.setUint8(this.offset++, value);
    this._updateLastWrittenByte();
    return this;
  }
  /**
   * An alias for {@link IOBuffer#writeUint8}.
   * @param value - The value to write.
   * @returns This.
   */
  writeByte(value) {
    return this.writeUint8(value);
  }
  /**
   * Write all elements of `bytes` as uint8 values and move pointer forward by
   * `bytes.length` bytes.
   * @param bytes - The array of bytes to write.
   * @returns This.
   */
  writeBytes(bytes) {
    this.ensureAvailable(bytes.length);
    // eslint-disable-next-line @typescript-eslint/prefer-for-of
    for (let i = 0; i < bytes.length; i++) {
      this._data.setUint8(this.offset++, bytes[i]);
    }
    this._updateLastWrittenByte();
    return this;
  }
  /**
   * Write `value` as a 16-bit signed integer and move pointer forward by 2
   * bytes.
   * @param value - The value to write.
   * @returns This.
   */
  writeInt16(value) {
    this.ensureAvailable(2);
    this._data.setInt16(this.offset, value, this.littleEndian);
    this.offset += 2;
    this._updateLastWrittenByte();
    return this;
  }
  /**
   * Write `value` as a 16-bit unsigned integer and move pointer forward by 2
   * bytes.
   * @param value - The value to write.
   * @returns This.
   */
  writeUint16(value) {
    this.ensureAvailable(2);
    this._data.setUint16(this.offset, value, this.littleEndian);
    this.offset += 2;
    this._updateLastWrittenByte();
    return this;
  }
  /**
   * Write `value` as a 32-bit signed integer and move pointer forward by 4
   * bytes.
   * @param value - The value to write.
   * @returns This.
   */
  writeInt32(value) {
    this.ensureAvailable(4);
    this._data.setInt32(this.offset, value, this.littleEndian);
    this.offset += 4;
    this._updateLastWrittenByte();
    return this;
  }
  /**
   * Write `value` as a 32-bit unsigned integer and move pointer forward by 4
   * bytes.
   * @param value - The value to write.
   * @returns This.
   */
  writeUint32(value) {
    this.ensureAvailable(4);
    this._data.setUint32(this.offset, value, this.littleEndian);
    this.offset += 4;
    this._updateLastWrittenByte();
    return this;
  }
  /**
   * Write `value` as a 32-bit floating number and move pointer forward by 4
   * bytes.
   * @param value - The value to write.
   * @returns This.
   */
  writeFloat32(value) {
    this.ensureAvailable(4);
    this._data.setFloat32(this.offset, value, this.littleEndian);
    this.offset += 4;
    this._updateLastWrittenByte();
    return this;
  }
  /**
   * Write `value` as a 64-bit floating number and move pointer forward by 8
   * bytes.
   * @param value - The value to write.
   * @returns This.
   */
  writeFloat64(value) {
    this.ensureAvailable(8);
    this._data.setFloat64(this.offset, value, this.littleEndian);
    this.offset += 8;
    this._updateLastWrittenByte();
    return this;
  }
  /**
   * Write `value` as a 64-bit signed bigint and move pointer forward by 8
   * bytes.
   * @param value - The value to write.
   * @returns This.
   */
  writeBigInt64(value) {
    this.ensureAvailable(8);
    this._data.setBigInt64(this.offset, value, this.littleEndian);
    this.offset += 8;
    this._updateLastWrittenByte();
    return this;
  }
  /**
   * Write `value` as a 64-bit unsigned bigint and move pointer forward by 8
   * bytes.
   * @param value - The value to write.
   * @returns This.
   */
  writeBigUint64(value) {
    this.ensureAvailable(8);
    this._data.setBigUint64(this.offset, value, this.littleEndian);
    this.offset += 8;
    this._updateLastWrittenByte();
    return this;
  }
  /**
   * Write the charCode of `str`'s first character as an 8-bit unsigned integer
   * and move pointer forward by 1 byte.
   * @param str - The character to write.
   * @returns This.
   */
  writeChar(str) {
    // eslint-disable-next-line unicorn/prefer-code-point
    return this.writeUint8(str.charCodeAt(0));
  }
  /**
   * Write the charCodes of all `str`'s characters as 8-bit unsigned integers
   * and move pointer forward by `str.length` bytes.
   * @param str - The characters to write.
   * @returns This.
   */
  writeChars(str) {
    for (let i = 0; i < str.length; i++) {
      // eslint-disable-next-line unicorn/prefer-code-point
      this.writeUint8(str.charCodeAt(i));
    }
    return this;
  }
  /**
   * UTF-8 encode and write `str` to the current pointer offset and move pointer
   * forward according to the encoded length.
   * @param str - The string to write.
   * @returns This.
   */
  writeUtf8(str) {
    return this.writeBytes(encode$3(str));
  }
  /**
   * Export a Uint8Array view of the internal buffer.
   * The view starts at the byte offset and its length
   * is calculated to stop at the last written byte or the original length.
   * @returns A new Uint8Array view.
   */
  toArray() {
    return new Uint8Array(this.buffer, this.byteOffset, this.lastWrittenByte);
  }
  /**
   *  Get the total number of bytes written so far, regardless of the current offset.
   * @returns - Total number of bytes.
   */
  getWrittenByteLength() {
    return this.lastWrittenByte - this.byteOffset;
  }
  /**
   * Update the last written byte offset
   * @private
   */
  _updateLastWrittenByte() {
    if (this.offset > this.lastWrittenByte) {
      this.lastWrittenByte = this.offset;
    }
  }
}

class BMPDecoder {
  bufferData;
  pixelDataOffset;
  width;
  height;
  bitsPerPixel;
  xPixelsPerMeter;
  yPixelsPerMeter;
  compression;
  colorMasks;
  constructor(bufferData) {
    this.bufferData = new IOBuffer(bufferData);
    const formatCheck = this.bufferData.readBytes(2);
    if (formatCheck[0] !== 0x42 && formatCheck[1] !== 0x4d) {
      throw new Error('This is not a BMP image or the encoding is not correct.');
    }
    this.pixelDataOffset = this.bufferData.skip(8).readUint32();
    this.width = this.bufferData.skip(4).readUint32();
    this.height = this.bufferData.readUint32();
    this.bitsPerPixel = this.bufferData.seek(28).readUint16();
    if (this.bitsPerPixel !== 1 && this.bitsPerPixel !== 8 && this.bitsPerPixel !== 24 && this.bitsPerPixel !== 32) {
      throw new Error(`Invalid number of bits per pixel. Supported number of bits per pixel: 1, 8, 24, 32. Received: ${this.bitsPerPixel}`);
    }
    this.compression = this.bufferData.readUint32();
    if (this.compression !== 0 && this.compression !== 3) {
      throw new Error(`Only BI_RGB and BI_BITFIELDS compression methods are allowed. `);
    }
    this.colorMasks = [this.bufferData.seek(54).readUint32(), this.bufferData.readUint32(), this.bufferData.readUint32()];
    if (this.bitsPerPixel === 32 && (this.colorMasks[0] !== 0x00ff0000 || this.colorMasks[1] !== 0x0000ff00 || this.colorMasks[2] !== 0x000000ff)) {
      throw new Error(`Unsupported color masks detected in 32-bit BMP image. Only standard RGBA (${0x00ff0000.toString(16)}, ${0x0000ff00.toString(16)}, ${0x000000ff.toString(16)}) masks are supported. Received: ${this.colorMasks[0].toString(16)},${this.colorMasks[1].toString(16)},${this.colorMasks[2].toString(16)}.`);
    }
    this.bufferData.skip(1); // skipping image size.
    this.xPixelsPerMeter = this.bufferData.seek(38).readInt32();
    this.yPixelsPerMeter = this.bufferData.readInt32();
    this.bufferData.skip(1);
  }
  decode() {
    this.bufferData.seek(this.pixelDataOffset);
    this.bufferData.setBigEndian();
    const channels = Math.ceil(this.bitsPerPixel / 8);
    const components = channels % 2 === 0 ? channels - 1 : channels;
    const data = this.decodePixelData(channels, components);
    return {
      width: this.width,
      height: this.height,
      bitsPerPixel: this.bitsPerPixel,
      compression: this.compression,
      colorMasks: this.colorMasks,
      channels,
      components,
      data,
      yPixelsPerMeter: this.yPixelsPerMeter,
      xPixelsPerMeter: this.xPixelsPerMeter
    };
  }
  decodePixelData(channels, components) {
    const data = new Uint8Array(this.height * this.width * channels);
    if (this.bitsPerPixel === 1) {
      this.decodeBitDepth1Pixels(data);
    } else if (channels === components) {
      this.decodeStandardPixels(data, channels);
    } else {
      this.decodePixelsWithAlpha(data, channels, components);
    }
    return data;
  }
  decodeBitDepth1Pixels(data) {
    let currentNumber = 0;
    for (let row = 0; row < this.height; row++) {
      for (let col = 0; col < this.width; col++) {
        const bitIndex = col % 32;
        if (bitIndex === 0) {
          currentNumber = this.bufferData.readUint32();
        }
        if (currentNumber & 1 << 31 - bitIndex) {
          data[(this.height - row - 1) * this.width + col] = 1;
        }
      }
    }
  }
  decodeStandardPixels(data, channels) {
    const padding = this.calculatePadding(channels);
    for (let row = 0; row < this.height; row++) {
      const rowOffset = (this.height - row - 1) * this.width;
      for (let col = 0; col < this.width; col++) {
        for (let channel = channels - 1; channel >= 0; channel--) {
          data[(rowOffset + col) * channels + channel] = this.bufferData.readByte();
        }
      }
      this.bufferData.skip(padding);
    }
  }
  decodePixelsWithAlpha(data, channels, components) {
    for (let row = 0; row < this.height; row++) {
      const rowOffset = (this.height - row - 1) * this.width;
      for (let col = 0; col < this.width; col++) {
        const pixelBaseIndex = (rowOffset + col) * channels;
        // Decode color components
        for (let component = components - 1; component >= 0; component--) {
          data[pixelBaseIndex + component] = this.bufferData.readByte();
        }
        // Decode alpha channel
        data[pixelBaseIndex + components] = this.bufferData.readByte();
      }
    }
  }
  calculatePadding(channels) {
    return this.width * channels % 4 === 0 ? 0 : 4 - this.width * channels % 4;
  }
}

const BITMAPV5HEADER = {
  LogicalColorSpace: {
    LCS_sRGB: 0x73524742},
  GamutMappingIntent: {
    LCS_GM_GRAPHICS: 0x00000002},
  // legacy resolution (72 dpi)
  DEFAULT_PIXELS_PER_METER: 2835
};

class BMPEncoder {
  width;
  height;
  bitsPerPixel;
  channels;
  components;
  data;
  xPixelsPerMeter;
  yPixelsPerMeter;
  encoded = new IOBuffer();
  compression;
  colorMasks;
  constructor(data) {
    if (!data.height || !data.width) {
      throw new Error('ImageData width and height are required.');
    }
    this.data = data.data;
    this.width = data.width;
    this.height = data.height;
    if (this.data.length !== data.width * data.height * data.channels) {
      throw new Error('Invalid data length.');
    }
    this.bitsPerPixel = data.bitsPerPixel;
    if (this.bitsPerPixel !== 1 && this.bitsPerPixel !== 8 && this.bitsPerPixel !== 24 && this.bitsPerPixel !== 32) {
      throw new Error(`Invalid number of bits per pixel. Supported number of bits per pixel: 1, 8, 24, 32. Received: ${this.bitsPerPixel}`);
    }
    this.channels = data.channels;
    this.components = this.channels % 2 === 0 ? this.channels - 1 : this.channels;
    this.xPixelsPerMeter = data.xPixelsPerMeter ?? BITMAPV5HEADER.DEFAULT_PIXELS_PER_METER;
    this.yPixelsPerMeter = data.yPixelsPerMeter ?? BITMAPV5HEADER.DEFAULT_PIXELS_PER_METER;
    this.compression = data.compression ?? 0;
    this.colorMasks = data.colorMasks ?? [0x00ff0000, 0x0000ff00, 0x000000ff];
  }
  encode() {
    this.encoded = new IOBuffer();
    this.encoded.skip(14);
    this.writeBitmapV5Header();
    if (this.bitsPerPixel <= 8) {
      this.writeColorTable();
    }
    const offset = this.encoded.offset;
    this.writePixelArray();
    const imageSize = this.encoded.getWrittenByteLength();
    this.encoded.rewind();
    this.writeBitmapFileHeader(offset, imageSize);
    return this.encoded.toArray();
  }
  writePixelArray() {
    this.encoded.setBigEndian();
    if (this.bitsPerPixel === 1) {
      this.writeBitDepth1Pixels();
    } else if (this.channels === this.components) {
      this.writeStandardPixels();
    } else {
      this.writePixelsWithAlpha();
    }
    this.encoded.setLittleEndian();
  }
  writeBitDepth1Pixels() {
    let byte = 0;
    for (let row = this.height - 1; row >= 0; row--) {
      for (let col = 0; col < this.width; col++) {
        if (col % 32 === 0 && col !== 0) {
          this.encoded.writeUint32(byte);
          byte = 0;
        }
        byte |= this.data[row * this.width + col] << 31 - col % 32;
      }
      this.encoded.writeUint32(byte);
      byte = 0;
    }
  }
  writeStandardPixels() {
    for (let row = 0; row < this.height; row++) {
      const rowOffset = this.width * (this.height - row - 1) * this.channels;
      for (let col = 0; col < this.width; col++) {
        for (let channel = this.channels - 1; channel >= 0; channel--) {
          this.encoded.writeByte(this.data[rowOffset + col * this.channels + channel]);
        }
      }
      this.writePadding();
    }
  }
  writePixelsWithAlpha() {
    const pixel = 0;
    for (let row = 0; row < this.height; row++) {
      const rowOffset = this.width * (this.height - row - 1);
      for (let col = 0; col < this.width; col++) {
        const pixelIndex = (rowOffset + col) * this.channels;
        this.encoded.writeUint32(pixel | this.data[pixelIndex + 2] << 3 * 8 | this.data[pixelIndex + 1] << 2 * 8 | this.data[pixelIndex] << 8 | this.data[pixelIndex + 3]);
      }
    }
  }
  writePadding() {
    const padding = this.width * this.channels % 4 === 0 ? 0 : 4 - this.width * this.channels % 4;
    for (let i = 0; i < padding; i++) {
      this.encoded.writeByte(0);
    }
  }
  writeColorTable() {
    if (this.bitsPerPixel === 1) {
      this.encoded.writeUint32(0x00000000) // black
      .writeUint32(0x00ffffff); // white
    } else {
      //Grayscale 8 bit
      for (let i = 0; i < 256; i++) {
        this.encoded.writeUint32(0x00000000 | i << 4 * 4 | i << 2 * 4 | i);
      }
    }
  }
  writeBitmapFileHeader(imageOffset, fileSize) {
    this.encoded.writeChars('BM') // 14 bytes bitmap file header
    .writeInt32(fileSize) // Size of BMP file in bytes
    .writeUint16(0).writeUint16(0).writeUint32(imageOffset);
  }
  writeBitmapV5Header() {
    const rowSize = Math.floor((this.bitsPerPixel * this.width + 31) / 32) * 4;
    const totalBytes = rowSize * this.height;
    // Size of the header
    this.encoded.writeUint32(124) // Header size, offset 14
    .writeInt32(this.width) // bV5Width, offset 18
    .writeInt32(this.height) // bV5Height, offset 22
    .writeUint16(1) // bv5Planes - must be set to 1, offset 26
    .writeUint16(this.bitsPerPixel) // bV5BitCount, offset 30
    .writeUint32(this.compression) // bV5Compression - No compression, offset 34
    .writeUint32(totalBytes) // bv5SizeImage - size of pixel buffer (can be 0 if uncompressed), offset 38
    .writeInt32(this.xPixelsPerMeter) // bV5XPelsPerMeter - resolution, offset 42
    .writeInt32(this.yPixelsPerMeter) // bV5YPelsPerMeter - resolution, offset 46
    .writeUint32(this.bitsPerPixel <= 8 ? 2 ** this.bitsPerPixel : 0) // number of colors used, set to 0 if number of pixels is bigger than 8 set to 0, offset 50
    .writeUint32(this.bitsPerPixel <= 8 ? 2 ** this.bitsPerPixel : 0); // number of important colors, set to 0 if number of pixels is bigger than 8 set to 0,  offset 54
    if (this.bitsPerPixel === 32 && (this.colorMasks[0] !== 0x00ff0000 || this.colorMasks[1] !== 0x0000ff00 || this.colorMasks[2] !== 0x000000ff)) {
      throw new Error(`Unsupported color masks detected in 32-bit BMP image. Only standard RGBA (${0x00ff0000.toString(16)}, ${0x0000ff00.toString(16)}, ${0x000000ff.toString(16)}) masks are supported. Received: ${this.colorMasks[0].toString(16)},${this.colorMasks[1].toString(16)},${this.colorMasks[2].toString(16)}.`);
    }
    this.encoded.writeUint32(this.colorMasks[0]) // bV5RedMask, offset 58
    .writeUint32(this.colorMasks[1]) // bV5GreenMask, offset 62
    .writeUint32(this.colorMasks[2]) // bV5BlueMask, offset 66
    .writeUint32(this.channels === this.components ? 0x00000000 : 0xff000000) // bv5ReservedData
    .writeUint32(BITMAPV5HEADER.LogicalColorSpace.LCS_sRGB).skip(36) // bV5Endpoints
    .skip(12) // bV5GammaRed, Green, Blue
    .writeUint32(BITMAPV5HEADER.GamutMappingIntent.LCS_GM_GRAPHICS).skip(12); // ProfileData, ProfileSize, Reserved
  }
}

/**
 * Encodes data into BMP format.
 * @param data - Data for encoding.
 * @returns typed array buffer.
 */
function encode$2(data) {
  const encoder = new BMPEncoder(data);
  return encoder.encode();
}
/**
 * Decodes BMP format image into data.
 * @param data - Buffer with image data.
 * @returns - Decoded data.
 */
function decode$3(data) {
  const decoder = new BMPDecoder(data);
  return decoder.decode();
}

/**
 * Creates a BMP buffer from a mask.
 * @param image - The mask instance.
 * @returns The buffer.
 */
function encodeBmp(image) {
  if (image instanceof Image) {
    return encode$2({
      width: image.width,
      height: image.height,
      components: image.components,
      bitsPerPixel: image.channels * image.bitDepth,
      channels: image.channels,
      data: image.getRawImage().data
    });
  } else {
    return encode$2({
      width: image.width,
      height: image.height,
      components: 1,
      bitsPerPixel: 1,
      channels: 1,
      data: image.getRawImage().data
    });
  }
}

var encoder = {exports: {}};

/*
  Copyright (c) 2008, Adobe Systems Incorporated
  All rights reserved.

  Redistribution and use in source and binary forms, with or without 
  modification, are permitted provided that the following conditions are
  met:

  * Redistributions of source code must retain the above copyright notice, 
    this list of conditions and the following disclaimer.
  
  * Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in the 
    documentation and/or other materials provided with the distribution.
  
  * Neither the name of Adobe Systems Incorporated nor the names of its 
    contributors may be used to endorse or promote products derived from 
    this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 
  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
(function (module) {
  function JPEGEncoder(quality) {
    var ffloor = Math.floor;
    var YTable = new Array(64);
    var UVTable = new Array(64);
    var fdtbl_Y = new Array(64);
    var fdtbl_UV = new Array(64);
    var YDC_HT;
    var UVDC_HT;
    var YAC_HT;
    var UVAC_HT;
    var bitcode = new Array(65535);
    var category = new Array(65535);
    var outputfDCTQuant = new Array(64);
    var DU = new Array(64);
    var byteout = [];
    var bytenew = 0;
    var bytepos = 7;
    var YDU = new Array(64);
    var UDU = new Array(64);
    var VDU = new Array(64);
    var clt = new Array(256);
    var RGB_YUV_TABLE = new Array(2048);
    var currentQuality;
    var ZigZag = [0, 1, 5, 6, 14, 15, 27, 28, 2, 4, 7, 13, 16, 26, 29, 42, 3, 8, 12, 17, 25, 30, 41, 43, 9, 11, 18, 24, 31, 40, 44, 53, 10, 19, 23, 32, 39, 45, 52, 54, 20, 22, 33, 38, 46, 51, 55, 60, 21, 34, 37, 47, 50, 56, 59, 61, 35, 36, 48, 49, 57, 58, 62, 63];
    var std_dc_luminance_nrcodes = [0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0];
    var std_dc_luminance_values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
    var std_ac_luminance_nrcodes = [0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d];
    var std_ac_luminance_values = [0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07, 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08, 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0, 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa];
    var std_dc_chrominance_nrcodes = [0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0];
    var std_dc_chrominance_values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
    var std_ac_chrominance_nrcodes = [0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77];
    var std_ac_chrominance_values = [0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71, 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91, 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0, 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34, 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa];
    function initQuantTables(sf) {
      var YQT = [16, 11, 10, 16, 24, 40, 51, 61, 12, 12, 14, 19, 26, 58, 60, 55, 14, 13, 16, 24, 40, 57, 69, 56, 14, 17, 22, 29, 51, 87, 80, 62, 18, 22, 37, 56, 68, 109, 103, 77, 24, 35, 55, 64, 81, 104, 113, 92, 49, 64, 78, 87, 103, 121, 120, 101, 72, 92, 95, 98, 112, 100, 103, 99];
      for (var i = 0; i < 64; i++) {
        var t = ffloor((YQT[i] * sf + 50) / 100);
        if (t < 1) {
          t = 1;
        } else if (t > 255) {
          t = 255;
        }
        YTable[ZigZag[i]] = t;
      }
      var UVQT = [17, 18, 24, 47, 99, 99, 99, 99, 18, 21, 26, 66, 99, 99, 99, 99, 24, 26, 56, 99, 99, 99, 99, 99, 47, 66, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99];
      for (var j = 0; j < 64; j++) {
        var u = ffloor((UVQT[j] * sf + 50) / 100);
        if (u < 1) {
          u = 1;
        } else if (u > 255) {
          u = 255;
        }
        UVTable[ZigZag[j]] = u;
      }
      var aasf = [1.0, 1.387039845, 1.306562965, 1.175875602, 1.0, 0.785694958, 0.541196100, 0.275899379];
      var k = 0;
      for (var row = 0; row < 8; row++) {
        for (var col = 0; col < 8; col++) {
          fdtbl_Y[k] = 1.0 / (YTable[ZigZag[k]] * aasf[row] * aasf[col] * 8.0);
          fdtbl_UV[k] = 1.0 / (UVTable[ZigZag[k]] * aasf[row] * aasf[col] * 8.0);
          k++;
        }
      }
    }
    function computeHuffmanTbl(nrcodes, std_table) {
      var codevalue = 0;
      var pos_in_table = 0;
      var HT = new Array();
      for (var k = 1; k <= 16; k++) {
        for (var j = 1; j <= nrcodes[k]; j++) {
          HT[std_table[pos_in_table]] = [];
          HT[std_table[pos_in_table]][0] = codevalue;
          HT[std_table[pos_in_table]][1] = k;
          pos_in_table++;
          codevalue++;
        }
        codevalue *= 2;
      }
      return HT;
    }
    function initHuffmanTbl() {
      YDC_HT = computeHuffmanTbl(std_dc_luminance_nrcodes, std_dc_luminance_values);
      UVDC_HT = computeHuffmanTbl(std_dc_chrominance_nrcodes, std_dc_chrominance_values);
      YAC_HT = computeHuffmanTbl(std_ac_luminance_nrcodes, std_ac_luminance_values);
      UVAC_HT = computeHuffmanTbl(std_ac_chrominance_nrcodes, std_ac_chrominance_values);
    }
    function initCategoryNumber() {
      var nrlower = 1;
      var nrupper = 2;
      for (var cat = 1; cat <= 15; cat++) {
        //Positive numbers
        for (var nr = nrlower; nr < nrupper; nr++) {
          category[32767 + nr] = cat;
          bitcode[32767 + nr] = [];
          bitcode[32767 + nr][1] = cat;
          bitcode[32767 + nr][0] = nr;
        }
        //Negative numbers
        for (var nrneg = -(nrupper - 1); nrneg <= -nrlower; nrneg++) {
          category[32767 + nrneg] = cat;
          bitcode[32767 + nrneg] = [];
          bitcode[32767 + nrneg][1] = cat;
          bitcode[32767 + nrneg][0] = nrupper - 1 + nrneg;
        }
        nrlower <<= 1;
        nrupper <<= 1;
      }
    }
    function initRGBYUVTable() {
      for (var i = 0; i < 256; i++) {
        RGB_YUV_TABLE[i] = 19595 * i;
        RGB_YUV_TABLE[i + 256 >> 0] = 38470 * i;
        RGB_YUV_TABLE[i + 512 >> 0] = 7471 * i + 0x8000;
        RGB_YUV_TABLE[i + 768 >> 0] = -11059 * i;
        RGB_YUV_TABLE[i + 1024 >> 0] = -21709 * i;
        RGB_YUV_TABLE[i + 1280 >> 0] = 32768 * i + 0x807FFF;
        RGB_YUV_TABLE[i + 1536 >> 0] = -27439 * i;
        RGB_YUV_TABLE[i + 1792 >> 0] = -5329 * i;
      }
    }

    // IO functions
    function writeBits(bs) {
      var value = bs[0];
      var posval = bs[1] - 1;
      while (posval >= 0) {
        if (value & 1 << posval) {
          bytenew |= 1 << bytepos;
        }
        posval--;
        bytepos--;
        if (bytepos < 0) {
          if (bytenew == 0xFF) {
            writeByte(0xFF);
            writeByte(0);
          } else {
            writeByte(bytenew);
          }
          bytepos = 7;
          bytenew = 0;
        }
      }
    }
    function writeByte(value) {
      //byteout.push(clt[value]); // write char directly instead of converting later
      byteout.push(value);
    }
    function writeWord(value) {
      writeByte(value >> 8 & 0xFF);
      writeByte(value & 0xFF);
    }

    // DCT & quantization core
    function fDCTQuant(data, fdtbl) {
      var d0, d1, d2, d3, d4, d5, d6, d7;
      /* Pass 1: process rows. */
      var dataOff = 0;
      var i;
      var I8 = 8;
      var I64 = 64;
      for (i = 0; i < I8; ++i) {
        d0 = data[dataOff];
        d1 = data[dataOff + 1];
        d2 = data[dataOff + 2];
        d3 = data[dataOff + 3];
        d4 = data[dataOff + 4];
        d5 = data[dataOff + 5];
        d6 = data[dataOff + 6];
        d7 = data[dataOff + 7];
        var tmp0 = d0 + d7;
        var tmp7 = d0 - d7;
        var tmp1 = d1 + d6;
        var tmp6 = d1 - d6;
        var tmp2 = d2 + d5;
        var tmp5 = d2 - d5;
        var tmp3 = d3 + d4;
        var tmp4 = d3 - d4;

        /* Even part */
        var tmp10 = tmp0 + tmp3; /* phase 2 */
        var tmp13 = tmp0 - tmp3;
        var tmp11 = tmp1 + tmp2;
        var tmp12 = tmp1 - tmp2;
        data[dataOff] = tmp10 + tmp11; /* phase 3 */
        data[dataOff + 4] = tmp10 - tmp11;
        var z1 = (tmp12 + tmp13) * 0.707106781; /* c4 */
        data[dataOff + 2] = tmp13 + z1; /* phase 5 */
        data[dataOff + 6] = tmp13 - z1;

        /* Odd part */
        tmp10 = tmp4 + tmp5; /* phase 2 */
        tmp11 = tmp5 + tmp6;
        tmp12 = tmp6 + tmp7;

        /* The rotator is modified from fig 4-8 to avoid extra negations. */
        var z5 = (tmp10 - tmp12) * 0.382683433; /* c6 */
        var z2 = 0.541196100 * tmp10 + z5; /* c2-c6 */
        var z4 = 1.306562965 * tmp12 + z5; /* c2+c6 */
        var z3 = tmp11 * 0.707106781; /* c4 */

        var z11 = tmp7 + z3; /* phase 5 */
        var z13 = tmp7 - z3;
        data[dataOff + 5] = z13 + z2; /* phase 6 */
        data[dataOff + 3] = z13 - z2;
        data[dataOff + 1] = z11 + z4;
        data[dataOff + 7] = z11 - z4;
        dataOff += 8; /* advance pointer to next row */
      }

      /* Pass 2: process columns. */
      dataOff = 0;
      for (i = 0; i < I8; ++i) {
        d0 = data[dataOff];
        d1 = data[dataOff + 8];
        d2 = data[dataOff + 16];
        d3 = data[dataOff + 24];
        d4 = data[dataOff + 32];
        d5 = data[dataOff + 40];
        d6 = data[dataOff + 48];
        d7 = data[dataOff + 56];
        var tmp0p2 = d0 + d7;
        var tmp7p2 = d0 - d7;
        var tmp1p2 = d1 + d6;
        var tmp6p2 = d1 - d6;
        var tmp2p2 = d2 + d5;
        var tmp5p2 = d2 - d5;
        var tmp3p2 = d3 + d4;
        var tmp4p2 = d3 - d4;

        /* Even part */
        var tmp10p2 = tmp0p2 + tmp3p2; /* phase 2 */
        var tmp13p2 = tmp0p2 - tmp3p2;
        var tmp11p2 = tmp1p2 + tmp2p2;
        var tmp12p2 = tmp1p2 - tmp2p2;
        data[dataOff] = tmp10p2 + tmp11p2; /* phase 3 */
        data[dataOff + 32] = tmp10p2 - tmp11p2;
        var z1p2 = (tmp12p2 + tmp13p2) * 0.707106781; /* c4 */
        data[dataOff + 16] = tmp13p2 + z1p2; /* phase 5 */
        data[dataOff + 48] = tmp13p2 - z1p2;

        /* Odd part */
        tmp10p2 = tmp4p2 + tmp5p2; /* phase 2 */
        tmp11p2 = tmp5p2 + tmp6p2;
        tmp12p2 = tmp6p2 + tmp7p2;

        /* The rotator is modified from fig 4-8 to avoid extra negations. */
        var z5p2 = (tmp10p2 - tmp12p2) * 0.382683433; /* c6 */
        var z2p2 = 0.541196100 * tmp10p2 + z5p2; /* c2-c6 */
        var z4p2 = 1.306562965 * tmp12p2 + z5p2; /* c2+c6 */
        var z3p2 = tmp11p2 * 0.707106781; /* c4 */

        var z11p2 = tmp7p2 + z3p2; /* phase 5 */
        var z13p2 = tmp7p2 - z3p2;
        data[dataOff + 40] = z13p2 + z2p2; /* phase 6 */
        data[dataOff + 24] = z13p2 - z2p2;
        data[dataOff + 8] = z11p2 + z4p2;
        data[dataOff + 56] = z11p2 - z4p2;
        dataOff++; /* advance pointer to next column */
      }

      // Quantize/descale the coefficients
      var fDCTQuant;
      for (i = 0; i < I64; ++i) {
        // Apply the quantization and scaling factor & Round to nearest integer
        fDCTQuant = data[i] * fdtbl[i];
        outputfDCTQuant[i] = fDCTQuant > 0.0 ? fDCTQuant + 0.5 | 0 : fDCTQuant - 0.5 | 0;
        //outputfDCTQuant[i] = fround(fDCTQuant);
      }
      return outputfDCTQuant;
    }
    function writeAPP0() {
      writeWord(0xFFE0); // marker
      writeWord(16); // length
      writeByte(0x4A); // J
      writeByte(0x46); // F
      writeByte(0x49); // I
      writeByte(0x46); // F
      writeByte(0); // = "JFIF",'\0'
      writeByte(1); // versionhi
      writeByte(1); // versionlo
      writeByte(0); // xyunits
      writeWord(1); // xdensity
      writeWord(1); // ydensity
      writeByte(0); // thumbnwidth
      writeByte(0); // thumbnheight
    }
    function writeAPP1(exifBuffer) {
      if (!exifBuffer) return;
      writeWord(0xFFE1); // APP1 marker

      if (exifBuffer[0] === 0x45 && exifBuffer[1] === 0x78 && exifBuffer[2] === 0x69 && exifBuffer[3] === 0x66) {
        // Buffer already starts with EXIF, just use it directly
        writeWord(exifBuffer.length + 2); // length is buffer + length itself!
      } else {
        // Buffer doesn't start with EXIF, write it for them
        writeWord(exifBuffer.length + 5 + 2); // length is buffer + EXIF\0 + length itself!
        writeByte(0x45); // E
        writeByte(0x78); // X
        writeByte(0x69); // I
        writeByte(0x66); // F
        writeByte(0); // = "EXIF",'\0'
      }
      for (var i = 0; i < exifBuffer.length; i++) {
        writeByte(exifBuffer[i]);
      }
    }
    function writeSOF0(width, height) {
      writeWord(0xFFC0); // marker
      writeWord(17); // length, truecolor YUV JPG
      writeByte(8); // precision
      writeWord(height);
      writeWord(width);
      writeByte(3); // nrofcomponents
      writeByte(1); // IdY
      writeByte(0x11); // HVY
      writeByte(0); // QTY
      writeByte(2); // IdU
      writeByte(0x11); // HVU
      writeByte(1); // QTU
      writeByte(3); // IdV
      writeByte(0x11); // HVV
      writeByte(1); // QTV
    }
    function writeDQT() {
      writeWord(0xFFDB); // marker
      writeWord(132); // length
      writeByte(0);
      for (var i = 0; i < 64; i++) {
        writeByte(YTable[i]);
      }
      writeByte(1);
      for (var j = 0; j < 64; j++) {
        writeByte(UVTable[j]);
      }
    }
    function writeDHT() {
      writeWord(0xFFC4); // marker
      writeWord(0x01A2); // length

      writeByte(0); // HTYDCinfo
      for (var i = 0; i < 16; i++) {
        writeByte(std_dc_luminance_nrcodes[i + 1]);
      }
      for (var j = 0; j <= 11; j++) {
        writeByte(std_dc_luminance_values[j]);
      }
      writeByte(0x10); // HTYACinfo
      for (var k = 0; k < 16; k++) {
        writeByte(std_ac_luminance_nrcodes[k + 1]);
      }
      for (var l = 0; l <= 161; l++) {
        writeByte(std_ac_luminance_values[l]);
      }
      writeByte(1); // HTUDCinfo
      for (var m = 0; m < 16; m++) {
        writeByte(std_dc_chrominance_nrcodes[m + 1]);
      }
      for (var n = 0; n <= 11; n++) {
        writeByte(std_dc_chrominance_values[n]);
      }
      writeByte(0x11); // HTUACinfo
      for (var o = 0; o < 16; o++) {
        writeByte(std_ac_chrominance_nrcodes[o + 1]);
      }
      for (var p = 0; p <= 161; p++) {
        writeByte(std_ac_chrominance_values[p]);
      }
    }
    function writeCOM(comments) {
      if (typeof comments === "undefined" || comments.constructor !== Array) return;
      comments.forEach(e => {
        if (typeof e !== "string") return;
        writeWord(0xFFFE); // marker
        var l = e.length;
        writeWord(l + 2); // length itself as well
        var i;
        for (i = 0; i < l; i++) writeByte(e.charCodeAt(i));
      });
    }
    function writeSOS() {
      writeWord(0xFFDA); // marker
      writeWord(12); // length
      writeByte(3); // nrofcomponents
      writeByte(1); // IdY
      writeByte(0); // HTY
      writeByte(2); // IdU
      writeByte(0x11); // HTU
      writeByte(3); // IdV
      writeByte(0x11); // HTV
      writeByte(0); // Ss
      writeByte(0x3f); // Se
      writeByte(0); // Bf
    }
    function processDU(CDU, fdtbl, DC, HTDC, HTAC) {
      var EOB = HTAC[0x00];
      var M16zeroes = HTAC[0xF0];
      var pos;
      var I16 = 16;
      var I63 = 63;
      var I64 = 64;
      var DU_DCT = fDCTQuant(CDU, fdtbl);
      //ZigZag reorder
      for (var j = 0; j < I64; ++j) {
        DU[ZigZag[j]] = DU_DCT[j];
      }
      var Diff = DU[0] - DC;
      DC = DU[0];
      //Encode DC
      if (Diff == 0) {
        writeBits(HTDC[0]); // Diff might be 0
      } else {
        pos = 32767 + Diff;
        writeBits(HTDC[category[pos]]);
        writeBits(bitcode[pos]);
      }
      //Encode ACs
      var end0pos = 63; // was const... which is crazy
      for (; end0pos > 0 && DU[end0pos] == 0; end0pos--) {}
      //end0pos = first element in reverse order !=0
      if (end0pos == 0) {
        writeBits(EOB);
        return DC;
      }
      var i = 1;
      var lng;
      while (i <= end0pos) {
        var startpos = i;
        for (; DU[i] == 0 && i <= end0pos; ++i) {}
        var nrzeroes = i - startpos;
        if (nrzeroes >= I16) {
          lng = nrzeroes >> 4;
          for (var nrmarker = 1; nrmarker <= lng; ++nrmarker) writeBits(M16zeroes);
          nrzeroes = nrzeroes & 0xF;
        }
        pos = 32767 + DU[i];
        writeBits(HTAC[(nrzeroes << 4) + category[pos]]);
        writeBits(bitcode[pos]);
        i++;
      }
      if (end0pos != I63) {
        writeBits(EOB);
      }
      return DC;
    }
    function initCharLookupTable() {
      var sfcc = String.fromCharCode;
      for (var i = 0; i < 256; i++) {
        ///// ACHTUNG // 255
        clt[i] = sfcc(i);
      }
    }
    this.encode = function (image, quality)
    // image data object
    {
      new Date().getTime();
      if (quality) setQuality(quality);

      // Initialize bit writer
      byteout = new Array();
      bytenew = 0;
      bytepos = 7;

      // Add JPEG headers
      writeWord(0xFFD8); // SOI
      writeAPP0();
      writeCOM(image.comments);
      writeAPP1(image.exifBuffer);
      writeDQT();
      writeSOF0(image.width, image.height);
      writeDHT();
      writeSOS();

      // Encode 8x8 macroblocks
      var DCY = 0;
      var DCU = 0;
      var DCV = 0;
      bytenew = 0;
      bytepos = 7;
      this.encode.displayName = "_encode_";
      var imageData = image.data;
      var width = image.width;
      var height = image.height;
      var quadWidth = width * 4;
      var x,
        y = 0;
      var r, g, b;
      var start, p, col, row, pos;
      while (y < height) {
        x = 0;
        while (x < quadWidth) {
          start = quadWidth * y + x;
          p = start;
          col = -1;
          row = 0;
          for (pos = 0; pos < 64; pos++) {
            row = pos >> 3; // /8
            col = (pos & 7) * 4; // %8
            p = start + row * quadWidth + col;
            if (y + row >= height) {
              // padding bottom
              p -= quadWidth * (y + 1 + row - height);
            }
            if (x + col >= quadWidth) {
              // padding right	
              p -= x + col - quadWidth + 4;
            }
            r = imageData[p++];
            g = imageData[p++];
            b = imageData[p++];

            /* // calculate YUV values dynamically
            YDU[pos]=((( 0.29900)*r+( 0.58700)*g+( 0.11400)*b))-128; //-0x80
            UDU[pos]=(((-0.16874)*r+(-0.33126)*g+( 0.50000)*b));
            VDU[pos]=((( 0.50000)*r+(-0.41869)*g+(-0.08131)*b));
            */

            // use lookup table (slightly faster)
            YDU[pos] = (RGB_YUV_TABLE[r] + RGB_YUV_TABLE[g + 256 >> 0] + RGB_YUV_TABLE[b + 512 >> 0] >> 16) - 128;
            UDU[pos] = (RGB_YUV_TABLE[r + 768 >> 0] + RGB_YUV_TABLE[g + 1024 >> 0] + RGB_YUV_TABLE[b + 1280 >> 0] >> 16) - 128;
            VDU[pos] = (RGB_YUV_TABLE[r + 1280 >> 0] + RGB_YUV_TABLE[g + 1536 >> 0] + RGB_YUV_TABLE[b + 1792 >> 0] >> 16) - 128;
          }
          DCY = processDU(YDU, fdtbl_Y, DCY, YDC_HT, YAC_HT);
          DCU = processDU(UDU, fdtbl_UV, DCU, UVDC_HT, UVAC_HT);
          DCV = processDU(VDU, fdtbl_UV, DCV, UVDC_HT, UVAC_HT);
          x += 32;
        }
        y += 8;
      }

      ////////////////////////////////////////////////////////////////

      // Do the bit alignment of the EOI marker
      if (bytepos >= 0) {
        var fillbits = [];
        fillbits[1] = bytepos + 1;
        fillbits[0] = (1 << bytepos + 1) - 1;
        writeBits(fillbits);
      }
      writeWord(0xFFD9); //EOI
      return Buffer.from(byteout);
    };
    function setQuality(quality) {
      if (quality <= 0) {
        quality = 1;
      }
      if (quality > 100) {
        quality = 100;
      }
      if (currentQuality == quality) return; // don't recalc if unchanged

      var sf = 0;
      if (quality < 50) {
        sf = Math.floor(5000 / quality);
      } else {
        sf = Math.floor(200 - quality * 2);
      }
      initQuantTables(sf);
      currentQuality = quality;
      //console.log('Quality set to: '+quality +'%');
    }
    function init() {
      var time_start = new Date().getTime();
      if (!quality) quality = 50;
      // Create tables
      initCharLookupTable();
      initHuffmanTbl();
      initCategoryNumber();
      initRGBYUVTable();
      setQuality(quality);
      new Date().getTime() - time_start;
      //console.log('Initialization '+ duration + 'ms');
    }
    init();
  }
  {
    module.exports = encode;
  }
  function encode(imgData, qu) {
    if (typeof qu === 'undefined') qu = 50;
    var encoder = new JPEGEncoder(qu);
    var data = encoder.encode(imgData, qu);
    return {
      data: data,
      width: imgData.width,
      height: imgData.height
    };
  }
})(encoder);
var encoderExports = encoder.exports;

var decoder = {exports: {}};

/* -*- tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- /
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
(function (module) {
  /*
     Copyright 2011 notmasteryet
  	   Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at
  	       http://www.apache.org/licenses/LICENSE-2.0
  	   Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
  */

  // - The JPEG specification can be found in the ITU CCITT Recommendation T.81
  //   (www.w3.org/Graphics/JPEG/itu-t81.pdf)
  // - The JFIF specification can be found in the JPEG File Interchange Format
  //   (www.w3.org/Graphics/JPEG/jfif3.pdf)
  // - The Adobe Application-Specific JPEG markers in the Supporting the DCT Filters
  //   in PostScript Level 2, Technical Note #5116
  //   (partners.adobe.com/public/developer/en/ps/sdk/5116.DCT_Filter.pdf)

  var JpegImage = function jpegImage() {

    var dctZigZag = new Int32Array([0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63]);
    var dctCos1 = 4017; // cos(pi/16)
    var dctSin1 = 799; // sin(pi/16)
    var dctCos3 = 3406; // cos(3*pi/16)
    var dctSin3 = 2276; // sin(3*pi/16)
    var dctCos6 = 1567; // cos(6*pi/16)
    var dctSin6 = 3784; // sin(6*pi/16)
    var dctSqrt2 = 5793; // sqrt(2)
    var dctSqrt1d2 = 2896; // sqrt(2) / 2

    function constructor() {}
    function buildHuffmanTable(codeLengths, values) {
      var k = 0,
        code = [],
        i,
        j,
        length = 16;
      while (length > 0 && !codeLengths[length - 1]) length--;
      code.push({
        children: [],
        index: 0
      });
      var p = code[0],
        q;
      for (i = 0; i < length; i++) {
        for (j = 0; j < codeLengths[i]; j++) {
          p = code.pop();
          p.children[p.index] = values[k];
          while (p.index > 0) {
            if (code.length === 0) throw new Error('Could not recreate Huffman Table');
            p = code.pop();
          }
          p.index++;
          code.push(p);
          while (code.length <= i) {
            code.push(q = {
              children: [],
              index: 0
            });
            p.children[p.index] = q.children;
            p = q;
          }
          k++;
        }
        if (i + 1 < length) {
          // p here points to last code
          code.push(q = {
            children: [],
            index: 0
          });
          p.children[p.index] = q.children;
          p = q;
        }
      }
      return code[0].children;
    }
    function decodeScan(data, offset, frame, components, resetInterval, spectralStart, spectralEnd, successivePrev, successive, opts) {
      frame.precision;
      frame.samplesPerLine;
      frame.scanLines;
      var mcusPerLine = frame.mcusPerLine;
      var progressive = frame.progressive;
      frame.maxH;
        frame.maxV;
      var startOffset = offset,
        bitsData = 0,
        bitsCount = 0;
      function readBit() {
        if (bitsCount > 0) {
          bitsCount--;
          return bitsData >> bitsCount & 1;
        }
        bitsData = data[offset++];
        if (bitsData == 0xFF) {
          var nextByte = data[offset++];
          if (nextByte) {
            throw new Error("unexpected marker: " + (bitsData << 8 | nextByte).toString(16));
          }
          // unstuff 0
        }
        bitsCount = 7;
        return bitsData >>> 7;
      }
      function decodeHuffman(tree) {
        var node = tree,
          bit;
        while ((bit = readBit()) !== null) {
          node = node[bit];
          if (typeof node === 'number') return node;
          if (typeof node !== 'object') throw new Error("invalid huffman sequence");
        }
        return null;
      }
      function receive(length) {
        var n = 0;
        while (length > 0) {
          var bit = readBit();
          if (bit === null) return;
          n = n << 1 | bit;
          length--;
        }
        return n;
      }
      function receiveAndExtend(length) {
        var n = receive(length);
        if (n >= 1 << length - 1) return n;
        return n + (-1 << length) + 1;
      }
      function decodeBaseline(component, zz) {
        var t = decodeHuffman(component.huffmanTableDC);
        var diff = t === 0 ? 0 : receiveAndExtend(t);
        zz[0] = component.pred += diff;
        var k = 1;
        while (k < 64) {
          var rs = decodeHuffman(component.huffmanTableAC);
          var s = rs & 15,
            r = rs >> 4;
          if (s === 0) {
            if (r < 15) break;
            k += 16;
            continue;
          }
          k += r;
          var z = dctZigZag[k];
          zz[z] = receiveAndExtend(s);
          k++;
        }
      }
      function decodeDCFirst(component, zz) {
        var t = decodeHuffman(component.huffmanTableDC);
        var diff = t === 0 ? 0 : receiveAndExtend(t) << successive;
        zz[0] = component.pred += diff;
      }
      function decodeDCSuccessive(component, zz) {
        zz[0] |= readBit() << successive;
      }
      var eobrun = 0;
      function decodeACFirst(component, zz) {
        if (eobrun > 0) {
          eobrun--;
          return;
        }
        var k = spectralStart,
          e = spectralEnd;
        while (k <= e) {
          var rs = decodeHuffman(component.huffmanTableAC);
          var s = rs & 15,
            r = rs >> 4;
          if (s === 0) {
            if (r < 15) {
              eobrun = receive(r) + (1 << r) - 1;
              break;
            }
            k += 16;
            continue;
          }
          k += r;
          var z = dctZigZag[k];
          zz[z] = receiveAndExtend(s) * (1 << successive);
          k++;
        }
      }
      var successiveACState = 0,
        successiveACNextValue;
      function decodeACSuccessive(component, zz) {
        var k = spectralStart,
          e = spectralEnd,
          r = 0;
        while (k <= e) {
          var z = dctZigZag[k];
          var direction = zz[z] < 0 ? -1 : 1;
          switch (successiveACState) {
            case 0:
              // initial state
              var rs = decodeHuffman(component.huffmanTableAC);
              var s = rs & 15,
                r = rs >> 4;
              if (s === 0) {
                if (r < 15) {
                  eobrun = receive(r) + (1 << r);
                  successiveACState = 4;
                } else {
                  r = 16;
                  successiveACState = 1;
                }
              } else {
                if (s !== 1) throw new Error("invalid ACn encoding");
                successiveACNextValue = receiveAndExtend(s);
                successiveACState = r ? 2 : 3;
              }
              continue;
            case 1: // skipping r zero items
            case 2:
              if (zz[z]) zz[z] += (readBit() << successive) * direction;else {
                r--;
                if (r === 0) successiveACState = successiveACState == 2 ? 3 : 0;
              }
              break;
            case 3:
              // set value for a zero item
              if (zz[z]) zz[z] += (readBit() << successive) * direction;else {
                zz[z] = successiveACNextValue << successive;
                successiveACState = 0;
              }
              break;
            case 4:
              // eob
              if (zz[z]) zz[z] += (readBit() << successive) * direction;
              break;
          }
          k++;
        }
        if (successiveACState === 4) {
          eobrun--;
          if (eobrun === 0) successiveACState = 0;
        }
      }
      function decodeMcu(component, decode, mcu, row, col) {
        var mcuRow = mcu / mcusPerLine | 0;
        var mcuCol = mcu % mcusPerLine;
        var blockRow = mcuRow * component.v + row;
        var blockCol = mcuCol * component.h + col;
        // If the block is missing and we're in tolerant mode, just skip it.
        if (component.blocks[blockRow] === undefined && opts.tolerantDecoding) return;
        decode(component, component.blocks[blockRow][blockCol]);
      }
      function decodeBlock(component, decode, mcu) {
        var blockRow = mcu / component.blocksPerLine | 0;
        var blockCol = mcu % component.blocksPerLine;
        // If the block is missing and we're in tolerant mode, just skip it.
        if (component.blocks[blockRow] === undefined && opts.tolerantDecoding) return;
        decode(component, component.blocks[blockRow][blockCol]);
      }
      var componentsLength = components.length;
      var component, i, j, k, n;
      var decodeFn;
      if (progressive) {
        if (spectralStart === 0) decodeFn = successivePrev === 0 ? decodeDCFirst : decodeDCSuccessive;else decodeFn = successivePrev === 0 ? decodeACFirst : decodeACSuccessive;
      } else {
        decodeFn = decodeBaseline;
      }
      var mcu = 0,
        marker;
      var mcuExpected;
      if (componentsLength == 1) {
        mcuExpected = components[0].blocksPerLine * components[0].blocksPerColumn;
      } else {
        mcuExpected = mcusPerLine * frame.mcusPerColumn;
      }
      if (!resetInterval) resetInterval = mcuExpected;
      var h, v;
      while (mcu < mcuExpected) {
        // reset interval stuff
        for (i = 0; i < componentsLength; i++) components[i].pred = 0;
        eobrun = 0;
        if (componentsLength == 1) {
          component = components[0];
          for (n = 0; n < resetInterval; n++) {
            decodeBlock(component, decodeFn, mcu);
            mcu++;
          }
        } else {
          for (n = 0; n < resetInterval; n++) {
            for (i = 0; i < componentsLength; i++) {
              component = components[i];
              h = component.h;
              v = component.v;
              for (j = 0; j < v; j++) {
                for (k = 0; k < h; k++) {
                  decodeMcu(component, decodeFn, mcu, j, k);
                }
              }
            }
            mcu++;

            // If we've reached our expected MCU's, stop decoding
            if (mcu === mcuExpected) break;
          }
        }
        if (mcu === mcuExpected) {
          // Skip trailing bytes at the end of the scan - until we reach the next marker
          do {
            if (data[offset] === 0xFF) {
              if (data[offset + 1] !== 0x00) {
                break;
              }
            }
            offset += 1;
          } while (offset < data.length - 2);
        }

        // find marker
        bitsCount = 0;
        marker = data[offset] << 8 | data[offset + 1];
        if (marker < 0xFF00) {
          throw new Error("marker was not found");
        }
        if (marker >= 0xFFD0 && marker <= 0xFFD7) {
          // RSTx
          offset += 2;
        } else break;
      }
      return offset - startOffset;
    }
    function buildComponentData(frame, component) {
      var lines = [];
      var blocksPerLine = component.blocksPerLine;
      var blocksPerColumn = component.blocksPerColumn;
      var samplesPerLine = blocksPerLine << 3;
      // Only 1 used per invocation of this function and garbage collected after invocation, so no need to account for its memory footprint.
      var R = new Int32Array(64),
        r = new Uint8Array(64);

      // A port of poppler's IDCT method which in turn is taken from:
      //   Christoph Loeffler, Adriaan Ligtenberg, George S. Moschytz,
      //   "Practical Fast 1-D DCT Algorithms with 11 Multiplications",
      //   IEEE Intl. Conf. on Acoustics, Speech & Signal Processing, 1989,
      //   988-991.
      function quantizeAndInverse(zz, dataOut, dataIn) {
        var qt = component.quantizationTable;
        var v0, v1, v2, v3, v4, v5, v6, v7, t;
        var p = dataIn;
        var i;

        // dequant
        for (i = 0; i < 64; i++) p[i] = zz[i] * qt[i];

        // inverse DCT on rows
        for (i = 0; i < 8; ++i) {
          var row = 8 * i;

          // check for all-zero AC coefficients
          if (p[1 + row] == 0 && p[2 + row] == 0 && p[3 + row] == 0 && p[4 + row] == 0 && p[5 + row] == 0 && p[6 + row] == 0 && p[7 + row] == 0) {
            t = dctSqrt2 * p[0 + row] + 512 >> 10;
            p[0 + row] = t;
            p[1 + row] = t;
            p[2 + row] = t;
            p[3 + row] = t;
            p[4 + row] = t;
            p[5 + row] = t;
            p[6 + row] = t;
            p[7 + row] = t;
            continue;
          }

          // stage 4
          v0 = dctSqrt2 * p[0 + row] + 128 >> 8;
          v1 = dctSqrt2 * p[4 + row] + 128 >> 8;
          v2 = p[2 + row];
          v3 = p[6 + row];
          v4 = dctSqrt1d2 * (p[1 + row] - p[7 + row]) + 128 >> 8;
          v7 = dctSqrt1d2 * (p[1 + row] + p[7 + row]) + 128 >> 8;
          v5 = p[3 + row] << 4;
          v6 = p[5 + row] << 4;

          // stage 3
          t = v0 - v1 + 1 >> 1;
          v0 = v0 + v1 + 1 >> 1;
          v1 = t;
          t = v2 * dctSin6 + v3 * dctCos6 + 128 >> 8;
          v2 = v2 * dctCos6 - v3 * dctSin6 + 128 >> 8;
          v3 = t;
          t = v4 - v6 + 1 >> 1;
          v4 = v4 + v6 + 1 >> 1;
          v6 = t;
          t = v7 + v5 + 1 >> 1;
          v5 = v7 - v5 + 1 >> 1;
          v7 = t;

          // stage 2
          t = v0 - v3 + 1 >> 1;
          v0 = v0 + v3 + 1 >> 1;
          v3 = t;
          t = v1 - v2 + 1 >> 1;
          v1 = v1 + v2 + 1 >> 1;
          v2 = t;
          t = v4 * dctSin3 + v7 * dctCos3 + 2048 >> 12;
          v4 = v4 * dctCos3 - v7 * dctSin3 + 2048 >> 12;
          v7 = t;
          t = v5 * dctSin1 + v6 * dctCos1 + 2048 >> 12;
          v5 = v5 * dctCos1 - v6 * dctSin1 + 2048 >> 12;
          v6 = t;

          // stage 1
          p[0 + row] = v0 + v7;
          p[7 + row] = v0 - v7;
          p[1 + row] = v1 + v6;
          p[6 + row] = v1 - v6;
          p[2 + row] = v2 + v5;
          p[5 + row] = v2 - v5;
          p[3 + row] = v3 + v4;
          p[4 + row] = v3 - v4;
        }

        // inverse DCT on columns
        for (i = 0; i < 8; ++i) {
          var col = i;

          // check for all-zero AC coefficients
          if (p[1 * 8 + col] == 0 && p[2 * 8 + col] == 0 && p[3 * 8 + col] == 0 && p[4 * 8 + col] == 0 && p[5 * 8 + col] == 0 && p[6 * 8 + col] == 0 && p[7 * 8 + col] == 0) {
            t = dctSqrt2 * dataIn[i + 0] + 8192 >> 14;
            p[0 * 8 + col] = t;
            p[1 * 8 + col] = t;
            p[2 * 8 + col] = t;
            p[3 * 8 + col] = t;
            p[4 * 8 + col] = t;
            p[5 * 8 + col] = t;
            p[6 * 8 + col] = t;
            p[7 * 8 + col] = t;
            continue;
          }

          // stage 4
          v0 = dctSqrt2 * p[0 * 8 + col] + 2048 >> 12;
          v1 = dctSqrt2 * p[4 * 8 + col] + 2048 >> 12;
          v2 = p[2 * 8 + col];
          v3 = p[6 * 8 + col];
          v4 = dctSqrt1d2 * (p[1 * 8 + col] - p[7 * 8 + col]) + 2048 >> 12;
          v7 = dctSqrt1d2 * (p[1 * 8 + col] + p[7 * 8 + col]) + 2048 >> 12;
          v5 = p[3 * 8 + col];
          v6 = p[5 * 8 + col];

          // stage 3
          t = v0 - v1 + 1 >> 1;
          v0 = v0 + v1 + 1 >> 1;
          v1 = t;
          t = v2 * dctSin6 + v3 * dctCos6 + 2048 >> 12;
          v2 = v2 * dctCos6 - v3 * dctSin6 + 2048 >> 12;
          v3 = t;
          t = v4 - v6 + 1 >> 1;
          v4 = v4 + v6 + 1 >> 1;
          v6 = t;
          t = v7 + v5 + 1 >> 1;
          v5 = v7 - v5 + 1 >> 1;
          v7 = t;

          // stage 2
          t = v0 - v3 + 1 >> 1;
          v0 = v0 + v3 + 1 >> 1;
          v3 = t;
          t = v1 - v2 + 1 >> 1;
          v1 = v1 + v2 + 1 >> 1;
          v2 = t;
          t = v4 * dctSin3 + v7 * dctCos3 + 2048 >> 12;
          v4 = v4 * dctCos3 - v7 * dctSin3 + 2048 >> 12;
          v7 = t;
          t = v5 * dctSin1 + v6 * dctCos1 + 2048 >> 12;
          v5 = v5 * dctCos1 - v6 * dctSin1 + 2048 >> 12;
          v6 = t;

          // stage 1
          p[0 * 8 + col] = v0 + v7;
          p[7 * 8 + col] = v0 - v7;
          p[1 * 8 + col] = v1 + v6;
          p[6 * 8 + col] = v1 - v6;
          p[2 * 8 + col] = v2 + v5;
          p[5 * 8 + col] = v2 - v5;
          p[3 * 8 + col] = v3 + v4;
          p[4 * 8 + col] = v3 - v4;
        }

        // convert to 8-bit integers
        for (i = 0; i < 64; ++i) {
          var sample = 128 + (p[i] + 8 >> 4);
          dataOut[i] = sample < 0 ? 0 : sample > 0xFF ? 0xFF : sample;
        }
      }
      requestMemoryAllocation(samplesPerLine * blocksPerColumn * 8);
      var i, j;
      for (var blockRow = 0; blockRow < blocksPerColumn; blockRow++) {
        var scanLine = blockRow << 3;
        for (i = 0; i < 8; i++) lines.push(new Uint8Array(samplesPerLine));
        for (var blockCol = 0; blockCol < blocksPerLine; blockCol++) {
          quantizeAndInverse(component.blocks[blockRow][blockCol], r, R);
          var offset = 0,
            sample = blockCol << 3;
          for (j = 0; j < 8; j++) {
            var line = lines[scanLine + j];
            for (i = 0; i < 8; i++) line[sample + i] = r[offset++];
          }
        }
      }
      return lines;
    }
    function clampTo8bit(a) {
      return a < 0 ? 0 : a > 255 ? 255 : a;
    }
    constructor.prototype = {
      load: function load(path) {
        var xhr = new XMLHttpRequest();
        xhr.open("GET", path, true);
        xhr.responseType = "arraybuffer";
        xhr.onload = function () {
          // TODO catch parse error
          var data = new Uint8Array(xhr.response || xhr.mozResponseArrayBuffer);
          this.parse(data);
          if (this.onload) this.onload();
        }.bind(this);
        xhr.send(null);
      },
      parse: function parse(data) {
        var maxResolutionInPixels = this.opts.maxResolutionInMP * 1000 * 1000;
        var offset = 0;
          data.length;
        function readUint16() {
          var value = data[offset] << 8 | data[offset + 1];
          offset += 2;
          return value;
        }
        function readDataBlock() {
          var length = readUint16();
          var array = data.subarray(offset, offset + length - 2);
          offset += array.length;
          return array;
        }
        function prepareComponents(frame) {
          // According to the JPEG standard, the sampling factor must be between 1 and 4
          // See https://github.com/libjpeg-turbo/libjpeg-turbo/blob/9abeff46d87bd201a952e276f3e4339556a403a3/libjpeg.txt#L1138-L1146
          var maxH = 1,
            maxV = 1;
          var component, componentId;
          for (componentId in frame.components) {
            if (frame.components.hasOwnProperty(componentId)) {
              component = frame.components[componentId];
              if (maxH < component.h) maxH = component.h;
              if (maxV < component.v) maxV = component.v;
            }
          }
          var mcusPerLine = Math.ceil(frame.samplesPerLine / 8 / maxH);
          var mcusPerColumn = Math.ceil(frame.scanLines / 8 / maxV);
          for (componentId in frame.components) {
            if (frame.components.hasOwnProperty(componentId)) {
              component = frame.components[componentId];
              var blocksPerLine = Math.ceil(Math.ceil(frame.samplesPerLine / 8) * component.h / maxH);
              var blocksPerColumn = Math.ceil(Math.ceil(frame.scanLines / 8) * component.v / maxV);
              var blocksPerLineForMcu = mcusPerLine * component.h;
              var blocksPerColumnForMcu = mcusPerColumn * component.v;
              var blocksToAllocate = blocksPerColumnForMcu * blocksPerLineForMcu;
              var blocks = [];

              // Each block is a Int32Array of length 64 (4 x 64 = 256 bytes)
              requestMemoryAllocation(blocksToAllocate * 256);
              for (var i = 0; i < blocksPerColumnForMcu; i++) {
                var row = [];
                for (var j = 0; j < blocksPerLineForMcu; j++) row.push(new Int32Array(64));
                blocks.push(row);
              }
              component.blocksPerLine = blocksPerLine;
              component.blocksPerColumn = blocksPerColumn;
              component.blocks = blocks;
            }
          }
          frame.maxH = maxH;
          frame.maxV = maxV;
          frame.mcusPerLine = mcusPerLine;
          frame.mcusPerColumn = mcusPerColumn;
        }
        var jfif = null;
        var adobe = null;
        var frame, resetInterval;
        var quantizationTables = [],
          frames = [];
        var huffmanTablesAC = [],
          huffmanTablesDC = [];
        var fileMarker = readUint16();
        var malformedDataOffset = -1;
        this.comments = [];
        if (fileMarker != 0xFFD8) {
          // SOI (Start of Image)
          throw new Error("SOI not found");
        }
        fileMarker = readUint16();
        while (fileMarker != 0xFFD9) {
          // EOI (End of image)
          var i, j;
          switch (fileMarker) {
            case 0xFF00:
              break;
            case 0xFFE0: // APP0 (Application Specific)
            case 0xFFE1: // APP1
            case 0xFFE2: // APP2
            case 0xFFE3: // APP3
            case 0xFFE4: // APP4
            case 0xFFE5: // APP5
            case 0xFFE6: // APP6
            case 0xFFE7: // APP7
            case 0xFFE8: // APP8
            case 0xFFE9: // APP9
            case 0xFFEA: // APP10
            case 0xFFEB: // APP11
            case 0xFFEC: // APP12
            case 0xFFED: // APP13
            case 0xFFEE: // APP14
            case 0xFFEF: // APP15
            case 0xFFFE:
              // COM (Comment)
              var appData = readDataBlock();
              if (fileMarker === 0xFFFE) {
                var comment = String.fromCharCode.apply(null, appData);
                this.comments.push(comment);
              }
              if (fileMarker === 0xFFE0) {
                if (appData[0] === 0x4A && appData[1] === 0x46 && appData[2] === 0x49 && appData[3] === 0x46 && appData[4] === 0) {
                  // 'JFIF\x00'
                  jfif = {
                    version: {
                      major: appData[5],
                      minor: appData[6]
                    },
                    densityUnits: appData[7],
                    xDensity: appData[8] << 8 | appData[9],
                    yDensity: appData[10] << 8 | appData[11],
                    thumbWidth: appData[12],
                    thumbHeight: appData[13],
                    thumbData: appData.subarray(14, 14 + 3 * appData[12] * appData[13])
                  };
                }
              }
              // TODO APP1 - Exif
              if (fileMarker === 0xFFE1) {
                if (appData[0] === 0x45 && appData[1] === 0x78 && appData[2] === 0x69 && appData[3] === 0x66 && appData[4] === 0) {
                  // 'EXIF\x00'
                  this.exifBuffer = appData.subarray(5, appData.length);
                }
              }
              if (fileMarker === 0xFFEE) {
                if (appData[0] === 0x41 && appData[1] === 0x64 && appData[2] === 0x6F && appData[3] === 0x62 && appData[4] === 0x65 && appData[5] === 0) {
                  // 'Adobe\x00'
                  adobe = {
                    version: appData[6],
                    flags0: appData[7] << 8 | appData[8],
                    flags1: appData[9] << 8 | appData[10],
                    transformCode: appData[11]
                  };
                }
              }
              break;
            case 0xFFDB:
              // DQT (Define Quantization Tables)
              var quantizationTablesLength = readUint16();
              var quantizationTablesEnd = quantizationTablesLength + offset - 2;
              while (offset < quantizationTablesEnd) {
                var quantizationTableSpec = data[offset++];
                requestMemoryAllocation(64 * 4);
                var tableData = new Int32Array(64);
                if (quantizationTableSpec >> 4 === 0) {
                  // 8 bit values
                  for (j = 0; j < 64; j++) {
                    var z = dctZigZag[j];
                    tableData[z] = data[offset++];
                  }
                } else if (quantizationTableSpec >> 4 === 1) {
                  //16 bit
                  for (j = 0; j < 64; j++) {
                    var z = dctZigZag[j];
                    tableData[z] = readUint16();
                  }
                } else throw new Error("DQT: invalid table spec");
                quantizationTables[quantizationTableSpec & 15] = tableData;
              }
              break;
            case 0xFFC0: // SOF0 (Start of Frame, Baseline DCT)
            case 0xFFC1: // SOF1 (Start of Frame, Extended DCT)
            case 0xFFC2:
              // SOF2 (Start of Frame, Progressive DCT)
              readUint16(); // skip data length
              frame = {};
              frame.extended = fileMarker === 0xFFC1;
              frame.progressive = fileMarker === 0xFFC2;
              frame.precision = data[offset++];
              frame.scanLines = readUint16();
              frame.samplesPerLine = readUint16();
              frame.components = {};
              frame.componentsOrder = [];
              var pixelsInFrame = frame.scanLines * frame.samplesPerLine;
              if (pixelsInFrame > maxResolutionInPixels) {
                var exceededAmount = Math.ceil((pixelsInFrame - maxResolutionInPixels) / 1e6);
                throw new Error(`maxResolutionInMP limit exceeded by ${exceededAmount}MP`);
              }
              var componentsCount = data[offset++],
                componentId;
              for (i = 0; i < componentsCount; i++) {
                componentId = data[offset];
                var h = data[offset + 1] >> 4;
                var v = data[offset + 1] & 15;
                var qId = data[offset + 2];
                if (h <= 0 || v <= 0) {
                  throw new Error('Invalid sampling factor, expected values above 0');
                }
                frame.componentsOrder.push(componentId);
                frame.components[componentId] = {
                  h: h,
                  v: v,
                  quantizationIdx: qId
                };
                offset += 3;
              }
              prepareComponents(frame);
              frames.push(frame);
              break;
            case 0xFFC4:
              // DHT (Define Huffman Tables)
              var huffmanLength = readUint16();
              for (i = 2; i < huffmanLength;) {
                var huffmanTableSpec = data[offset++];
                var codeLengths = new Uint8Array(16);
                var codeLengthSum = 0;
                for (j = 0; j < 16; j++, offset++) {
                  codeLengthSum += codeLengths[j] = data[offset];
                }
                requestMemoryAllocation(16 + codeLengthSum);
                var huffmanValues = new Uint8Array(codeLengthSum);
                for (j = 0; j < codeLengthSum; j++, offset++) huffmanValues[j] = data[offset];
                i += 17 + codeLengthSum;
                (huffmanTableSpec >> 4 === 0 ? huffmanTablesDC : huffmanTablesAC)[huffmanTableSpec & 15] = buildHuffmanTable(codeLengths, huffmanValues);
              }
              break;
            case 0xFFDD:
              // DRI (Define Restart Interval)
              readUint16(); // skip data length
              resetInterval = readUint16();
              break;
            case 0xFFDC:
              // Number of Lines marker
              readUint16(); // skip data length
              readUint16(); // Ignore this data since it represents the image height
              break;
            case 0xFFDA:
              // SOS (Start of Scan)
              readUint16();
              var selectorsCount = data[offset++];
              var components = [],
                component;
              for (i = 0; i < selectorsCount; i++) {
                component = frame.components[data[offset++]];
                var tableSpec = data[offset++];
                component.huffmanTableDC = huffmanTablesDC[tableSpec >> 4];
                component.huffmanTableAC = huffmanTablesAC[tableSpec & 15];
                components.push(component);
              }
              var spectralStart = data[offset++];
              var spectralEnd = data[offset++];
              var successiveApproximation = data[offset++];
              var processed = decodeScan(data, offset, frame, components, resetInterval, spectralStart, spectralEnd, successiveApproximation >> 4, successiveApproximation & 15, this.opts);
              offset += processed;
              break;
            case 0xFFFF:
              // Fill bytes
              if (data[offset] !== 0xFF) {
                // Avoid skipping a valid marker.
                offset--;
              }
              break;
            default:
              if (data[offset - 3] == 0xFF && data[offset - 2] >= 0xC0 && data[offset - 2] <= 0xFE) {
                // could be incorrect encoding -- last 0xFF byte of the previous
                // block was eaten by the encoder
                offset -= 3;
                break;
              } else if (fileMarker === 0xE0 || fileMarker == 0xE1) {
                // Recover from malformed APP1 markers popular in some phone models.
                // See https://github.com/eugeneware/jpeg-js/issues/82
                if (malformedDataOffset !== -1) {
                  throw new Error(`first unknown JPEG marker at offset ${malformedDataOffset.toString(16)}, second unknown JPEG marker ${fileMarker.toString(16)} at offset ${(offset - 1).toString(16)}`);
                }
                malformedDataOffset = offset - 1;
                const nextOffset = readUint16();
                if (data[offset + nextOffset - 2] === 0xFF) {
                  offset += nextOffset - 2;
                  break;
                }
              }
              throw new Error("unknown JPEG marker " + fileMarker.toString(16));
          }
          fileMarker = readUint16();
        }
        if (frames.length != 1) throw new Error("only single frame JPEGs supported");

        // set each frame's components quantization table
        for (var i = 0; i < frames.length; i++) {
          var cp = frames[i].components;
          for (var j in cp) {
            cp[j].quantizationTable = quantizationTables[cp[j].quantizationIdx];
            delete cp[j].quantizationIdx;
          }
        }
        this.width = frame.samplesPerLine;
        this.height = frame.scanLines;
        this.jfif = jfif;
        this.adobe = adobe;
        this.components = [];
        for (var i = 0; i < frame.componentsOrder.length; i++) {
          var component = frame.components[frame.componentsOrder[i]];
          this.components.push({
            lines: buildComponentData(frame, component),
            scaleX: component.h / frame.maxH,
            scaleY: component.v / frame.maxV
          });
        }
      },
      getData: function getData(width, height) {
        var scaleX = this.width / width,
          scaleY = this.height / height;
        var component1, component2, component3, component4;
        var component1Line, component2Line, component3Line, component4Line;
        var x, y;
        var offset = 0;
        var Y, Cb, Cr, K, C, M, Ye, R, G, B;
        var colorTransform;
        var dataLength = width * height * this.components.length;
        requestMemoryAllocation(dataLength);
        var data = new Uint8Array(dataLength);
        switch (this.components.length) {
          case 1:
            component1 = this.components[0];
            for (y = 0; y < height; y++) {
              component1Line = component1.lines[0 | y * component1.scaleY * scaleY];
              for (x = 0; x < width; x++) {
                Y = component1Line[0 | x * component1.scaleX * scaleX];
                data[offset++] = Y;
              }
            }
            break;
          case 2:
            // PDF might compress two component data in custom colorspace
            component1 = this.components[0];
            component2 = this.components[1];
            for (y = 0; y < height; y++) {
              component1Line = component1.lines[0 | y * component1.scaleY * scaleY];
              component2Line = component2.lines[0 | y * component2.scaleY * scaleY];
              for (x = 0; x < width; x++) {
                Y = component1Line[0 | x * component1.scaleX * scaleX];
                data[offset++] = Y;
                Y = component2Line[0 | x * component2.scaleX * scaleX];
                data[offset++] = Y;
              }
            }
            break;
          case 3:
            // The default transform for three components is true
            colorTransform = true;
            // The adobe transform marker overrides any previous setting
            if (this.adobe && this.adobe.transformCode) colorTransform = true;else if (typeof this.opts.colorTransform !== 'undefined') colorTransform = !!this.opts.colorTransform;
            component1 = this.components[0];
            component2 = this.components[1];
            component3 = this.components[2];
            for (y = 0; y < height; y++) {
              component1Line = component1.lines[0 | y * component1.scaleY * scaleY];
              component2Line = component2.lines[0 | y * component2.scaleY * scaleY];
              component3Line = component3.lines[0 | y * component3.scaleY * scaleY];
              for (x = 0; x < width; x++) {
                if (!colorTransform) {
                  R = component1Line[0 | x * component1.scaleX * scaleX];
                  G = component2Line[0 | x * component2.scaleX * scaleX];
                  B = component3Line[0 | x * component3.scaleX * scaleX];
                } else {
                  Y = component1Line[0 | x * component1.scaleX * scaleX];
                  Cb = component2Line[0 | x * component2.scaleX * scaleX];
                  Cr = component3Line[0 | x * component3.scaleX * scaleX];
                  R = clampTo8bit(Y + 1.402 * (Cr - 128));
                  G = clampTo8bit(Y - 0.3441363 * (Cb - 128) - 0.71413636 * (Cr - 128));
                  B = clampTo8bit(Y + 1.772 * (Cb - 128));
                }
                data[offset++] = R;
                data[offset++] = G;
                data[offset++] = B;
              }
            }
            break;
          case 4:
            if (!this.adobe) throw new Error('Unsupported color mode (4 components)');
            // The default transform for four components is false
            colorTransform = false;
            // The adobe transform marker overrides any previous setting
            if (this.adobe && this.adobe.transformCode) colorTransform = true;else if (typeof this.opts.colorTransform !== 'undefined') colorTransform = !!this.opts.colorTransform;
            component1 = this.components[0];
            component2 = this.components[1];
            component3 = this.components[2];
            component4 = this.components[3];
            for (y = 0; y < height; y++) {
              component1Line = component1.lines[0 | y * component1.scaleY * scaleY];
              component2Line = component2.lines[0 | y * component2.scaleY * scaleY];
              component3Line = component3.lines[0 | y * component3.scaleY * scaleY];
              component4Line = component4.lines[0 | y * component4.scaleY * scaleY];
              for (x = 0; x < width; x++) {
                if (!colorTransform) {
                  C = component1Line[0 | x * component1.scaleX * scaleX];
                  M = component2Line[0 | x * component2.scaleX * scaleX];
                  Ye = component3Line[0 | x * component3.scaleX * scaleX];
                  K = component4Line[0 | x * component4.scaleX * scaleX];
                } else {
                  Y = component1Line[0 | x * component1.scaleX * scaleX];
                  Cb = component2Line[0 | x * component2.scaleX * scaleX];
                  Cr = component3Line[0 | x * component3.scaleX * scaleX];
                  K = component4Line[0 | x * component4.scaleX * scaleX];
                  C = 255 - clampTo8bit(Y + 1.402 * (Cr - 128));
                  M = 255 - clampTo8bit(Y - 0.3441363 * (Cb - 128) - 0.71413636 * (Cr - 128));
                  Ye = 255 - clampTo8bit(Y + 1.772 * (Cb - 128));
                }
                data[offset++] = 255 - C;
                data[offset++] = 255 - M;
                data[offset++] = 255 - Ye;
                data[offset++] = 255 - K;
              }
            }
            break;
          default:
            throw new Error('Unsupported color mode');
        }
        return data;
      },
      copyToImageData: function copyToImageData(imageData, formatAsRGBA) {
        var width = imageData.width,
          height = imageData.height;
        var imageDataArray = imageData.data;
        var data = this.getData(width, height);
        var i = 0,
          j = 0,
          x,
          y;
        var Y, K, C, M, R, G, B;
        switch (this.components.length) {
          case 1:
            for (y = 0; y < height; y++) {
              for (x = 0; x < width; x++) {
                Y = data[i++];
                imageDataArray[j++] = Y;
                imageDataArray[j++] = Y;
                imageDataArray[j++] = Y;
                if (formatAsRGBA) {
                  imageDataArray[j++] = 255;
                }
              }
            }
            break;
          case 3:
            for (y = 0; y < height; y++) {
              for (x = 0; x < width; x++) {
                R = data[i++];
                G = data[i++];
                B = data[i++];
                imageDataArray[j++] = R;
                imageDataArray[j++] = G;
                imageDataArray[j++] = B;
                if (formatAsRGBA) {
                  imageDataArray[j++] = 255;
                }
              }
            }
            break;
          case 4:
            for (y = 0; y < height; y++) {
              for (x = 0; x < width; x++) {
                C = data[i++];
                M = data[i++];
                Y = data[i++];
                K = data[i++];
                R = 255 - clampTo8bit(C * (1 - K / 255) + K);
                G = 255 - clampTo8bit(M * (1 - K / 255) + K);
                B = 255 - clampTo8bit(Y * (1 - K / 255) + K);
                imageDataArray[j++] = R;
                imageDataArray[j++] = G;
                imageDataArray[j++] = B;
                if (formatAsRGBA) {
                  imageDataArray[j++] = 255;
                }
              }
            }
            break;
          default:
            throw new Error('Unsupported color mode');
        }
      }
    };

    // We cap the amount of memory used by jpeg-js to avoid unexpected OOMs from untrusted content.
    var totalBytesAllocated = 0;
    var maxMemoryUsageBytes = 0;
    function requestMemoryAllocation(increaseAmount = 0) {
      var totalMemoryImpactBytes = totalBytesAllocated + increaseAmount;
      if (totalMemoryImpactBytes > maxMemoryUsageBytes) {
        var exceededAmount = Math.ceil((totalMemoryImpactBytes - maxMemoryUsageBytes) / 1024 / 1024);
        throw new Error(`maxMemoryUsageInMB limit exceeded by at least ${exceededAmount}MB`);
      }
      totalBytesAllocated = totalMemoryImpactBytes;
    }
    constructor.resetMaxMemoryUsage = function (maxMemoryUsageBytes_) {
      totalBytesAllocated = 0;
      maxMemoryUsageBytes = maxMemoryUsageBytes_;
    };
    constructor.getBytesAllocated = function () {
      return totalBytesAllocated;
    };
    constructor.requestMemoryAllocation = requestMemoryAllocation;
    return constructor;
  }();
  {
    module.exports = decode;
  }
  function decode(jpegData, userOpts = {}) {
    var defaultOpts = {
      // "undefined" means "Choose whether to transform colors based on the image’s color model."
      colorTransform: undefined,
      useTArray: false,
      formatAsRGBA: true,
      tolerantDecoding: true,
      maxResolutionInMP: 100,
      // Don't decode more than 100 megapixels
      maxMemoryUsageInMB: 512 // Don't decode if memory footprint is more than 512MB
    };
    var opts = {
      ...defaultOpts,
      ...userOpts
    };
    var arr = new Uint8Array(jpegData);
    var decoder = new JpegImage();
    decoder.opts = opts;
    // If this constructor ever supports async decoding this will need to be done differently.
    // Until then, treating as singleton limit is fine.
    JpegImage.resetMaxMemoryUsage(opts.maxMemoryUsageInMB * 1024 * 1024);
    decoder.parse(arr);
    var channels = opts.formatAsRGBA ? 4 : 3;
    var bytesNeeded = decoder.width * decoder.height * channels;
    try {
      JpegImage.requestMemoryAllocation(bytesNeeded);
      var image = {
        width: decoder.width,
        height: decoder.height,
        exifBuffer: decoder.exifBuffer,
        data: opts.useTArray ? new Uint8Array(bytesNeeded) : Buffer.alloc(bytesNeeded)
      };
      if (decoder.comments.length > 0) {
        image["comments"] = decoder.comments;
      }
    } catch (err) {
      if (err instanceof RangeError) {
        throw new Error("Could not allocate enough memory for the image. " + "Required: " + bytesNeeded);
      }
      if (err instanceof ReferenceError) {
        if (err.message === "Buffer is not defined") {
          throw new Error("Buffer is not globally defined in this environment. " + "Consider setting useTArray to true");
        }
      }
      throw err;
    }
    decoder.copyToImageData(image, opts.formatAsRGBA);
    return image;
  }
})(decoder);
var decoderExports = decoder.exports;

var encode$1 = encoderExports,
  decode$2 = decoderExports;
var jpegJs = {
  encode: encode$1,
  decode: decode$2
};

/**
 * Creates a JPEG buffer from an image.
 * @param image - The image instance.
 * @param options - JPEG encoding options.
 * @returns The buffer.
 */
function encodeJpeg(image, options = {}) {
  const {
    quality = 50
  } = options;
  if (image.colorModel !== 'RGBA' || image instanceof Mask) {
    image = image.convertColor('RGBA');
  }
  if (image.bitDepth !== 8) {
    image = image.convertBitDepth(8);
  }
  // Image data after bit depth conversion will always be UInt8Array.
  const buffer = jpegJs.encode(image.getRawImage(), quality).data;
  return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
}

// DEFLATE is a complex format; to read this code, you should probably check the RFC first:
// https://tools.ietf.org/html/rfc1951
// You may also wish to take a look at the guide I made about this program:
// https://gist.github.com/101arrowz/253f31eb5abc3d9275ab943003ffecad
// Some of the following code is similar to that of UZIP.js:
// https://github.com/photopea/UZIP.js
// However, the vast majority of the codebase has diverged from UZIP.js to increase performance and reduce bundle size.
// Sometimes 0 will appear where -1 would be more appropriate. This is because using a uint
// is better for memory in most engines (I *think*).

// aliases for shorter compressed code (most minifers don't do this)
var u8 = Uint8Array,
  u16 = Uint16Array,
  i32 = Int32Array;
// fixed length extra bits
var fleb = new u8([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, /* unused */0, 0, /* impossible */0]);
// fixed distance extra bits
var fdeb = new u8([0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, /* unused */0, 0]);
// code length index map
var clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]);
// get base, reverse index map from extra bits
var freb = function (eb, start) {
  var b = new u16(31);
  for (var i = 0; i < 31; ++i) {
    b[i] = start += 1 << eb[i - 1];
  }
  // numbers here are at max 18 bits
  var r = new i32(b[30]);
  for (var i = 1; i < 30; ++i) {
    for (var j = b[i]; j < b[i + 1]; ++j) {
      r[j] = j - b[i] << 5 | i;
    }
  }
  return {
    b: b,
    r: r
  };
};
var _a = freb(fleb, 2),
  fl = _a.b,
  revfl = _a.r;
// we can ignore the fact that the other numbers are wrong; they never happen anyway
fl[28] = 258, revfl[258] = 28;
var _b = freb(fdeb, 0),
  fd = _b.b,
  revfd = _b.r;
// map of value to reverse (assuming 16 bits)
var rev = new u16(32768);
for (var i = 0; i < 32768; ++i) {
  // reverse table algorithm from SO
  var x = (i & 0xAAAA) >> 1 | (i & 0x5555) << 1;
  x = (x & 0xCCCC) >> 2 | (x & 0x3333) << 2;
  x = (x & 0xF0F0) >> 4 | (x & 0x0F0F) << 4;
  rev[i] = ((x & 0xFF00) >> 8 | (x & 0x00FF) << 8) >> 1;
}
// create huffman tree from u8 "map": index -> code length for code index
// mb (max bits) must be at most 15
// TODO: optimize/split up?
var hMap = function (cd, mb, r) {
  var s = cd.length;
  // index
  var i = 0;
  // u16 "map": index -> # of codes with bit length = index
  var l = new u16(mb);
  // length of cd must be 288 (total # of codes)
  for (; i < s; ++i) {
    if (cd[i]) ++l[cd[i] - 1];
  }
  // u16 "map": index -> minimum code for bit length = index
  var le = new u16(mb);
  for (i = 1; i < mb; ++i) {
    le[i] = le[i - 1] + l[i - 1] << 1;
  }
  var co;
  if (r) {
    // u16 "map": index -> number of actual bits, symbol for code
    co = new u16(1 << mb);
    // bits to remove for reverser
    var rvb = 15 - mb;
    for (i = 0; i < s; ++i) {
      // ignore 0 lengths
      if (cd[i]) {
        // num encoding both symbol and bits read
        var sv = i << 4 | cd[i];
        // free bits
        var r_1 = mb - cd[i];
        // start value
        var v = le[cd[i] - 1]++ << r_1;
        // m is end value
        for (var m = v | (1 << r_1) - 1; v <= m; ++v) {
          // every 16 bit value starting with the code yields the same result
          co[rev[v] >> rvb] = sv;
        }
      }
    }
  } else {
    co = new u16(s);
    for (i = 0; i < s; ++i) {
      if (cd[i]) {
        co[i] = rev[le[cd[i] - 1]++] >> 15 - cd[i];
      }
    }
  }
  return co;
};
// fixed length tree
var flt = new u8(288);
for (var i = 0; i < 144; ++i) flt[i] = 8;
for (var i = 144; i < 256; ++i) flt[i] = 9;
for (var i = 256; i < 280; ++i) flt[i] = 7;
for (var i = 280; i < 288; ++i) flt[i] = 8;
// fixed distance tree
var fdt = new u8(32);
for (var i = 0; i < 32; ++i) fdt[i] = 5;
// fixed length map
var flm = /*#__PURE__*/hMap(flt, 9, 0),
  flrm = /*#__PURE__*/hMap(flt, 9, 1);
// fixed distance map
var fdm = /*#__PURE__*/hMap(fdt, 5, 0),
  fdrm = /*#__PURE__*/hMap(fdt, 5, 1);
// find max of array
var max = function (a) {
  var m = a[0];
  for (var i = 1; i < a.length; ++i) {
    if (a[i] > m) m = a[i];
  }
  return m;
};
// read d, starting at bit p and mask with m
var bits = function (d, p, m) {
  var o = p / 8 | 0;
  return (d[o] | d[o + 1] << 8) >> (p & 7) & m;
};
// read d, starting at bit p continuing for at least 16 bits
var bits16 = function (d, p) {
  var o = p / 8 | 0;
  return (d[o] | d[o + 1] << 8 | d[o + 2] << 16) >> (p & 7);
};
// get end of byte
var shft = function (p) {
  return (p + 7) / 8 | 0;
};
// typed array slice - allows garbage collector to free original reference,
// while being more compatible than .slice
var slc = function (v, s, e) {
  if (s == null || s < 0) s = 0;
  if (e == null || e > v.length) e = v.length;
  // can't use .constructor in case user-supplied
  return new u8(v.subarray(s, e));
};
// error codes
var ec = ['unexpected EOF', 'invalid block type', 'invalid length/literal', 'invalid distance', 'stream finished', 'no stream handler',, 'no callback', 'invalid UTF-8 data', 'extra field too long', 'date not in range 1980-2099', 'filename too long', 'stream finishing', 'invalid zip data'
// determined by unknown compression method
];
var err = function (ind, msg, nt) {
  var e = new Error(msg || ec[ind]);
  e.code = ind;
  if (Error.captureStackTrace) Error.captureStackTrace(e, err);
  if (!nt) throw e;
  return e;
};
// expands raw DEFLATE data
var inflt = function (dat, st, buf, dict) {
  // source length       dict length
  var sl = dat.length,
    dl = 0;
  if (!sl || st.f && !st.l) return buf || new u8(0);
  var noBuf = !buf;
  // have to estimate size
  var resize = noBuf || st.i != 2;
  // no state
  var noSt = st.i;
  // Assumes roughly 33% compression ratio average
  if (noBuf) buf = new u8(sl * 3);
  // ensure buffer can fit at least l elements
  var cbuf = function (l) {
    var bl = buf.length;
    // need to increase size to fit
    if (l > bl) {
      // Double or set to necessary, whichever is greater
      var nbuf = new u8(Math.max(bl * 2, l));
      nbuf.set(buf);
      buf = nbuf;
    }
  };
  //  last chunk         bitpos           bytes
  var final = st.f || 0,
    pos = st.p || 0,
    bt = st.b || 0,
    lm = st.l,
    dm = st.d,
    lbt = st.m,
    dbt = st.n;
  // total bits
  var tbts = sl * 8;
  do {
    if (!lm) {
      // BFINAL - this is only 1 when last chunk is next
      final = bits(dat, pos, 1);
      // type: 0 = no compression, 1 = fixed huffman, 2 = dynamic huffman
      var type = bits(dat, pos + 1, 3);
      pos += 3;
      if (!type) {
        // go to end of byte boundary
        var s = shft(pos) + 4,
          l = dat[s - 4] | dat[s - 3] << 8,
          t = s + l;
        if (t > sl) {
          if (noSt) err(0);
          break;
        }
        // ensure size
        if (resize) cbuf(bt + l);
        // Copy over uncompressed data
        buf.set(dat.subarray(s, t), bt);
        // Get new bitpos, update byte count
        st.b = bt += l, st.p = pos = t * 8, st.f = final;
        continue;
      } else if (type == 1) lm = flrm, dm = fdrm, lbt = 9, dbt = 5;else if (type == 2) {
        //  literal                            lengths
        var hLit = bits(dat, pos, 31) + 257,
          hcLen = bits(dat, pos + 10, 15) + 4;
        var tl = hLit + bits(dat, pos + 5, 31) + 1;
        pos += 14;
        // length+distance tree
        var ldt = new u8(tl);
        // code length tree
        var clt = new u8(19);
        for (var i = 0; i < hcLen; ++i) {
          // use index map to get real code
          clt[clim[i]] = bits(dat, pos + i * 3, 7);
        }
        pos += hcLen * 3;
        // code lengths bits
        var clb = max(clt),
          clbmsk = (1 << clb) - 1;
        // code lengths map
        var clm = hMap(clt, clb, 1);
        for (var i = 0; i < tl;) {
          var r = clm[bits(dat, pos, clbmsk)];
          // bits read
          pos += r & 15;
          // symbol
          var s = r >> 4;
          // code length to copy
          if (s < 16) {
            ldt[i++] = s;
          } else {
            //  copy   count
            var c = 0,
              n = 0;
            if (s == 16) n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i - 1];else if (s == 17) n = 3 + bits(dat, pos, 7), pos += 3;else if (s == 18) n = 11 + bits(dat, pos, 127), pos += 7;
            while (n--) ldt[i++] = c;
          }
        }
        //    length tree                 distance tree
        var lt = ldt.subarray(0, hLit),
          dt = ldt.subarray(hLit);
        // max length bits
        lbt = max(lt);
        // max dist bits
        dbt = max(dt);
        lm = hMap(lt, lbt, 1);
        dm = hMap(dt, dbt, 1);
      } else err(1);
      if (pos > tbts) {
        if (noSt) err(0);
        break;
      }
    }
    // Make sure the buffer can hold this + the largest possible addition
    // Maximum chunk size (practically, theoretically infinite) is 2^17
    if (resize) cbuf(bt + 131072);
    var lms = (1 << lbt) - 1,
      dms = (1 << dbt) - 1;
    var lpos = pos;
    for (;; lpos = pos) {
      // bits read, code
      var c = lm[bits16(dat, pos) & lms],
        sym = c >> 4;
      pos += c & 15;
      if (pos > tbts) {
        if (noSt) err(0);
        break;
      }
      if (!c) err(2);
      if (sym < 256) buf[bt++] = sym;else if (sym == 256) {
        lpos = pos, lm = null;
        break;
      } else {
        var add = sym - 254;
        // no extra bits needed if less
        if (sym > 264) {
          // index
          var i = sym - 257,
            b = fleb[i];
          add = bits(dat, pos, (1 << b) - 1) + fl[i];
          pos += b;
        }
        // dist
        var d = dm[bits16(dat, pos) & dms],
          dsym = d >> 4;
        if (!d) err(3);
        pos += d & 15;
        var dt = fd[dsym];
        if (dsym > 3) {
          var b = fdeb[dsym];
          dt += bits16(dat, pos) & (1 << b) - 1, pos += b;
        }
        if (pos > tbts) {
          if (noSt) err(0);
          break;
        }
        if (resize) cbuf(bt + 131072);
        var end = bt + add;
        if (bt < dt) {
          var shift = dl - dt,
            dend = Math.min(dt, end);
          if (shift + bt < 0) err(3);
          for (; bt < dend; ++bt) buf[bt] = dict[shift + bt];
        }
        for (; bt < end; ++bt) buf[bt] = buf[bt - dt];
      }
    }
    st.l = lm, st.p = lpos, st.b = bt, st.f = final;
    if (lm) final = 1, st.m = lbt, st.d = dm, st.n = dbt;
  } while (!final);
  // don't reallocate for streams or user buffers
  return bt != buf.length && noBuf ? slc(buf, 0, bt) : buf.subarray(0, bt);
};
// starting at p, write the minimum number of bits that can hold v to d
var wbits = function (d, p, v) {
  v <<= p & 7;
  var o = p / 8 | 0;
  d[o] |= v;
  d[o + 1] |= v >> 8;
};
// starting at p, write the minimum number of bits (>8) that can hold v to d
var wbits16 = function (d, p, v) {
  v <<= p & 7;
  var o = p / 8 | 0;
  d[o] |= v;
  d[o + 1] |= v >> 8;
  d[o + 2] |= v >> 16;
};
// creates code lengths from a frequency table
var hTree = function (d, mb) {
  // Need extra info to make a tree
  var t = [];
  for (var i = 0; i < d.length; ++i) {
    if (d[i]) t.push({
      s: i,
      f: d[i]
    });
  }
  var s = t.length;
  var t2 = t.slice();
  if (!s) return {
    t: et,
    l: 0
  };
  if (s == 1) {
    var v = new u8(t[0].s + 1);
    v[t[0].s] = 1;
    return {
      t: v,
      l: 1
    };
  }
  t.sort(function (a, b) {
    return a.f - b.f;
  });
  // after i2 reaches last ind, will be stopped
  // freq must be greater than largest possible number of symbols
  t.push({
    s: -1,
    f: 25001
  });
  var l = t[0],
    r = t[1],
    i0 = 0,
    i1 = 1,
    i2 = 2;
  t[0] = {
    s: -1,
    f: l.f + r.f,
    l: l,
    r: r
  };
  // efficient algorithm from UZIP.js
  // i0 is lookbehind, i2 is lookahead - after processing two low-freq
  // symbols that combined have high freq, will start processing i2 (high-freq,
  // non-composite) symbols instead
  // see https://reddit.com/r/photopea/comments/ikekht/uzipjs_questions/
  while (i1 != s - 1) {
    l = t[t[i0].f < t[i2].f ? i0++ : i2++];
    r = t[i0 != i1 && t[i0].f < t[i2].f ? i0++ : i2++];
    t[i1++] = {
      s: -1,
      f: l.f + r.f,
      l: l,
      r: r
    };
  }
  var maxSym = t2[0].s;
  for (var i = 1; i < s; ++i) {
    if (t2[i].s > maxSym) maxSym = t2[i].s;
  }
  // code lengths
  var tr = new u16(maxSym + 1);
  // max bits in tree
  var mbt = ln(t[i1 - 1], tr, 0);
  if (mbt > mb) {
    // more algorithms from UZIP.js
    // TODO: find out how this code works (debt)
    //  ind    debt
    var i = 0,
      dt = 0;
    //    left            cost
    var lft = mbt - mb,
      cst = 1 << lft;
    t2.sort(function (a, b) {
      return tr[b.s] - tr[a.s] || a.f - b.f;
    });
    for (; i < s; ++i) {
      var i2_1 = t2[i].s;
      if (tr[i2_1] > mb) {
        dt += cst - (1 << mbt - tr[i2_1]);
        tr[i2_1] = mb;
      } else break;
    }
    dt >>= lft;
    while (dt > 0) {
      var i2_2 = t2[i].s;
      if (tr[i2_2] < mb) dt -= 1 << mb - tr[i2_2]++ - 1;else ++i;
    }
    for (; i >= 0 && dt; --i) {
      var i2_3 = t2[i].s;
      if (tr[i2_3] == mb) {
        --tr[i2_3];
        ++dt;
      }
    }
    mbt = mb;
  }
  return {
    t: new u8(tr),
    l: mbt
  };
};
// get the max length and assign length codes
var ln = function (n, l, d) {
  return n.s == -1 ? Math.max(ln(n.l, l, d + 1), ln(n.r, l, d + 1)) : l[n.s] = d;
};
// length codes generation
var lc = function (c) {
  var s = c.length;
  // Note that the semicolon was intentional
  while (s && !c[--s]);
  var cl = new u16(++s);
  //  ind      num         streak
  var cli = 0,
    cln = c[0],
    cls = 1;
  var w = function (v) {
    cl[cli++] = v;
  };
  for (var i = 1; i <= s; ++i) {
    if (c[i] == cln && i != s) ++cls;else {
      if (!cln && cls > 2) {
        for (; cls > 138; cls -= 138) w(32754);
        if (cls > 2) {
          w(cls > 10 ? cls - 11 << 5 | 28690 : cls - 3 << 5 | 12305);
          cls = 0;
        }
      } else if (cls > 3) {
        w(cln), --cls;
        for (; cls > 6; cls -= 6) w(8304);
        if (cls > 2) w(cls - 3 << 5 | 8208), cls = 0;
      }
      while (cls--) w(cln);
      cls = 1;
      cln = c[i];
    }
  }
  return {
    c: cl.subarray(0, cli),
    n: s
  };
};
// calculate the length of output from tree, code lengths
var clen = function (cf, cl) {
  var l = 0;
  for (var i = 0; i < cl.length; ++i) l += cf[i] * cl[i];
  return l;
};
// writes a fixed block
// returns the new bit pos
var wfblk = function (out, pos, dat) {
  // no need to write 00 as type: TypedArray defaults to 0
  var s = dat.length;
  var o = shft(pos + 2);
  out[o] = s & 255;
  out[o + 1] = s >> 8;
  out[o + 2] = out[o] ^ 255;
  out[o + 3] = out[o + 1] ^ 255;
  for (var i = 0; i < s; ++i) out[o + i + 4] = dat[i];
  return (o + 4 + s) * 8;
};
// writes a block
var wblk = function (dat, out, final, syms, lf, df, eb, li, bs, bl, p) {
  wbits(out, p++, final);
  ++lf[256];
  var _a = hTree(lf, 15),
    dlt = _a.t,
    mlb = _a.l;
  var _b = hTree(df, 15),
    ddt = _b.t,
    mdb = _b.l;
  var _c = lc(dlt),
    lclt = _c.c,
    nlc = _c.n;
  var _d = lc(ddt),
    lcdt = _d.c,
    ndc = _d.n;
  var lcfreq = new u16(19);
  for (var i = 0; i < lclt.length; ++i) ++lcfreq[lclt[i] & 31];
  for (var i = 0; i < lcdt.length; ++i) ++lcfreq[lcdt[i] & 31];
  var _e = hTree(lcfreq, 7),
    lct = _e.t,
    mlcb = _e.l;
  var nlcc = 19;
  for (; nlcc > 4 && !lct[clim[nlcc - 1]]; --nlcc);
  var flen = bl + 5 << 3;
  var ftlen = clen(lf, flt) + clen(df, fdt) + eb;
  var dtlen = clen(lf, dlt) + clen(df, ddt) + eb + 14 + 3 * nlcc + clen(lcfreq, lct) + 2 * lcfreq[16] + 3 * lcfreq[17] + 7 * lcfreq[18];
  if (bs >= 0 && flen <= ftlen && flen <= dtlen) return wfblk(out, p, dat.subarray(bs, bs + bl));
  var lm, ll, dm, dl;
  wbits(out, p, 1 + (dtlen < ftlen)), p += 2;
  if (dtlen < ftlen) {
    lm = hMap(dlt, mlb, 0), ll = dlt, dm = hMap(ddt, mdb, 0), dl = ddt;
    var llm = hMap(lct, mlcb, 0);
    wbits(out, p, nlc - 257);
    wbits(out, p + 5, ndc - 1);
    wbits(out, p + 10, nlcc - 4);
    p += 14;
    for (var i = 0; i < nlcc; ++i) wbits(out, p + 3 * i, lct[clim[i]]);
    p += 3 * nlcc;
    var lcts = [lclt, lcdt];
    for (var it = 0; it < 2; ++it) {
      var clct = lcts[it];
      for (var i = 0; i < clct.length; ++i) {
        var len = clct[i] & 31;
        wbits(out, p, llm[len]), p += lct[len];
        if (len > 15) wbits(out, p, clct[i] >> 5 & 127), p += clct[i] >> 12;
      }
    }
  } else {
    lm = flm, ll = flt, dm = fdm, dl = fdt;
  }
  for (var i = 0; i < li; ++i) {
    var sym = syms[i];
    if (sym > 255) {
      var len = sym >> 18 & 31;
      wbits16(out, p, lm[len + 257]), p += ll[len + 257];
      if (len > 7) wbits(out, p, sym >> 23 & 31), p += fleb[len];
      var dst = sym & 31;
      wbits16(out, p, dm[dst]), p += dl[dst];
      if (dst > 3) wbits16(out, p, sym >> 5 & 8191), p += fdeb[dst];
    } else {
      wbits16(out, p, lm[sym]), p += ll[sym];
    }
  }
  wbits16(out, p, lm[256]);
  return p + ll[256];
};
// deflate options (nice << 13) | chain
var deo = /*#__PURE__*/new i32([65540, 131080, 131088, 131104, 262176, 1048704, 1048832, 2114560, 2117632]);
// empty
var et = /*#__PURE__*/new u8(0);
// compresses data into a raw DEFLATE buffer
var dflt = function (dat, lvl, plvl, pre, post, st) {
  var s = st.z || dat.length;
  var o = new u8(pre + s + 5 * (1 + Math.ceil(s / 7000)) + post);
  // writing to this writes to the output buffer
  var w = o.subarray(pre, o.length - post);
  var lst = st.l;
  var pos = (st.r || 0) & 7;
  if (lvl) {
    if (pos) w[0] = st.r >> 3;
    var opt = deo[lvl - 1];
    var n = opt >> 13,
      c = opt & 8191;
    var msk_1 = (1 << plvl) - 1;
    //    prev 2-byte val map    curr 2-byte val map
    var prev = st.p || new u16(32768),
      head = st.h || new u16(msk_1 + 1);
    var bs1_1 = Math.ceil(plvl / 3),
      bs2_1 = 2 * bs1_1;
    var hsh = function (i) {
      return (dat[i] ^ dat[i + 1] << bs1_1 ^ dat[i + 2] << bs2_1) & msk_1;
    };
    // 24576 is an arbitrary number of maximum symbols per block
    // 424 buffer for last block
    var syms = new i32(25000);
    // length/literal freq   distance freq
    var lf = new u16(288),
      df = new u16(32);
    //  l/lcnt  exbits  index          l/lind  waitdx          blkpos
    var lc_1 = 0,
      eb = 0,
      i = st.i || 0,
      li = 0,
      wi = st.w || 0,
      bs = 0;
    for (; i + 2 < s; ++i) {
      // hash value
      var hv = hsh(i);
      // index mod 32768    previous index mod
      var imod = i & 32767,
        pimod = head[hv];
      prev[imod] = pimod;
      head[hv] = imod;
      // We always should modify head and prev, but only add symbols if
      // this data is not yet processed ("wait" for wait index)
      if (wi <= i) {
        // bytes remaining
        var rem = s - i;
        if ((lc_1 > 7000 || li > 24576) && (rem > 423 || !lst)) {
          pos = wblk(dat, w, 0, syms, lf, df, eb, li, bs, i - bs, pos);
          li = lc_1 = eb = 0, bs = i;
          for (var j = 0; j < 286; ++j) lf[j] = 0;
          for (var j = 0; j < 30; ++j) df[j] = 0;
        }
        //  len    dist   chain
        var l = 2,
          d = 0,
          ch_1 = c,
          dif = imod - pimod & 32767;
        if (rem > 2 && hv == hsh(i - dif)) {
          var maxn = Math.min(n, rem) - 1;
          var maxd = Math.min(32767, i);
          // max possible length
          // not capped at dif because decompressors implement "rolling" index population
          var ml = Math.min(258, rem);
          while (dif <= maxd && --ch_1 && imod != pimod) {
            if (dat[i + l] == dat[i + l - dif]) {
              var nl = 0;
              for (; nl < ml && dat[i + nl] == dat[i + nl - dif]; ++nl);
              if (nl > l) {
                l = nl, d = dif;
                // break out early when we reach "nice" (we are satisfied enough)
                if (nl > maxn) break;
                // now, find the rarest 2-byte sequence within this
                // length of literals and search for that instead.
                // Much faster than just using the start
                var mmd = Math.min(dif, nl - 2);
                var md = 0;
                for (var j = 0; j < mmd; ++j) {
                  var ti = i - dif + j & 32767;
                  var pti = prev[ti];
                  var cd = ti - pti & 32767;
                  if (cd > md) md = cd, pimod = ti;
                }
              }
            }
            // check the previous match
            imod = pimod, pimod = prev[imod];
            dif += imod - pimod & 32767;
          }
        }
        // d will be nonzero only when a match was found
        if (d) {
          // store both dist and len data in one int32
          // Make sure this is recognized as a len/dist with 28th bit (2^28)
          syms[li++] = 268435456 | revfl[l] << 18 | revfd[d];
          var lin = revfl[l] & 31,
            din = revfd[d] & 31;
          eb += fleb[lin] + fdeb[din];
          ++lf[257 + lin];
          ++df[din];
          wi = i + l;
          ++lc_1;
        } else {
          syms[li++] = dat[i];
          ++lf[dat[i]];
        }
      }
    }
    for (i = Math.max(i, wi); i < s; ++i) {
      syms[li++] = dat[i];
      ++lf[dat[i]];
    }
    pos = wblk(dat, w, lst, syms, lf, df, eb, li, bs, i - bs, pos);
    if (!lst) {
      st.r = pos & 7 | w[pos / 8 | 0] << 3;
      // shft(pos) now 1 less if pos & 7 != 0
      pos -= 7;
      st.h = head, st.p = prev, st.i = i, st.w = wi;
    }
  } else {
    for (var i = st.w || 0; i < s + lst; i += 65535) {
      // end
      var e = i + 65535;
      if (e >= s) {
        // write final block
        w[pos / 8 | 0] = lst;
        e = s;
      }
      pos = wfblk(w, pos + 1, dat.subarray(i, e));
    }
    st.i = s;
  }
  return slc(o, 0, pre + shft(pos) + post);
};
// Adler32
var adler = function () {
  var a = 1,
    b = 0;
  return {
    p: function (d) {
      // closures have awful performance
      var n = a,
        m = b;
      var l = d.length | 0;
      for (var i = 0; i != l;) {
        var e = Math.min(i + 2655, l);
        for (; i < e; ++i) m += n += d[i];
        n = (n & 65535) + 15 * (n >> 16), m = (m & 65535) + 15 * (m >> 16);
      }
      a = n, b = m;
    },
    d: function () {
      a %= 65521, b %= 65521;
      return (a & 255) << 24 | (a & 0xFF00) << 8 | (b & 255) << 8 | b >> 8;
    }
  };
};
// deflate with opts
var dopt = function (dat, opt, pre, post, st) {
  if (!st) {
    st = {
      l: 1
    };
    if (opt.dictionary) {
      var dict = opt.dictionary.subarray(-32768);
      var newDat = new u8(dict.length + dat.length);
      newDat.set(dict);
      newDat.set(dat, dict.length);
      dat = newDat;
      st.w = dict.length;
    }
  }
  return dflt(dat, opt.level == null ? 6 : opt.level, opt.mem == null ? st.l ? Math.ceil(Math.max(8, Math.min(13, Math.log(dat.length))) * 1.5) : 20 : 12 + opt.mem, pre, post, st);
};
// write bytes
var wbytes = function (d, b, v) {
  for (; v; ++b) d[b] = v, v >>>= 8;
};
// gzip footer: -8 to -4 = CRC, -4 to -0 is length
// gzip start
var gzs = function (d) {
  if (d[0] != 31 || d[1] != 139 || d[2] != 8) err(6, 'invalid gzip data');
  var flg = d[3];
  var st = 10;
  if (flg & 4) st += (d[10] | d[11] << 8) + 2;
  for (var zs = (flg >> 3 & 1) + (flg >> 4 & 1); zs > 0; zs -= !d[st++]);
  return st + (flg & 2);
};
// gzip length
var gzl = function (d) {
  var l = d.length;
  return (d[l - 4] | d[l - 3] << 8 | d[l - 2] << 16 | d[l - 1] << 24) >>> 0;
};
// zlib header
var zlh = function (c, o) {
  var lv = o.level,
    fl = lv == 0 ? 0 : lv < 6 ? 1 : lv == 9 ? 3 : 2;
  c[0] = 120, c[1] = fl << 6 | (o.dictionary && 32);
  c[1] |= 31 - (c[0] << 8 | c[1]) % 31;
  if (o.dictionary) {
    var h = adler();
    h.p(o.dictionary);
    wbytes(c, 2, h.d());
  }
};
// zlib start
var zls = function (d, dict) {
  if ((d[0] & 15) != 8 || d[0] >> 4 > 7 || (d[0] << 8 | d[1]) % 31) err(6, 'invalid zlib data');
  if ((d[1] >> 5 & 1) == +!dict) err(6, 'invalid zlib data: ' + (d[1] & 32 ? 'need' : 'unexpected') + ' dictionary');
  return (d[1] >> 3 & 4) + 2;
};
/**
 * Streaming DEFLATE decompression
 */
var Inflate = /*#__PURE__*/function () {
  function Inflate(opts, cb) {
    // no StrmOpt here to avoid adding to workerizer
    if (typeof opts == 'function') cb = opts, opts = {};
    this.ondata = cb;
    var dict = opts && opts.dictionary && opts.dictionary.subarray(-32768);
    this.s = {
      i: 0,
      b: dict ? dict.length : 0
    };
    this.o = new u8(32768);
    this.p = new u8(0);
    if (dict) this.o.set(dict);
  }
  Inflate.prototype.e = function (c) {
    if (!this.ondata) err(5);
    if (this.d) err(4);
    if (!this.p.length) this.p = c;else if (c.length) {
      var n = new u8(this.p.length + c.length);
      n.set(this.p), n.set(c, this.p.length), this.p = n;
    }
  };
  Inflate.prototype.c = function (final) {
    this.s.i = +(this.d = final || false);
    var bts = this.s.b;
    var dt = inflt(this.p, this.s, this.o);
    this.ondata(slc(dt, bts, this.s.b), this.d);
    this.o = slc(dt, this.s.b - 32768), this.s.b = this.o.length;
    this.p = slc(this.p, this.s.p / 8 | 0), this.s.p &= 7;
  };
  /**
   * Pushes a chunk to be inflated
   * @param chunk The chunk to push
   * @param final Whether this is the final chunk
   */
  Inflate.prototype.push = function (chunk, final) {
    this.e(chunk), this.c(final);
  };
  return Inflate;
}();
/**
 * Expands DEFLATE data with no wrapper
 * @param data The data to decompress
 * @param opts The decompression options
 * @returns The decompressed version of the data
 */
function inflateSync(data, opts) {
  return inflt(data, {
    i: 2
  }, opts, opts);
}
/**
 * Expands GZIP data
 * @param data The data to decompress
 * @param opts The decompression options
 * @returns The decompressed version of the data
 */
function gunzipSync(data, opts) {
  var st = gzs(data);
  if (st + 8 > data.length) err(6, 'invalid gzip data');
  return inflt(data.subarray(st, -8), {
    i: 2
  }, new u8(gzl(data)), opts);
}
/**
 * Compress data with Zlib
 * @param data The data to compress
 * @param opts The compression options
 * @returns The zlib-compressed version of the data
 */
function zlibSync(data, opts) {
  if (!opts) opts = {};
  var a = adler();
  a.p(data);
  var d = dopt(data, opts, opts.dictionary ? 6 : 2, 4);
  return zlh(d, opts), wbytes(d, d.length - 4, a.d()), d;
}
/**
 * Streaming Zlib decompression
 */
var Unzlib = /*#__PURE__*/function () {
  function Unzlib(opts, cb) {
    Inflate.call(this, opts, cb);
    this.v = opts && opts.dictionary ? 2 : 1;
  }
  /**
   * Pushes a chunk to be unzlibbed
   * @param chunk The chunk to push
   * @param final Whether this is the last chunk
   */
  Unzlib.prototype.push = function (chunk, final) {
    Inflate.prototype.e.call(this, chunk);
    if (this.v) {
      if (this.p.length < 6 && !final) return;
      this.p = this.p.subarray(zls(this.p, this.v - 1)), this.v = 0;
    }
    if (final) {
      if (this.p.length < 4) err(6, 'invalid zlib data');
      this.p = this.p.subarray(0, -4);
    }
    // necessary to prevent TS from using the closure value
    // This allows for workerization to function correctly
    Inflate.prototype.c.call(this, final);
  };
  return Unzlib;
}();
/**
 * Expands Zlib data
 * @param data The data to decompress
 * @param opts The decompression options
 * @returns The decompressed version of the data
 */
function unzlibSync(data, opts) {
  return inflt(data.subarray(zls(data, opts), -4), {
    i: 2
  }, opts, opts);
}
/**
 * Expands compressed GZIP, Zlib, or raw DEFLATE data, automatically detecting the format
 * @param data The data to decompress
 * @param opts The decompression options
 * @returns The decompressed version of the data
 */
function decompressSync(data, opts) {
  return data[0] == 31 && data[1] == 139 && data[2] == 8 ? gunzipSync(data, opts) : (data[0] & 15) != 8 || data[0] >> 4 > 7 || (data[0] << 8 | data[1]) % 31 ? inflateSync(data, opts) : unzlibSync(data, opts);
}
// text decoder
var td = typeof TextDecoder != 'undefined' && /*#__PURE__*/new TextDecoder();
// text decoder stream
var tds = 0;
try {
  td.decode(et, {
    stream: true
  });
  tds = 1;
} catch (e) {}

const crcTable = [];
for (let n = 0; n < 256; n++) {
  let c = n;
  for (let k = 0; k < 8; k++) {
    if (c & 1) {
      c = 0xedb88320 ^ c >>> 1;
    } else {
      c = c >>> 1;
    }
  }
  crcTable[n] = c;
}
const initialCrc = 0xffffffff;
function updateCrc(currentCrc, data, length) {
  let c = currentCrc;
  for (let n = 0; n < length; n++) {
    c = crcTable[(c ^ data[n]) & 0xff] ^ c >>> 8;
  }
  return c;
}
function crc(data, length) {
  return (updateCrc(initialCrc, data, length) ^ initialCrc) >>> 0;
}
function checkCrc(buffer, crcLength, chunkName) {
  const expectedCrc = buffer.readUint32();
  const actualCrc = crc(new Uint8Array(buffer.buffer, buffer.byteOffset + buffer.offset - crcLength - 4, crcLength), crcLength); // "- 4" because we already advanced by reading the CRC
  if (actualCrc !== expectedCrc) {
    throw new Error(`CRC mismatch for chunk ${chunkName}. Expected ${expectedCrc}, found ${actualCrc}`);
  }
}
function writeCrc(buffer, length) {
  buffer.writeUint32(crc(new Uint8Array(buffer.buffer, buffer.byteOffset + buffer.offset - length, length), length));
}

function unfilterNone(currentLine, newLine, bytesPerLine) {
  for (let i = 0; i < bytesPerLine; i++) {
    newLine[i] = currentLine[i];
  }
}
function unfilterSub(currentLine, newLine, bytesPerLine, bytesPerPixel) {
  let i = 0;
  for (; i < bytesPerPixel; i++) {
    // just copy first bytes
    newLine[i] = currentLine[i];
  }
  for (; i < bytesPerLine; i++) {
    newLine[i] = currentLine[i] + newLine[i - bytesPerPixel] & 0xff;
  }
}
function unfilterUp(currentLine, newLine, prevLine, bytesPerLine) {
  let i = 0;
  if (prevLine.length === 0) {
    // just copy bytes for first line
    for (; i < bytesPerLine; i++) {
      newLine[i] = currentLine[i];
    }
  } else {
    for (; i < bytesPerLine; i++) {
      newLine[i] = currentLine[i] + prevLine[i] & 0xff;
    }
  }
}
function unfilterAverage(currentLine, newLine, prevLine, bytesPerLine, bytesPerPixel) {
  let i = 0;
  if (prevLine.length === 0) {
    for (; i < bytesPerPixel; i++) {
      newLine[i] = currentLine[i];
    }
    for (; i < bytesPerLine; i++) {
      newLine[i] = currentLine[i] + (newLine[i - bytesPerPixel] >> 1) & 0xff;
    }
  } else {
    for (; i < bytesPerPixel; i++) {
      newLine[i] = currentLine[i] + (prevLine[i] >> 1) & 0xff;
    }
    for (; i < bytesPerLine; i++) {
      newLine[i] = currentLine[i] + (newLine[i - bytesPerPixel] + prevLine[i] >> 1) & 0xff;
    }
  }
}
function unfilterPaeth(currentLine, newLine, prevLine, bytesPerLine, bytesPerPixel) {
  let i = 0;
  if (prevLine.length === 0) {
    for (; i < bytesPerPixel; i++) {
      newLine[i] = currentLine[i];
    }
    for (; i < bytesPerLine; i++) {
      newLine[i] = currentLine[i] + newLine[i - bytesPerPixel] & 0xff;
    }
  } else {
    for (; i < bytesPerPixel; i++) {
      newLine[i] = currentLine[i] + prevLine[i] & 0xff;
    }
    for (; i < bytesPerLine; i++) {
      newLine[i] = currentLine[i] + paethPredictor(newLine[i - bytesPerPixel], prevLine[i], prevLine[i - bytesPerPixel]) & 0xff;
    }
  }
}
function paethPredictor(a, b, c) {
  const p = a + b - c;
  const pa = Math.abs(p - a);
  const pb = Math.abs(p - b);
  const pc = Math.abs(p - c);
  if (pa <= pb && pa <= pc) return a;else if (pb <= pc) return b;else return c;
}

/**
 * Apllies filter on scanline based on the filter type.
 * @param filterType - The filter type to apply.
 * @param currentLine - The current line of pixel data.
 * @param newLine - The new line of pixel data.
 * @param prevLine - The previous line of pixel data.
 * @param passLineBytes - The number of bytes in the pass line.
 * @param bytesPerPixel - The number of bytes per pixel.
 */
function applyUnfilter(filterType, currentLine, newLine, prevLine, passLineBytes, bytesPerPixel) {
  switch (filterType) {
    case 0:
      unfilterNone(currentLine, newLine, passLineBytes);
      break;
    case 1:
      unfilterSub(currentLine, newLine, passLineBytes, bytesPerPixel);
      break;
    case 2:
      unfilterUp(currentLine, newLine, prevLine, passLineBytes);
      break;
    case 3:
      unfilterAverage(currentLine, newLine, prevLine, passLineBytes, bytesPerPixel);
      break;
    case 4:
      unfilterPaeth(currentLine, newLine, prevLine, passLineBytes, bytesPerPixel);
      break;
    default:
      throw new Error(`Unsupported filter: ${filterType}`);
  }
}

const uint16$1 = new Uint16Array([0x00ff]);
const uint8$1 = new Uint8Array(uint16$1.buffer);
const osIsLittleEndian$1 = uint8$1[0] === 0xff;
/**
 * Decodes the Adam7 interlaced PNG data.
 * @param params - DecodeInterlaceNullParams
 * @returns - array of pixel data.
 */
function decodeInterlaceAdam7(params) {
  const {
    data,
    width,
    height,
    channels,
    depth
  } = params;
  // Adam7 interlacing pattern
  const passes = [{
    x: 0,
    y: 0,
    xStep: 8,
    yStep: 8
  },
  // Pass 1
  {
    x: 4,
    y: 0,
    xStep: 8,
    yStep: 8
  },
  // Pass 2
  {
    x: 0,
    y: 4,
    xStep: 4,
    yStep: 8
  },
  // Pass 3
  {
    x: 2,
    y: 0,
    xStep: 4,
    yStep: 4
  },
  // Pass 4
  {
    x: 0,
    y: 2,
    xStep: 2,
    yStep: 4
  },
  // Pass 5
  {
    x: 1,
    y: 0,
    xStep: 2,
    yStep: 2
  },
  // Pass 6
  {
    x: 0,
    y: 1,
    xStep: 1,
    yStep: 2
  } // Pass 7
  ];
  const bytesPerPixel = Math.ceil(depth / 8) * channels;
  const resultData = new Uint8Array(height * width * bytesPerPixel);
  let offset = 0;
  // Process each pass
  for (let passIndex = 0; passIndex < 7; passIndex++) {
    const pass = passes[passIndex];
    // Calculate pass dimensions
    const passWidth = Math.ceil((width - pass.x) / pass.xStep);
    const passHeight = Math.ceil((height - pass.y) / pass.yStep);
    if (passWidth <= 0 || passHeight <= 0) continue;
    const passLineBytes = passWidth * bytesPerPixel;
    const prevLine = new Uint8Array(passLineBytes);
    // Process each scanline in this pass
    for (let y = 0; y < passHeight; y++) {
      // First byte is the filter type
      const filterType = data[offset++];
      const currentLine = data.subarray(offset, offset + passLineBytes);
      offset += passLineBytes;
      // Create a new line for the unfiltered data
      const newLine = new Uint8Array(passLineBytes);
      // Apply the appropriate unfilter
      applyUnfilter(filterType, currentLine, newLine, prevLine, passLineBytes, bytesPerPixel);
      prevLine.set(newLine);
      for (let x = 0; x < passWidth; x++) {
        const outputX = pass.x + x * pass.xStep;
        const outputY = pass.y + y * pass.yStep;
        if (outputX >= width || outputY >= height) continue;
        for (let i = 0; i < bytesPerPixel; i++) {
          resultData[(outputY * width + outputX) * bytesPerPixel + i] = newLine[x * bytesPerPixel + i];
        }
      }
    }
  }
  if (depth === 16) {
    const uint16Data = new Uint16Array(resultData.buffer);
    if (osIsLittleEndian$1) {
      for (let k = 0; k < uint16Data.length; k++) {
        // PNG is always big endian. Swap the bytes.
        uint16Data[k] = swap16$1(uint16Data[k]);
      }
    }
    return uint16Data;
  } else {
    return resultData;
  }
}
function swap16$1(val) {
  return (val & 0xff) << 8 | val >> 8 & 0xff;
}

const uint16 = new Uint16Array([0x00ff]);
const uint8 = new Uint8Array(uint16.buffer);
const osIsLittleEndian = uint8[0] === 0xff;
const empty = new Uint8Array(0);
function decodeInterlaceNull(params) {
  const {
    data,
    width,
    height,
    channels,
    depth
  } = params;
  const bytesPerPixel = Math.ceil(depth / 8) * channels;
  const bytesPerLine = Math.ceil(depth / 8 * channels * width);
  const newData = new Uint8Array(height * bytesPerLine);
  let prevLine = empty;
  let offset = 0;
  let currentLine;
  let newLine;
  for (let i = 0; i < height; i++) {
    currentLine = data.subarray(offset + 1, offset + 1 + bytesPerLine);
    newLine = newData.subarray(i * bytesPerLine, (i + 1) * bytesPerLine);
    switch (data[offset]) {
      case 0:
        unfilterNone(currentLine, newLine, bytesPerLine);
        break;
      case 1:
        unfilterSub(currentLine, newLine, bytesPerLine, bytesPerPixel);
        break;
      case 2:
        unfilterUp(currentLine, newLine, prevLine, bytesPerLine);
        break;
      case 3:
        unfilterAverage(currentLine, newLine, prevLine, bytesPerLine, bytesPerPixel);
        break;
      case 4:
        unfilterPaeth(currentLine, newLine, prevLine, bytesPerLine, bytesPerPixel);
        break;
      default:
        throw new Error(`Unsupported filter: ${data[offset]}`);
    }
    prevLine = newLine;
    offset += bytesPerLine + 1;
  }
  if (depth === 16) {
    const uint16Data = new Uint16Array(newData.buffer);
    if (osIsLittleEndian) {
      for (let k = 0; k < uint16Data.length; k++) {
        // PNG is always big endian. Swap the bytes.
        uint16Data[k] = swap16(uint16Data[k]);
      }
    }
    return uint16Data;
  } else {
    return newData;
  }
}
function swap16(val) {
  return (val & 0xff) << 8 | val >> 8 & 0xff;
}

// https://www.w3.org/TR/PNG/#5PNG-file-signature
const pngSignature = Uint8Array.of(137, 80, 78, 71, 13, 10, 26, 10);
function writeSignature(buffer) {
  buffer.writeBytes(pngSignature);
}
function checkSignature(buffer) {
  if (!hasPngSignature(buffer.readBytes(pngSignature.length))) {
    throw new Error('wrong PNG signature');
  }
}
function hasPngSignature(array) {
  if (array.length < pngSignature.length) {
    return false;
  }
  for (let i = 0; i < pngSignature.length; i++) {
    if (array[i] !== pngSignature[i]) {
      return false;
    }
  }
  return true;
}

// https://www.w3.org/TR/png/#11tEXt
const textChunkName = 'tEXt';
const NULL = 0;
const latin1Decoder = new TextDecoder('latin1');
function validateKeyword(keyword) {
  validateLatin1(keyword);
  if (keyword.length === 0 || keyword.length > 79) {
    throw new Error('keyword length must be between 1 and 79');
  }
}
// eslint-disable-next-line no-control-regex
const latin1Regex = /^[\u0000-\u00FF]*$/;
function validateLatin1(text) {
  if (!latin1Regex.test(text)) {
    throw new Error('invalid latin1 text');
  }
}
function decodetEXt(text, buffer, length) {
  const keyword = readKeyword(buffer);
  text[keyword] = readLatin1(buffer, length - keyword.length - 1);
}
function encodetEXt(buffer, keyword, text) {
  validateKeyword(keyword);
  validateLatin1(text);
  const length = keyword.length + 1 /* NULL */ + text.length;
  buffer.writeUint32(length);
  buffer.writeChars(textChunkName);
  buffer.writeChars(keyword);
  buffer.writeByte(NULL);
  buffer.writeChars(text);
  writeCrc(buffer, length + 4);
}
// https://www.w3.org/TR/png/#11keywords
function readKeyword(buffer) {
  buffer.mark();
  while (buffer.readByte() !== NULL) {
    /* advance */
  }
  const end = buffer.offset;
  buffer.reset();
  const keyword = latin1Decoder.decode(buffer.readBytes(end - buffer.offset - 1));
  // NULL
  buffer.skip(1);
  validateKeyword(keyword);
  return keyword;
}
function readLatin1(buffer, length) {
  return latin1Decoder.decode(buffer.readBytes(length));
}

const ColorType = {
  UNKNOWN: -1,
  GREYSCALE: 0,
  TRUECOLOUR: 2,
  INDEXED_COLOUR: 3,
  GREYSCALE_ALPHA: 4,
  TRUECOLOUR_ALPHA: 6
};
const CompressionMethod = {
  UNKNOWN: -1,
  DEFLATE: 0
};
const FilterMethod = {
  UNKNOWN: -1,
  ADAPTIVE: 0
};
const InterlaceMethod = {
  UNKNOWN: -1,
  NO_INTERLACE: 0,
  ADAM7: 1
};
const DisposeOpType = {
  NONE: 0,
  BACKGROUND: 1,
  PREVIOUS: 2
};
const BlendOpType = {
  SOURCE: 0,
  OVER: 1
};

class PngDecoder extends IOBuffer {
  _checkCrc;
  _inflator;
  _png;
  _apng;
  _end;
  _hasPalette;
  _palette;
  _hasTransparency;
  _transparency;
  _compressionMethod;
  _filterMethod;
  _interlaceMethod;
  _colorType;
  _isAnimated;
  _numberOfFrames;
  _numberOfPlays;
  _frames;
  _writingDataChunks;
  _chunks;
  _inflatorResult;
  constructor(data, options = {}) {
    super(data);
    const {
      checkCrc = false
    } = options;
    this._checkCrc = checkCrc;
    this._inflator = new Unzlib((chunk, final) => {
      this._chunks.push(chunk);
      if (final) {
        const totalLength = this._chunks.reduce((sum, c) => sum + c.length, 0);
        this._inflatorResult = new Uint8Array(totalLength);
        let offset = 0;
        for (const chunk of this._chunks) {
          this._inflatorResult.set(chunk, offset);
          offset += chunk.length;
        }
        this._chunks = [];
      }
    });
    this._chunks = [];
    this._png = {
      width: -1,
      height: -1,
      channels: -1,
      data: new Uint8Array(0),
      depth: 1,
      text: {}
    };
    this._apng = {
      width: -1,
      height: -1,
      channels: -1,
      depth: 1,
      numberOfFrames: 1,
      numberOfPlays: 0,
      text: {},
      frames: []
    };
    this._end = false;
    this._hasPalette = false;
    this._palette = [];
    this._hasTransparency = false;
    this._transparency = new Uint16Array(0);
    this._compressionMethod = CompressionMethod.UNKNOWN;
    this._filterMethod = FilterMethod.UNKNOWN;
    this._interlaceMethod = InterlaceMethod.UNKNOWN;
    this._colorType = ColorType.UNKNOWN;
    this._isAnimated = false;
    this._numberOfFrames = 1;
    this._numberOfPlays = 0;
    this._frames = [];
    this._writingDataChunks = false;
    this._inflatorResult = new Uint8Array(0);
    // PNG is always big endian
    // https://www.w3.org/TR/PNG/#7Integers-and-byte-order
    this.setBigEndian();
  }
  decode() {
    checkSignature(this);
    while (!this._end) {
      const length = this.readUint32();
      const type = this.readChars(4);
      this.decodeChunk(length, type);
    }
    this._inflator.push(new Uint8Array(0), true);
    this.decodeImage();
    return this._png;
  }
  decodeApng() {
    checkSignature(this);
    while (!this._end) {
      const length = this.readUint32();
      const type = this.readChars(4);
      this.decodeApngChunk(length, type);
    }
    this.decodeApngImage();
    return this._apng;
  }
  // https://www.w3.org/TR/PNG/#5Chunk-layout
  decodeChunk(length, type) {
    const offset = this.offset;
    switch (type) {
      // 11.2 Critical chunks
      case 'IHDR':
        // 11.2.2 IHDR Image header
        this.decodeIHDR();
        break;
      case 'PLTE':
        // 11.2.3 PLTE Palette
        this.decodePLTE(length);
        break;
      case 'IDAT':
        // 11.2.4 IDAT Image data
        this.decodeIDAT(length);
        break;
      case 'IEND':
        // 11.2.5 IEND Image trailer
        this._end = true;
        break;
      // 11.3 Ancillary chunks
      case 'tRNS':
        // 11.3.2.1 tRNS Transparency
        this.decodetRNS(length);
        break;
      case 'iCCP':
        // 11.3.3.3 iCCP Embedded ICC profile
        this.decodeiCCP(length);
        break;
      case textChunkName:
        // 11.3.4.3 tEXt Textual data
        decodetEXt(this._png.text, this, length);
        break;
      case 'pHYs':
        // 11.3.5.3 pHYs Physical pixel dimensions
        this.decodepHYs();
        break;
      default:
        this.skip(length);
        break;
    }
    if (this.offset - offset !== length) {
      throw new Error(`Length mismatch while decoding chunk ${type}`);
    }
    if (this._checkCrc) {
      checkCrc(this, length + 4, type);
    } else {
      this.skip(4);
    }
  }
  decodeApngChunk(length, type) {
    const offset = this.offset;
    if (type !== 'fdAT' && type !== 'IDAT' && this._writingDataChunks) {
      this.pushDataToFrame();
    }
    switch (type) {
      case 'acTL':
        this.decodeACTL();
        break;
      case 'fcTL':
        this.decodeFCTL();
        break;
      case 'fdAT':
        this.decodeFDAT(length);
        break;
      default:
        this.decodeChunk(length, type);
        this.offset = offset + length;
        break;
    }
    if (this.offset - offset !== length) {
      throw new Error(`Length mismatch while decoding chunk ${type}`);
    }
    if (this._checkCrc) {
      checkCrc(this, length + 4, type);
    } else {
      this.skip(4);
    }
  }
  // https://www.w3.org/TR/PNG/#11IHDR
  decodeIHDR() {
    const image = this._png;
    image.width = this.readUint32();
    image.height = this.readUint32();
    image.depth = checkBitDepth(this.readUint8());
    const colorType = this.readUint8();
    this._colorType = colorType;
    let channels;
    switch (colorType) {
      case ColorType.GREYSCALE:
        channels = 1;
        break;
      case ColorType.TRUECOLOUR:
        channels = 3;
        break;
      case ColorType.INDEXED_COLOUR:
        channels = 1;
        break;
      case ColorType.GREYSCALE_ALPHA:
        channels = 2;
        break;
      case ColorType.TRUECOLOUR_ALPHA:
        channels = 4;
        break;
      // Kept for exhaustiveness.
      // eslint-disable-next-line unicorn/no-useless-switch-case
      case ColorType.UNKNOWN:
      default:
        throw new Error(`Unknown color type: ${colorType}`);
    }
    this._png.channels = channels;
    this._compressionMethod = this.readUint8();
    if (this._compressionMethod !== CompressionMethod.DEFLATE) {
      throw new Error(`Unsupported compression method: ${this._compressionMethod}`);
    }
    this._filterMethod = this.readUint8();
    this._interlaceMethod = this.readUint8();
  }
  decodeACTL() {
    this._numberOfFrames = this.readUint32();
    this._numberOfPlays = this.readUint32();
    this._isAnimated = true;
  }
  decodeFCTL() {
    const image = {
      sequenceNumber: this.readUint32(),
      width: this.readUint32(),
      height: this.readUint32(),
      xOffset: this.readUint32(),
      yOffset: this.readUint32(),
      delayNumber: this.readUint16(),
      delayDenominator: this.readUint16(),
      disposeOp: this.readUint8(),
      blendOp: this.readUint8(),
      data: new Uint8Array(0)
    };
    this._frames.push(image);
  }
  // https://www.w3.org/TR/PNG/#11PLTE
  decodePLTE(length) {
    if (length % 3 !== 0) {
      throw new RangeError(`PLTE field length must be a multiple of 3. Got ${length}`);
    }
    const l = length / 3;
    this._hasPalette = true;
    const palette = [];
    this._palette = palette;
    for (let i = 0; i < l; i++) {
      palette.push([this.readUint8(), this.readUint8(), this.readUint8()]);
    }
  }
  // https://www.w3.org/TR/PNG/#11IDAT
  decodeIDAT(length) {
    this._writingDataChunks = true;
    const dataLength = length;
    const dataOffset = this.offset + this.byteOffset;
    try {
      this._inflator.push(new Uint8Array(this.buffer, dataOffset, dataLength), false);
    } catch (error) {
      throw new Error('Error while decompressing the data:', {
        cause: error
      });
    }
    this.skip(length);
  }
  decodeFDAT(length) {
    this._writingDataChunks = true;
    let dataLength = length;
    let dataOffset = this.offset + this.byteOffset;
    dataOffset += 4;
    dataLength -= 4;
    try {
      this._inflator.push(new Uint8Array(this.buffer, dataOffset, dataLength), false);
    } catch (error) {
      throw new Error('Error while decompressing the data:', {
        cause: error
      });
    }
    this.skip(length);
  }
  // https://www.w3.org/TR/PNG/#11tRNS
  decodetRNS(length) {
    switch (this._colorType) {
      case ColorType.GREYSCALE:
      case ColorType.TRUECOLOUR:
        {
          if (length % 2 !== 0) {
            throw new RangeError(`tRNS chunk length must be a multiple of 2. Got ${length}`);
          }
          if (length / 2 > this._png.width * this._png.height) {
            throw new Error(`tRNS chunk contains more alpha values than there are pixels (${length / 2} vs ${this._png.width * this._png.height})`);
          }
          this._hasTransparency = true;
          this._transparency = new Uint16Array(length / 2);
          for (let i = 0; i < length / 2; i++) {
            this._transparency[i] = this.readUint16();
          }
          break;
        }
      case ColorType.INDEXED_COLOUR:
        {
          if (length > this._palette.length) {
            throw new Error(`tRNS chunk contains more alpha values than there are palette colors (${length} vs ${this._palette.length})`);
          }
          let i = 0;
          for (; i < length; i++) {
            const alpha = this.readByte();
            this._palette[i].push(alpha);
          }
          for (; i < this._palette.length; i++) {
            this._palette[i].push(255);
          }
          break;
        }
      // Kept for exhaustiveness.
      /* eslint-disable unicorn/no-useless-switch-case */
      case ColorType.UNKNOWN:
      case ColorType.GREYSCALE_ALPHA:
      case ColorType.TRUECOLOUR_ALPHA:
      default:
        {
          throw new Error(`tRNS chunk is not supported for color type ${this._colorType}`);
        }
      /* eslint-enable unicorn/no-useless-switch-case */
    }
  }
  // https://www.w3.org/TR/PNG/#11iCCP
  decodeiCCP(length) {
    const name = readKeyword(this);
    const compressionMethod = this.readUint8();
    if (compressionMethod !== CompressionMethod.DEFLATE) {
      throw new Error(`Unsupported iCCP compression method: ${compressionMethod}`);
    }
    const compressedProfile = this.readBytes(length - name.length - 2);
    this._png.iccEmbeddedProfile = {
      name,
      profile: unzlibSync(compressedProfile)
    };
  }
  // https://www.w3.org/TR/PNG/#11pHYs
  decodepHYs() {
    const ppuX = this.readUint32();
    const ppuY = this.readUint32();
    const unitSpecifier = this.readByte();
    this._png.resolution = {
      x: ppuX,
      y: ppuY,
      unit: unitSpecifier
    };
  }
  decodeApngImage() {
    this._apng.width = this._png.width;
    this._apng.height = this._png.height;
    this._apng.channels = this._png.channels;
    this._apng.depth = this._png.depth;
    this._apng.numberOfFrames = this._numberOfFrames;
    this._apng.numberOfPlays = this._numberOfPlays;
    this._apng.text = this._png.text;
    this._apng.resolution = this._png.resolution;
    for (let i = 0; i < this._numberOfFrames; i++) {
      const newFrame = {
        sequenceNumber: this._frames[i].sequenceNumber,
        delayNumber: this._frames[i].delayNumber,
        delayDenominator: this._frames[i].delayDenominator,
        data: this._apng.depth === 8 ? new Uint8Array(this._apng.width * this._apng.height * this._apng.channels) : new Uint16Array(this._apng.width * this._apng.height * this._apng.channels)
      };
      const frame = this._frames.at(i);
      if (frame) {
        frame.data = decodeInterlaceNull({
          data: frame.data,
          width: frame.width,
          height: frame.height,
          channels: this._apng.channels,
          depth: this._apng.depth
        });
        if (this._hasPalette) {
          this._apng.palette = this._palette;
        }
        if (this._hasTransparency) {
          this._apng.transparency = this._transparency;
        }
        if (i === 0 || frame.xOffset === 0 && frame.yOffset === 0 && frame.width === this._png.width && frame.height === this._png.height) {
          newFrame.data = frame.data;
        } else {
          const prevFrame = this._apng.frames.at(i - 1);
          this.disposeFrame(frame, prevFrame, newFrame);
          this.addFrameDataToCanvas(newFrame, frame);
        }
        this._apng.frames.push(newFrame);
      }
    }
    return this._apng;
  }
  disposeFrame(frame, prevFrame, imageFrame) {
    switch (frame.disposeOp) {
      case DisposeOpType.NONE:
        break;
      case DisposeOpType.BACKGROUND:
        for (let row = 0; row < this._png.height; row++) {
          for (let col = 0; col < this._png.width; col++) {
            const index = (row * frame.width + col) * this._png.channels;
            for (let channel = 0; channel < this._png.channels; channel++) {
              imageFrame.data[index + channel] = 0;
            }
          }
        }
        break;
      case DisposeOpType.PREVIOUS:
        imageFrame.data.set(prevFrame.data);
        break;
      default:
        throw new Error('Unknown disposeOp');
    }
  }
  addFrameDataToCanvas(imageFrame, frame) {
    const maxValue = 1 << this._png.depth;
    const calculatePixelIndices = (row, col) => {
      const index = ((row + frame.yOffset) * this._png.width + frame.xOffset + col) * this._png.channels;
      const frameIndex = (row * frame.width + col) * this._png.channels;
      return {
        index,
        frameIndex
      };
    };
    switch (frame.blendOp) {
      case BlendOpType.SOURCE:
        for (let row = 0; row < frame.height; row++) {
          for (let col = 0; col < frame.width; col++) {
            const {
              index,
              frameIndex
            } = calculatePixelIndices(row, col);
            for (let channel = 0; channel < this._png.channels; channel++) {
              imageFrame.data[index + channel] = frame.data[frameIndex + channel];
            }
          }
        }
        break;
      // https://www.w3.org/TR/png-3/#13Alpha-channel-processing
      case BlendOpType.OVER:
        for (let row = 0; row < frame.height; row++) {
          for (let col = 0; col < frame.width; col++) {
            const {
              index,
              frameIndex
            } = calculatePixelIndices(row, col);
            for (let channel = 0; channel < this._png.channels; channel++) {
              const sourceAlpha = frame.data[frameIndex + this._png.channels - 1] / maxValue;
              const foregroundValue = channel % (this._png.channels - 1) === 0 ? 1 : frame.data[frameIndex + channel];
              const value = Math.floor(sourceAlpha * foregroundValue + (1 - sourceAlpha) * imageFrame.data[index + channel]);
              imageFrame.data[index + channel] += value;
            }
          }
        }
        break;
      default:
        throw new Error('Unknown blendOp');
    }
  }
  decodeImage() {
    const data = this._inflatorResult;
    if (this._filterMethod !== FilterMethod.ADAPTIVE) {
      throw new Error(`Filter method ${this._filterMethod} not supported`);
    }
    if (this._interlaceMethod === InterlaceMethod.NO_INTERLACE) {
      this._png.data = decodeInterlaceNull({
        data,
        width: this._png.width,
        height: this._png.height,
        channels: this._png.channels,
        depth: this._png.depth
      });
    } else if (this._interlaceMethod === InterlaceMethod.ADAM7) {
      this._png.data = decodeInterlaceAdam7({
        data,
        width: this._png.width,
        height: this._png.height,
        channels: this._png.channels,
        depth: this._png.depth
      });
    } else {
      throw new Error(`Interlace method ${this._interlaceMethod} not supported`);
    }
    if (this._hasPalette) {
      this._png.palette = this._palette;
    }
    if (this._hasTransparency) {
      this._png.transparency = this._transparency;
    }
  }
  pushDataToFrame() {
    // Finalize the current stream
    this._inflator.push(new Uint8Array(0), true); // This triggers final=true in callback
    const result = this._inflatorResult;
    const lastFrame = this._frames.at(-1);
    if (lastFrame) {
      lastFrame.data = result;
    } else {
      this._frames.push({
        sequenceNumber: 0,
        width: this._png.width,
        height: this._png.height,
        xOffset: 0,
        yOffset: 0,
        delayNumber: 0,
        delayDenominator: 0,
        disposeOp: DisposeOpType.NONE,
        blendOp: BlendOpType.SOURCE,
        data: result
      });
    }
    // Create new inflator for next frame
    this._inflator = new Unzlib((chunk, final) => {
      this._chunks.push(chunk);
      if (final) {
        const totalLength = this._chunks.reduce((sum, c) => sum + c.length, 0);
        this._inflatorResult = new Uint8Array(totalLength);
        let offset = 0;
        for (const chunk of this._chunks) {
          this._inflatorResult.set(chunk, offset);
          offset += chunk.length;
        }
        this._chunks = [];
      }
    });
    this._chunks = [];
    this._writingDataChunks = false;
  }
}
function checkBitDepth(value) {
  if (value !== 1 && value !== 2 && value !== 4 && value !== 8 && value !== 16) {
    throw new Error(`invalid bit depth: ${value}`);
  }
  return value;
}

const defaultZlibOptions = {
  level: 3
};
class PngEncoder extends IOBuffer {
  _png;
  _zlibOptions;
  _colorType;
  _interlaceMethod;
  constructor(data, options = {}) {
    super();
    this._colorType = ColorType.UNKNOWN;
    this._zlibOptions = {
      ...defaultZlibOptions,
      ...options.zlib
    };
    this._png = this._checkData(data);
    this._interlaceMethod = (options.interlace === 'Adam7' ? InterlaceMethod.ADAM7 : InterlaceMethod.NO_INTERLACE) ?? InterlaceMethod.NO_INTERLACE;
    this.setBigEndian();
  }
  encode() {
    writeSignature(this);
    this.encodeIHDR();
    if (this._png.palette) {
      this.encodePLTE();
      if (this._png.palette[0].length === 4) {
        this.encodeTRNS();
      }
    }
    this.encodeData();
    if (this._png.text) {
      for (const [keyword, text] of Object.entries(this._png.text)) {
        encodetEXt(this, keyword, text);
      }
    }
    this.encodeIEND();
    return this.toArray();
  }
  // https://www.w3.org/TR/PNG/#11IHDR
  encodeIHDR() {
    this.writeUint32(13);
    this.writeChars('IHDR');
    this.writeUint32(this._png.width);
    this.writeUint32(this._png.height);
    this.writeByte(this._png.depth);
    this.writeByte(this._colorType);
    this.writeByte(CompressionMethod.DEFLATE);
    this.writeByte(FilterMethod.ADAPTIVE);
    this.writeByte(this._interlaceMethod);
    writeCrc(this, 17);
  }
  // https://www.w3.org/TR/PNG/#11IEND
  encodeIEND() {
    this.writeUint32(0);
    this.writeChars('IEND');
    writeCrc(this, 4);
  }
  encodePLTE() {
    const paletteLength = this._png.palette?.length * 3;
    this.writeUint32(paletteLength);
    this.writeChars('PLTE');
    for (const color of this._png.palette) {
      this.writeByte(color[0]);
      this.writeByte(color[1]);
      this.writeByte(color[2]);
    }
    writeCrc(this, 4 + paletteLength);
  }
  encodeTRNS() {
    const alpha = this._png.palette.filter(color => {
      return color.at(-1) !== 255;
    });
    this.writeUint32(alpha.length);
    this.writeChars('tRNS');
    for (const el of alpha) {
      this.writeByte(el.at(-1));
    }
    writeCrc(this, 4 + alpha.length);
  }
  // https://www.w3.org/TR/PNG/#11IDAT
  encodeIDAT(data) {
    this.writeUint32(data.length);
    this.writeChars('IDAT');
    this.writeBytes(data);
    writeCrc(this, data.length + 4);
  }
  encodeData() {
    const {
      width,
      height,
      channels,
      depth,
      data
    } = this._png;
    const slotsPerLine = depth <= 8 ? Math.ceil(width * depth / 8) * channels : Math.ceil(width * depth / 8 * channels / 2);
    const newData = new IOBuffer().setBigEndian();
    let offset = 0;
    if (this._interlaceMethod === InterlaceMethod.NO_INTERLACE) {
      for (let i = 0; i < height; i++) {
        newData.writeByte(0); // no filter
        if (depth === 16) {
          offset = writeDataUint16(data, newData, slotsPerLine, offset);
        } else {
          offset = writeDataBytes(data, newData, slotsPerLine, offset);
        }
      }
    } else if (this._interlaceMethod === InterlaceMethod.ADAM7) {
      // Adam7 interlacing
      offset = writeDataInterlaced(this._png, data, newData, offset);
    }
    const buffer = newData.toArray();
    const compressed = zlibSync(buffer, this._zlibOptions);
    this.encodeIDAT(compressed);
  }
  _checkData(data) {
    const {
      colorType,
      channels,
      depth
    } = getColorType(data, data.palette);
    const png = {
      width: checkInteger(data.width, 'width'),
      height: checkInteger(data.height, 'height'),
      channels,
      data: data.data,
      depth,
      text: data.text,
      palette: data.palette
    };
    this._colorType = colorType;
    const expectedSize = depth < 8 ? Math.ceil(png.width * depth / 8) * png.height * channels : png.width * png.height * channels;
    if (png.data.length !== expectedSize) {
      throw new RangeError(`wrong data size. Found ${png.data.length}, expected ${expectedSize}`);
    }
    return png;
  }
}
function checkInteger(value, name) {
  if (Number.isInteger(value) && value > 0) {
    return value;
  }
  throw new TypeError(`${name} must be a positive integer`);
}
function getColorType(data, palette) {
  const {
    channels = 4,
    depth = 8
  } = data;
  if (channels !== 4 && channels !== 3 && channels !== 2 && channels !== 1) {
    throw new RangeError(`unsupported number of channels: ${channels}`);
  }
  const returnValue = {
    channels,
    depth,
    colorType: ColorType.UNKNOWN
  };
  switch (channels) {
    case 4:
      returnValue.colorType = ColorType.TRUECOLOUR_ALPHA;
      break;
    case 3:
      returnValue.colorType = ColorType.TRUECOLOUR;
      break;
    case 1:
      if (palette) {
        returnValue.colorType = ColorType.INDEXED_COLOUR;
      } else {
        returnValue.colorType = ColorType.GREYSCALE;
      }
      break;
    case 2:
      returnValue.colorType = ColorType.GREYSCALE_ALPHA;
      break;
    default:
      throw new Error('unsupported number of channels');
  }
  return returnValue;
}
function writeDataBytes(data, newData, slotsPerLine, offset) {
  for (let j = 0; j < slotsPerLine; j++) {
    newData.writeByte(data[offset++]);
  }
  return offset;
}
function writeDataInterlaced(imageData, data, newData, offset) {
  const passes = [{
    x: 0,
    y: 0,
    xStep: 8,
    yStep: 8
  }, {
    x: 4,
    y: 0,
    xStep: 8,
    yStep: 8
  }, {
    x: 0,
    y: 4,
    xStep: 4,
    yStep: 8
  }, {
    x: 2,
    y: 0,
    xStep: 4,
    yStep: 4
  }, {
    x: 0,
    y: 2,
    xStep: 2,
    yStep: 4
  }, {
    x: 1,
    y: 0,
    xStep: 2,
    yStep: 2
  }, {
    x: 0,
    y: 1,
    xStep: 1,
    yStep: 2
  }];
  const {
    width,
    height,
    channels,
    depth
  } = imageData;
  let pixelSize;
  if (depth === 16) {
    pixelSize = channels * depth / 8 / 2;
  } else {
    pixelSize = channels * depth / 8;
  }
  // Process each pass
  for (let passIndex = 0; passIndex < 7; passIndex++) {
    const pass = passes[passIndex];
    const passWidth = Math.floor((width - pass.x + pass.xStep - 1) / pass.xStep);
    const passHeight = Math.floor((height - pass.y + pass.yStep - 1) / pass.yStep);
    if (passWidth <= 0 || passHeight <= 0) continue;
    const passLineBytes = passWidth * pixelSize;
    // For each scanline in this pass
    for (let y = 0; y < passHeight; y++) {
      const imageY = pass.y + y * pass.yStep;
      // Extract raw scanline data
      const rawScanline = depth <= 8 ? new Uint8Array(passLineBytes) : new Uint16Array(passLineBytes);
      let rawOffset = 0;
      for (let x = 0; x < passWidth; x++) {
        const imageX = pass.x + x * pass.xStep;
        if (imageX < width && imageY < height) {
          const srcPos = (imageY * width + imageX) * pixelSize;
          for (let i = 0; i < pixelSize; i++) {
            rawScanline[rawOffset++] = data[srcPos + i];
          }
        }
      }
      newData.writeByte(0); // no filter
      if (depth === 8) {
        newData.writeBytes(rawScanline);
      } else if (depth === 16) {
        for (const value of rawScanline) {
          newData.writeByte(value >> 8 & 0xff); // High byte
          newData.writeByte(value & 0xff);
        }
      }
    }
  }
  return offset;
}
function writeDataUint16(data, newData, slotsPerLine, offset) {
  for (let j = 0; j < slotsPerLine; j++) {
    newData.writeUint16(data[offset++]);
  }
  return offset;
}

function decodePng$1(data, options) {
  const decoder = new PngDecoder(data, options);
  return decoder.decode();
}
function encodePng$1(png, options) {
  const encoder = new PngEncoder(png, options);
  return encoder.encode();
}
function decodeApng(data, options) {
  const decoder = new PngDecoder(data, options);
  return decoder.decodeApng();
}

/**
 * Creates a PNG buffer from an image.
 * @param image - The image instance.
 * @param options - PNG encoding options.
 * @returns The buffer.
 */
function encodePng(image, options) {
  if (image.colorModel !== 'RGB' && image.colorModel !== 'RGBA' && image.colorModel !== 'GREY' && image.colorModel !== 'GREYA' || image instanceof Mask) {
    image = image.convertColor('GREY');
  }
  const {
    bitDepth: depth,
    ...other
  } = image.getRawImage();
  return encodePng$1({
    depth,
    ...other
  }, options);
}

const ImageFormat = {
  PNG: 'png',
  JPG: 'jpg',
  JPEG: 'jpeg',
  BMP: 'bmp'
};
const defaultPng = {
  format: 'png'
};
/**
 * Encodes the image to the specified format
 * @param image - Image to encode.
 * @param options - Format and options passed to the encoder.
 * @returns The encoded image.
 */
function encode(image, options = defaultPng) {
  return M$2(options).with({
    format: 'png'
  }, options => encodePng(image, options.encoderOptions)).with({
    format: z.union('jpg', 'jpeg')
  }, options => encodeJpeg(image, options.encoderOptions)).with({
    format: 'bmp'
  }, () => encodeBmp(image)).exhaustive();
}

/**
 * Returns builtin Node.js modules or throws an error saying that the method is only implemented in Node.js.
 * @param methodName - Name of the method that calls this function
 * @returns - The `fs`, `path` and `url` Node.js modules.
 */
function getNodeApiOrThrow(methodName) {
  if (!isNode()) {
    throw new Error(`${methodName} is only implemented for Node.js`);
  }
  return {
    fs: process.getBuiltinModule('node:fs'),
    path: process.getBuiltinModule('node:path'),
    url: process.getBuiltinModule('node:url')
  };
}
let CanvasCtorBrowser;
let CanvasCtorNode;
/**
 * Returns a 2D canvas context for rendering on the browser or Node.js.
 * On Node.js this requires the optional `skia-canvas` package to be installed.
 * @param width - Width of the canvas.
 * @param height - Height of the canvas.
 * @returns The initialised canvas context.
 */
function getCanvasContext(width, height) {
  if (isNode()) {
    if (!CanvasCtorNode) {
      try {
        CanvasCtorNode = getRequireFn()('skia-canvas').Canvas;
      } catch (error) {
        throw new Error('drawText on Node.js requires the optional "skia-canvas" package. Install it with: npm install skia-canvas', {
          cause: error
        });
      }
    }
    return new CanvasCtorNode(width, height).getContext('2d');
  } else {
    CanvasCtorBrowser ??= globalThis.OffscreenCanvas;
    const context = new CanvasCtorBrowser(width, height).getContext('2d');
    if (!context) {
      throw new Error('Failed to create canvas context');
    }
    return context;
  }
}
function isNode() {
  return typeof process !== 'undefined' && typeof process.getBuiltinModule === 'function';
}
let requireFn;
function getRequireFn() {
  requireFn ??= process.getBuiltinModule('node:module').createRequire(import.meta.url);
  return requireFn;
}

/**
 * Asynchronously write an image to the disk.
 * This method is only implemented for Node.js.
 * @param path - Path where the image should be written.
 * @param image - Image to save.
 * @param options - Encode options.
 */
async function write(path, image, options) {
  const nodeApi = getNodeApiOrThrow('write');
  if (typeof path !== 'string') {
    path = nodeApi.url.fileURLToPath(path);
  }
  if (image instanceof Mask) {
    image = image.convertColor('GREY');
  }
  const toWrite = getDataToWrite(path, image, options, nodeApi);
  if (options?.recursive) {
    const dir = nodeApi.path.dirname(path);
    await nodeApi.fs.promises.mkdir(dir, {
      recursive: true
    });
  }
  await nodeApi.fs.promises.writeFile(path, toWrite);
}
/**
 * Synchronous version of {@link write}.
 * This method is only implemented for Node.js.
 * @param path - Path where the image should be written.
 * @param image - Image to save.
 * @param options - Encode options.
 */
function writeSync(path, image, options) {
  const nodeApi = getNodeApiOrThrow('writeSync');
  if (typeof path !== 'string') {
    path = nodeApi.url.fileURLToPath(path);
  }
  const toWrite = getDataToWrite(path, image, options, nodeApi);
  if (options?.recursive) {
    const dir = nodeApi.path.dirname(path);
    nodeApi.fs.mkdirSync(dir, {
      recursive: true
    });
  }
  nodeApi.fs.writeFileSync(path, toWrite);
}
/**
 * Encode the image to the format specified by the file's extension.
 * @param destinationPath - Image destination.
 * @param image - Image to save.
 * @param options - Encode options.
 * @param nodeApi - Object with Node.js APIs.
 * @returns Buffer containing the encoded image.
 */
function getDataToWrite(destinationPath, image, options, nodeApi) {
  if (!options || !('format' in options)) {
    const extension = nodeApi.path.extname(destinationPath).slice(1).toLowerCase();
    if (extension === 'png' || extension === 'jpg' || extension === 'jpeg' || extension === 'bmp') {
      return encode(image, {
        ...options,
        format: extension
      });
    } else {
      throw new RangeError('image format could not be determined from file extension. Use a supported extension or specify the format option');
    }
  } else {
    return encode(image, options);
  }
}

// TODO: Create nodejs version that throws an error
/**
 * Draw the image in an HTML canvas.
 * @param image - The image to draw.
 * @param canvas - The HTML canvas.
 * @param options - Write canvas options.
 */
function writeCanvas(image, canvas, options = {}) {
  if (image.colorModel !== 'RGBA') {
    image = image.convertColor('RGBA');
  }
  if (image.bitDepth !== 8 && image instanceof Image) {
    image = image.convertBitDepth(8);
  }
  const {
    resizeCanvas = true,
    dx = 0,
    dy = 0,
    dirtyX = 0,
    dirtyY = 0,
    dirtyWidth = image.width,
    dirtyHeight = image.height
  } = options;
  if (resizeCanvas) {
    canvas.width = image.width;
    canvas.height = image.height;
  }
  const ctx = canvas.getContext('2d');
  assert(ctx);
  const data = image.getRawImage().data;
  ctx.putImageData(new ImageData(
  // @ts-expect-error ImageData types don't support SharedArrayBuffer.
  new Uint8ClampedArray(data.buffer, data.byteOffset, data.byteLength), image.width, image.height), dx, dy, dirtyX, dirtyY, dirtyWidth, dirtyHeight);
}

Uint8Array.from([255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 62, 255, 255, 255, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 255, 255, 255, 0, 255, 255, 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 255, 255, 255, 255, 255, 255, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51]);

const base64codes = Uint8Array.from([65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 43, 47]);

/*
3 bytes are encoded in 4 bytes of base64
11111122 22223333 33444444
We want to be the fastest possible, so we will use a lookup table to convert 12 bits to 2 bytes of base64
But in order still to avoid one operation we will create 2 of those lookup tables.
- One for 2222 11111122
- One for 3333 33444444
*/
// 2222 11111122
const base64codes1 = new Uint32Array(64 * 64);
for (let i = 0; i < 64; i++) {
  for (let j = 0; j < 64; j++) {
    const index = i << 2 | (j & 0x30) >> 4 | (j & 0x0f) << 8;
    base64codes1[index] = base64codes[i] | base64codes[j] << 8;
  }
}
// 3333 33444444 that we store on the bits 16->31 just to allow to make directly the OR with the previous value
const base64codes2 = new Uint32Array(64 * 64);
for (let i = 0; i < 64; i++) {
  for (let j = 0; j < 64; j++) {
    const index = i << 6 | j;
    base64codes2[index] = base64codes[i] << 16 | base64codes[j] << 24;
  }
}
/**
 * Convert a Uint8Array containing bytes to a Uint8Array containing the base64 encoded values
 * @param input
 * @returns a Uint8Array containing the encoded bytes
 */
function encodeFast(input) {
  const output32 = new Uint32Array(Math.ceil(input.length / 3));
  let i, j;
  for (i = 2, j = 0; i < input.length; i += 3, j++) {
    output32[j] = base64codes1[input[i - 2] | (input[i - 1] & 0xf0) << 4] | base64codes2[input[i] | (input[i - 1] & 0x0f) << 8];
  }
  if (i === input.length + 1) {
    // 1 octet yet to write
    output32[j] = base64codes[input[i - 2] >> 2] | base64codes[(input[i - 2] & 0x03) << 4] << 8 | 15677 << 16;
  }
  if (i === input.length) {
    // 2 octets yet to write
    output32[j] = base64codes[input[i - 2] >> 2] | base64codes[(input[i - 2] & 0x03) << 4 | input[i - 1] >> 4] << 8 | base64codes[(input[i - 1] & 0x0f) << 2] << 16 | 61 << 24;
  }
  const output8 = new Uint8Array(output32.buffer);
  return output8;
}

/**
 * Converts image into Data URL string.
 * @param image - Image to get base64 encoding from.
 * @param options - Encoding options.
 * @returns base64 string.
 */
function encodeDataURL(image, options = defaultPng) {
  const buffer = encode(image, options);
  const base64 = encodeFast(buffer);
  const base64Data = new TextDecoder().decode(base64);
  return `data:image/${options.format};base64,${base64Data}`;
}

/**
 * Convert row/column points to a matrix.
 * Last row is padded with **ones** (ignore third dimension).
 * @param points - Points to process.
 * @returns The matrix.
 */
function getMatrixFromPoints(points) {
  const matrix = new Matrix$1(3, points.length);
  for (let i = 0; i < points.length; i++) {
    matrix.set(0, i, points[i].column);
    matrix.set(1, i, points[i].row);
    matrix.set(2, i, 1);
  }
  return matrix;
}

/**
 * The fit function for an affine transformation.
 * Get the best transformation parameters for the given source and destination.
 * @param source - Source points.
 * @param destination - Destination points.
 * @returns The model parameters in the format [angle, xTranslation, yTranslation]
 */
function affineFitFunction(source, destination) {
  const sourceMatrix = getMatrixFromPoints(source);
  const destinationMatrix = getMatrixFromPoints(destination);
  const result = getAffineTransform$1(sourceMatrix, destinationMatrix);
  return [result.rotation, result.translation.x, result.translation.y, result.scale];
}

/**
 * Generate a function that applies the given transformation parameters to a point.
 * The transform is an array of number in the format: [angle, x, y, scale].
 * @param transform - Transformation to apply.
 * @returns Function to transform a point.
 */
function createAffineTransformModel(transform) {
  if (transform.length !== 4) {
    throw new Error('Transform had wrong number of parameters');
  }
  return point => {
    const angle = transform[0] * Math.PI / 180;
    const xTranslation = transform[1];
    const yTranslation = transform[2];
    const scale = transform[3];
    const column = scale * (Math.cos(angle) * point.column - Math.sin(angle) * point.row) + xTranslation;
    const row = scale * (Math.sin(angle) * point.column + Math.cos(angle) * point.row) + yTranslation;
    return {
      column,
      row
    };
  };
}

/**
 * Compute the distance between point 1 and point 2.
 * @param point1 - First point.
 * @param point2 - Second  point.
 * @returns Euclidean distance.
 */
function getEuclideanDistance(point1, point2) {
  return Math.hypot(point1.row - point2.row, point1.column - point2.column);
}

/**
 * Crop source image for contrast enhancement.
 * @param source - Source image enlarged compared to the destination image.
 * @param destination - Destination image.
 * @param destinationOrigin - Estimated origin of the destination image in the source image (relative to top-left corner).
 * @returns The source image without margins.
 */
function getSourceWithoutMargins(source, destination, destinationOrigin) {
  const width = Math.min(destination.width, source.width - destinationOrigin.column);
  const height = Math.min(destination.height, source.height - destinationOrigin.row);
  return source.crop({
    origin: {
      row: destinationOrigin.row,
      column: destinationOrigin.column
    },
    width,
    height
  });
}

/**
 * Get the affine transformation from the source to the destination image.
 * @param source - Source image. Should be the image to align on the reference image.
 * It can have an additional margin, specified in the options.
 * @param destination - Destination image. Should be the reference image.
 * @param options - Get destination translation options.
 * @returns The affine transformation from source to destination image.
 */
function getAffineTransform(source, destination, options = {}) {
  const {
    centroidPatchDiameter = 31,
    bestKeypointRadius = 5,
    enhanceContrast = true,
    crosscheck = true,
    destinationOrigin = {
      column: 0,
      row: 0
    },
    maxRansacNbIterations,
    debug = false,
    debugImagePath = `${import.meta.dirname}/montage.png`
  } = options;
  if (source.colorModel !== ImageColorModel.GREY) {
    source = source.grey();
  }
  if (destination.colorModel !== ImageColorModel.GREY) {
    destination = destination.grey();
  }
  // enhance images contrast
  if (enhanceContrast) {
    const sourceWithoutMargin = getSourceWithoutMargins(source, destination, destinationOrigin);
    const sourceExtremums = getMinMax(sourceWithoutMargin);
    source.level({
      inputMin: sourceExtremums.min[0],
      inputMax: sourceExtremums.max[0],
      out: source
    });
    const destinationExtremums = getMinMax(destination);
    destination.level({
      inputMin: destinationExtremums.min[0],
      inputMax: destinationExtremums.max[0],
      out: destination
    });
  }
  // compute briefs
  const sourceBrief = getBrief(source, {
    centroidPatchDiameter,
    bestKptRadius: bestKeypointRadius
  });
  const destinationBrief = getBrief(destination, {
    centroidPatchDiameter,
    bestKptRadius: bestKeypointRadius
  });
  const nbSourceKeypoints = sourceBrief.keypoints.length;
  const nbDestinationKeypoints = destinationBrief.keypoints.length;
  // match reference and destination keypoints
  let matches = [];
  if (crosscheck) {
    matches = getCrosscheckMatches(sourceBrief.descriptors, destinationBrief.descriptors);
  } else {
    matches = bruteForceOneMatch(sourceBrief.descriptors, destinationBrief.descriptors);
    matches = filterEuclideanDistance(matches, sourceBrief.keypoints, destinationBrief.keypoints, {
      origin: destinationOrigin
    });
  }
  if (matches.length < 2) {
    throw new Error('Insufficient number of matches found to compute affine transform (less than 2).');
  }
  // extract source and destination points
  let sourcePoints = [];
  let destinationPoints = [];
  for (const match of matches) {
    sourcePoints.push(sourceBrief.keypoints[match.sourceIndex].origin);
    destinationPoints.push(destinationBrief.keypoints[match.destinationIndex].origin);
  }
  // find inliers with ransac
  let nbInliers = sourcePoints.length;
  let nbRansacIterations = 0;
  let inliers = [0, 1];
  if (sourcePoints.length > 2) {
    const ransacResult = ransac(sourcePoints, destinationPoints, {
      distanceFunction: getEuclideanDistance,
      modelFunction: createAffineTransformModel,
      fitFunction: affineFitFunction,
      maxNbIterations: maxRansacNbIterations
    });
    nbRansacIterations = ransacResult.nbIterations;
    inliers = ransacResult.inliers;
    nbInliers = inliers.length;
    const newSrcPoints = [];
    const newDstPoints = [];
    for (const inlier of inliers) {
      newSrcPoints.push(sourcePoints[inlier]);
      newDstPoints.push(destinationPoints[inlier]);
    }
    sourcePoints = newSrcPoints;
    destinationPoints = newDstPoints;
  }
  // create debug image
  if (debug) {
    const montage = new Montage(source, destination, {
      disposition: MontageDisposition.VERTICAL
    });
    montage.drawMatches(matches, sourceBrief.keypoints, destinationBrief.keypoints, {
      showDistance: true
    });
    const inlierMatches = [];
    for (const inlier of inliers) {
      inlierMatches.push(matches[inlier]);
    }
    montage.drawMatches(inlierMatches, sourceBrief.keypoints, destinationBrief.keypoints, {
      strokeColor: [0, 0, 255]
    });
    const drawKeypointsBaseOptions = {
      fill: true,
      color: [0, 255, 0],
      showScore: true,
      markerSize: 3
    };
    montage.drawKeypoints(sourceBrief.keypoints, drawKeypointsBaseOptions);
    montage.drawKeypoints(destinationBrief.keypoints, {
      origin: montage.destinationOrigin,
      ...drawKeypointsBaseOptions
    });
    writeSync(debugImagePath, montage.image);
  }
  // compute affine transform from destination to reference
  const sourceMatrix = getMatrixFromPoints(sourcePoints);
  const destinationMatrix = getMatrixFromPoints(destinationPoints);
  const affineTransform = getAffineTransform$1(sourceMatrix, destinationMatrix);
  return {
    transform: {
      rotation: affineTransform.rotation,
      scale: affineTransform.scale,
      translation: {
        column: Math.round(affineTransform.translation.x),
        row: Math.round(affineTransform.translation.y)
      }
    },
    stats: {
      nbMatches: matches.length,
      nbInliers,
      nbRansacIterations,
      nbSourceKeypoints,
      nbDestinationKeypoints
    }
  };
}

/**
 * Aligns two images by finding the translation that minimizes the mean difference of all channels.
 * between them. The source image should fit entirely in the destination image.
 * @param source - Image to align.
 * @param destination - Image to align to.
 * @param options - Align images min difference options.
 * @returns Translation that minimizes the mean difference between the images.
 * Gives the origin of the source image relatively to the top-left corner of the destination image.
 */
function alignMinDifference(source, destination, options = {}) {
  checkProcessable$1(source, {
    bitDepth: [8, 16]
  });
  const xSpan = destination.width - source.width;
  const ySpan = destination.height - source.height;
  const {
    startStep = Math.max(Math.round(Math.min(source.width, source.height, Math.max(xSpan, ySpan)) / 4), 1),
    mask
  } = options;
  if (xSpan < 0 || ySpan < 0) {
    throw new Error('Source image must fit entirely in destination image');
  }
  let bestDifference = Number.POSITIVE_INFINITY;
  let bestShiftX = 0;
  let bestShiftY = 0;
  let step = startStep;
  let startX = 0;
  let startY = 0;
  let endX = xSpan;
  let endY = ySpan;
  if (mask && mask.size !== source.size) {
    throw new Error('Mask size must be equal to source size');
  }
  const nbPixelsToCheck = mask ? mask.getNbNonZeroPixels() : source.size;
  while (step >= 1) {
    step = Math.round(step);
    for (let shiftX = startX; shiftX <= endX; shiftX += step) {
      for (let shiftY = startY; shiftY <= endY; shiftY += step) {
        let currentDifference = 0;
        next: for (let column = 0; column < source.width; column++) {
          for (let row = 0; row < source.height; row++) {
            if (mask && !mask.getBit(column, row)) {
              continue;
            }
            for (let channel = 0; channel < source.channels; channel++) {
              const sourceValue = source.getValue(column, row, channel);
              const destinationValue = destination.getValue(column + shiftX, row + shiftY, channel);
              const difference = sourceValue - destinationValue;
              if (difference < 0) {
                // Math.abs is super slow, this simple trick is 5x faster
                currentDifference -= difference;
              } else {
                currentDifference += difference;
              }
              if (currentDifference > bestDifference) {
                break next;
              }
            }
          }
        }
        if (currentDifference < bestDifference) {
          bestDifference = currentDifference;
          bestShiftX = shiftX;
          bestShiftY = shiftY;
        }
      }
    }
    step /= 2;
    startX = Math.round(Math.max(0, bestShiftX - step));
    startY = Math.round(Math.max(0, bestShiftY - step));
    endX = Math.round(Math.min(xSpan, bestShiftX + step));
    endY = Math.round(Math.min(ySpan, bestShiftY + step));
  }
  return {
    row: bestShiftY,
    column: bestShiftX,
    similarity: 1 - bestDifference / (nbPixelsToCheck * source.maxValue)
  };
}

/**
 * Finds extreme values of an image which are not stacked together.
 * @param points - Array of points that should be combined to improve.
 * @param image - Image which extrema are calculated from.
 * @param options - FilterPointsOptions
 * @returns Array of Points.
 */
function removeClosePoints(points, image, options) {
  const distance = options?.distance || 0;
  const kind = options?.kind || 'maximum';
  if (options?.channel === undefined && image.channels > 1) {
    throw new Error('image channel must be specified or image must have only one channel');
  }
  const channel = options?.channel || 0;
  const isMax = kind === 'maximum';
  const sortedPoints = points.slice();
  sortedPoints.sort(getSort(image, channel, isMax));
  if (distance > 0) {
    for (let i = 0; i < sortedPoints.length; i++) {
      for (let j = i + 1; j < sortedPoints.length; j++) {
        if (Math.hypot(sortedPoints[i].column - sortedPoints[j].column, sortedPoints[i].row - sortedPoints[j].row) < distance) {
          sortedPoints.splice(j, 1);
          j--;
        }
      }
    }
  }
  return sortedPoints;
}
function getSort(image, channel, isDescending) {
  if (isDescending) {
    return function sortDescending(a, b) {
      return image.getValue(b.column, b.row, channel) - image.getValue(a.column, a.row, channel);
    };
  } else {
    return function sortAscending(a, b) {
      return image.getValue(a.column, a.row, channel) - image.getValue(b.column, b.row, channel);
    };
  }
}

var imageType$2 = {exports: {}};

var fileType$1 = {exports: {}};

(function (module) {

  const toBytes = s => [...s].map(c => c.charCodeAt(0));
  const xpiZipFilename = toBytes('META-INF/mozilla.rsa');
  const oxmlContentTypes = toBytes('[Content_Types].xml');
  const oxmlRels = toBytes('_rels/.rels');
  function readUInt64LE(buf, offset = 0) {
    let n = buf[offset];
    let mul = 1;
    let i = 0;
    while (++i < 8) {
      mul *= 0x100;
      n += buf[offset + i] * mul;
    }
    return n;
  }
  const fileType = input => {
    if (!(input instanceof Uint8Array || input instanceof ArrayBuffer || Buffer.isBuffer(input))) {
      throw new TypeError(`Expected the \`input\` argument to be of type \`Uint8Array\` or \`Buffer\` or \`ArrayBuffer\`, got \`${typeof input}\``);
    }
    const buf = input instanceof Uint8Array ? input : new Uint8Array(input);
    if (!(buf && buf.length > 1)) {
      return null;
    }
    const check = (header, options) => {
      options = Object.assign({
        offset: 0
      }, options);
      for (let i = 0; i < header.length; i++) {
        // If a bitmask is set
        if (options.mask) {
          // If header doesn't equal `buf` with bits masked off
          if (header[i] !== (options.mask[i] & buf[i + options.offset])) {
            return false;
          }
        } else if (header[i] !== buf[i + options.offset]) {
          return false;
        }
      }
      return true;
    };
    const checkString = (header, options) => check(toBytes(header), options);
    if (check([0xFF, 0xD8, 0xFF])) {
      return {
        ext: 'jpg',
        mime: 'image/jpeg'
      };
    }
    if (check([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A])) {
      return {
        ext: 'png',
        mime: 'image/png'
      };
    }
    if (check([0x47, 0x49, 0x46])) {
      return {
        ext: 'gif',
        mime: 'image/gif'
      };
    }
    if (check([0x57, 0x45, 0x42, 0x50], {
      offset: 8
    })) {
      return {
        ext: 'webp',
        mime: 'image/webp'
      };
    }
    if (check([0x46, 0x4C, 0x49, 0x46])) {
      return {
        ext: 'flif',
        mime: 'image/flif'
      };
    }

    // Needs to be before `tif` check
    if ((check([0x49, 0x49, 0x2A, 0x0]) || check([0x4D, 0x4D, 0x0, 0x2A])) && check([0x43, 0x52], {
      offset: 8
    })) {
      return {
        ext: 'cr2',
        mime: 'image/x-canon-cr2'
      };
    }
    if (check([0x49, 0x49, 0x2A, 0x0]) || check([0x4D, 0x4D, 0x0, 0x2A])) {
      return {
        ext: 'tif',
        mime: 'image/tiff'
      };
    }
    if (check([0x42, 0x4D])) {
      return {
        ext: 'bmp',
        mime: 'image/bmp'
      };
    }
    if (check([0x49, 0x49, 0xBC])) {
      return {
        ext: 'jxr',
        mime: 'image/vnd.ms-photo'
      };
    }
    if (check([0x38, 0x42, 0x50, 0x53])) {
      return {
        ext: 'psd',
        mime: 'image/vnd.adobe.photoshop'
      };
    }

    // Zip-based file formats
    // Need to be before the `zip` check
    if (check([0x50, 0x4B, 0x3, 0x4])) {
      if (check([0x6D, 0x69, 0x6D, 0x65, 0x74, 0x79, 0x70, 0x65, 0x61, 0x70, 0x70, 0x6C, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6F, 0x6E, 0x2F, 0x65, 0x70, 0x75, 0x62, 0x2B, 0x7A, 0x69, 0x70], {
        offset: 30
      })) {
        return {
          ext: 'epub',
          mime: 'application/epub+zip'
        };
      }

      // Assumes signed `.xpi` from addons.mozilla.org
      if (check(xpiZipFilename, {
        offset: 30
      })) {
        return {
          ext: 'xpi',
          mime: 'application/x-xpinstall'
        };
      }
      if (checkString('mimetypeapplication/vnd.oasis.opendocument.text', {
        offset: 30
      })) {
        return {
          ext: 'odt',
          mime: 'application/vnd.oasis.opendocument.text'
        };
      }
      if (checkString('mimetypeapplication/vnd.oasis.opendocument.spreadsheet', {
        offset: 30
      })) {
        return {
          ext: 'ods',
          mime: 'application/vnd.oasis.opendocument.spreadsheet'
        };
      }
      if (checkString('mimetypeapplication/vnd.oasis.opendocument.presentation', {
        offset: 30
      })) {
        return {
          ext: 'odp',
          mime: 'application/vnd.oasis.opendocument.presentation'
        };
      }

      // The docx, xlsx and pptx file types extend the Office Open XML file format:
      // https://en.wikipedia.org/wiki/Office_Open_XML_file_formats
      // We look for:
      // - one entry named '[Content_Types].xml' or '_rels/.rels',
      // - one entry indicating specific type of file.
      // MS Office, OpenOffice and LibreOffice may put the parts in different order, so the check should not rely on it.
      const findNextZipHeaderIndex = (arr, startAt = 0) => arr.findIndex((el, i, arr) => i >= startAt && arr[i] === 0x50 && arr[i + 1] === 0x4B && arr[i + 2] === 0x3 && arr[i + 3] === 0x4);
      let zipHeaderIndex = 0; // The first zip header was already found at index 0
      let oxmlFound = false;
      let type = null;
      do {
        const offset = zipHeaderIndex + 30;
        if (!oxmlFound) {
          oxmlFound = check(oxmlContentTypes, {
            offset
          }) || check(oxmlRels, {
            offset
          });
        }
        if (!type) {
          if (checkString('word/', {
            offset
          })) {
            type = {
              ext: 'docx',
              mime: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
            };
          } else if (checkString('ppt/', {
            offset
          })) {
            type = {
              ext: 'pptx',
              mime: 'application/vnd.openxmlformats-officedocument.presentationml.presentation'
            };
          } else if (checkString('xl/', {
            offset
          })) {
            type = {
              ext: 'xlsx',
              mime: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            };
          }
        }
        if (oxmlFound && type) {
          return type;
        }
        zipHeaderIndex = findNextZipHeaderIndex(buf, offset);
      } while (zipHeaderIndex >= 0);

      // No more zip parts available in the buffer, but maybe we are almost certain about the type?
      if (type) {
        return type;
      }
    }
    if (check([0x50, 0x4B]) && (buf[2] === 0x3 || buf[2] === 0x5 || buf[2] === 0x7) && (buf[3] === 0x4 || buf[3] === 0x6 || buf[3] === 0x8)) {
      return {
        ext: 'zip',
        mime: 'application/zip'
      };
    }
    if (check([0x75, 0x73, 0x74, 0x61, 0x72], {
      offset: 257
    })) {
      return {
        ext: 'tar',
        mime: 'application/x-tar'
      };
    }
    if (check([0x52, 0x61, 0x72, 0x21, 0x1A, 0x7]) && (buf[6] === 0x0 || buf[6] === 0x1)) {
      return {
        ext: 'rar',
        mime: 'application/x-rar-compressed'
      };
    }
    if (check([0x1F, 0x8B, 0x8])) {
      return {
        ext: 'gz',
        mime: 'application/gzip'
      };
    }
    if (check([0x42, 0x5A, 0x68])) {
      return {
        ext: 'bz2',
        mime: 'application/x-bzip2'
      };
    }
    if (check([0x37, 0x7A, 0xBC, 0xAF, 0x27, 0x1C])) {
      return {
        ext: '7z',
        mime: 'application/x-7z-compressed'
      };
    }
    if (check([0x78, 0x01])) {
      return {
        ext: 'dmg',
        mime: 'application/x-apple-diskimage'
      };
    }
    if (check([0x33, 0x67, 0x70, 0x35]) ||
    // 3gp5

    check([0x0, 0x0, 0x0]) && check([0x66, 0x74, 0x79, 0x70], {
      offset: 4
    }) && (check([0x6D, 0x70, 0x34, 0x31], {
      offset: 8
    }) ||
    // MP41
    check([0x6D, 0x70, 0x34, 0x32], {
      offset: 8
    }) ||
    // MP42
    check([0x69, 0x73, 0x6F, 0x6D], {
      offset: 8
    }) ||
    // ISOM
    check([0x69, 0x73, 0x6F, 0x32], {
      offset: 8
    }) ||
    // ISO2
    check([0x6D, 0x6D, 0x70, 0x34], {
      offset: 8
    }) ||
    // MMP4
    check([0x4D, 0x34, 0x56], {
      offset: 8
    }) ||
    // M4V
    check([0x64, 0x61, 0x73, 0x68], {
      offset: 8
    }) // DASH
    )) {
      return {
        ext: 'mp4',
        mime: 'video/mp4'
      };
    }
    if (check([0x4D, 0x54, 0x68, 0x64])) {
      return {
        ext: 'mid',
        mime: 'audio/midi'
      };
    }

    // https://github.com/threatstack/libmagic/blob/master/magic/Magdir/matroska
    if (check([0x1A, 0x45, 0xDF, 0xA3])) {
      const sliced = buf.subarray(4, 4 + 4096);
      const idPos = sliced.findIndex((el, i, arr) => arr[i] === 0x42 && arr[i + 1] === 0x82);
      if (idPos !== -1) {
        const docTypePos = idPos + 3;
        const findDocType = type => [...type].every((c, i) => sliced[docTypePos + i] === c.charCodeAt(0));
        if (findDocType('matroska')) {
          return {
            ext: 'mkv',
            mime: 'video/x-matroska'
          };
        }
        if (findDocType('webm')) {
          return {
            ext: 'webm',
            mime: 'video/webm'
          };
        }
      }
    }
    if (check([0x0, 0x0, 0x0, 0x14, 0x66, 0x74, 0x79, 0x70, 0x71, 0x74, 0x20, 0x20]) || check([0x66, 0x72, 0x65, 0x65], {
      offset: 4
    }) ||
    // Type: `free`
    check([0x66, 0x74, 0x79, 0x70, 0x71, 0x74, 0x20, 0x20], {
      offset: 4
    }) || check([0x6D, 0x64, 0x61, 0x74], {
      offset: 4
    }) ||
    // MJPEG
    check([0x6D, 0x6F, 0x6F, 0x76], {
      offset: 4
    }) ||
    // Type: `moov`
    check([0x77, 0x69, 0x64, 0x65], {
      offset: 4
    })) {
      return {
        ext: 'mov',
        mime: 'video/quicktime'
      };
    }

    // RIFF file format which might be AVI, WAV, QCP, etc
    if (check([0x52, 0x49, 0x46, 0x46])) {
      if (check([0x41, 0x56, 0x49], {
        offset: 8
      })) {
        return {
          ext: 'avi',
          mime: 'video/vnd.avi'
        };
      }
      if (check([0x57, 0x41, 0x56, 0x45], {
        offset: 8
      })) {
        return {
          ext: 'wav',
          mime: 'audio/vnd.wave'
        };
      }

      // QLCM, QCP file
      if (check([0x51, 0x4C, 0x43, 0x4D], {
        offset: 8
      })) {
        return {
          ext: 'qcp',
          mime: 'audio/qcelp'
        };
      }
    }

    // ASF_Header_Object first 80 bytes
    if (check([0x30, 0x26, 0xB2, 0x75, 0x8E, 0x66, 0xCF, 0x11, 0xA6, 0xD9])) {
      // Search for header should be in first 1KB of file.

      let offset = 30;
      do {
        const objectSize = readUInt64LE(buf, offset + 16);
        if (check([0x91, 0x07, 0xDC, 0xB7, 0xB7, 0xA9, 0xCF, 0x11, 0x8E, 0xE6, 0x00, 0xC0, 0x0C, 0x20, 0x53, 0x65], {
          offset
        })) {
          // Sync on Stream-Properties-Object (B7DC0791-A9B7-11CF-8EE6-00C00C205365)
          if (check([0x40, 0x9E, 0x69, 0xF8, 0x4D, 0x5B, 0xCF, 0x11, 0xA8, 0xFD, 0x00, 0x80, 0x5F, 0x5C, 0x44, 0x2B], {
            offset: offset + 24
          })) {
            // Found audio:
            return {
              ext: 'wma',
              mime: 'audio/x-ms-wma'
            };
          }
          if (check([0xC0, 0xEF, 0x19, 0xBC, 0x4D, 0x5B, 0xCF, 0x11, 0xA8, 0xFD, 0x00, 0x80, 0x5F, 0x5C, 0x44, 0x2B], {
            offset: offset + 24
          })) {
            // Found video:
            return {
              ext: 'wmv',
              mime: 'video/x-ms-asf'
            };
          }
          break;
        }
        offset += objectSize;
      } while (offset + 24 <= buf.length);

      // Default to ASF generic extension
      return {
        ext: 'asf',
        mime: 'application/vnd.ms-asf'
      };
    }
    if (check([0x0, 0x0, 0x1, 0xBA]) || check([0x0, 0x0, 0x1, 0xB3])) {
      return {
        ext: 'mpg',
        mime: 'video/mpeg'
      };
    }
    if (check([0x66, 0x74, 0x79, 0x70, 0x33, 0x67], {
      offset: 4
    })) {
      return {
        ext: '3gp',
        mime: 'video/3gpp'
      };
    }

    // Check for MPEG header at different starting offsets
    for (let start = 0; start < 2 && start < buf.length - 16; start++) {
      if (check([0x49, 0x44, 0x33], {
        offset: start
      }) ||
      // ID3 header
      check([0xFF, 0xE2], {
        offset: start,
        mask: [0xFF, 0xE2]
      }) // MPEG 1 or 2 Layer 3 header
      ) {
        return {
          ext: 'mp3',
          mime: 'audio/mpeg'
        };
      }
      if (check([0xFF, 0xE4], {
        offset: start,
        mask: [0xFF, 0xE4]
      }) // MPEG 1 or 2 Layer 2 header
      ) {
        return {
          ext: 'mp2',
          mime: 'audio/mpeg'
        };
      }
      if (check([0xFF, 0xF8], {
        offset: start,
        mask: [0xFF, 0xFC]
      }) // MPEG 2 layer 0 using ADTS
      ) {
        return {
          ext: 'mp2',
          mime: 'audio/mpeg'
        };
      }
      if (check([0xFF, 0xF0], {
        offset: start,
        mask: [0xFF, 0xFC]
      }) // MPEG 4 layer 0 using ADTS
      ) {
        return {
          ext: 'mp4',
          mime: 'audio/mpeg'
        };
      }
    }
    if (check([0x66, 0x74, 0x79, 0x70, 0x4D, 0x34, 0x41], {
      offset: 4
    })) {
      return {
        // MPEG-4 layer 3 (audio)
        ext: 'm4a',
        mime: 'audio/mp4' // RFC 4337
      };
    }

    // Needs to be before `ogg` check
    if (check([0x4F, 0x70, 0x75, 0x73, 0x48, 0x65, 0x61, 0x64], {
      offset: 28
    })) {
      return {
        ext: 'opus',
        mime: 'audio/opus'
      };
    }

    // If 'OggS' in first  bytes, then OGG container
    if (check([0x4F, 0x67, 0x67, 0x53])) {
      // This is a OGG container

      // If ' theora' in header.
      if (check([0x80, 0x74, 0x68, 0x65, 0x6F, 0x72, 0x61], {
        offset: 28
      })) {
        return {
          ext: 'ogv',
          mime: 'video/ogg'
        };
      }

      // If '\x01video' in header.
      if (check([0x01, 0x76, 0x69, 0x64, 0x65, 0x6F, 0x00], {
        offset: 28
      })) {
        return {
          ext: 'ogm',
          mime: 'video/ogg'
        };
      }

      // If ' FLAC' in header  https://xiph.org/flac/faq.html
      if (check([0x7F, 0x46, 0x4C, 0x41, 0x43], {
        offset: 28
      })) {
        return {
          ext: 'oga',
          mime: 'audio/ogg'
        };
      }

      // 'Speex  ' in header https://en.wikipedia.org/wiki/Speex
      if (check([0x53, 0x70, 0x65, 0x65, 0x78, 0x20, 0x20], {
        offset: 28
      })) {
        return {
          ext: 'spx',
          mime: 'audio/ogg'
        };
      }

      // If '\x01vorbis' in header
      if (check([0x01, 0x76, 0x6F, 0x72, 0x62, 0x69, 0x73], {
        offset: 28
      })) {
        return {
          ext: 'ogg',
          mime: 'audio/ogg'
        };
      }

      // Default OGG container https://www.iana.org/assignments/media-types/application/ogg
      return {
        ext: 'ogx',
        mime: 'application/ogg'
      };
    }
    if (check([0x66, 0x4C, 0x61, 0x43])) {
      return {
        ext: 'flac',
        mime: 'audio/x-flac'
      };
    }
    if (check([0x4D, 0x41, 0x43, 0x20])) {
      // 'MAC '
      return {
        ext: 'ape',
        mime: 'audio/ape'
      };
    }
    if (check([0x77, 0x76, 0x70, 0x6B])) {
      // 'wvpk'
      return {
        ext: 'wv',
        mime: 'audio/wavpack'
      };
    }
    if (check([0x23, 0x21, 0x41, 0x4D, 0x52, 0x0A])) {
      return {
        ext: 'amr',
        mime: 'audio/amr'
      };
    }
    if (check([0x25, 0x50, 0x44, 0x46])) {
      return {
        ext: 'pdf',
        mime: 'application/pdf'
      };
    }
    if (check([0x4D, 0x5A])) {
      return {
        ext: 'exe',
        mime: 'application/x-msdownload'
      };
    }
    if ((buf[0] === 0x43 || buf[0] === 0x46) && check([0x57, 0x53], {
      offset: 1
    })) {
      return {
        ext: 'swf',
        mime: 'application/x-shockwave-flash'
      };
    }
    if (check([0x7B, 0x5C, 0x72, 0x74, 0x66])) {
      return {
        ext: 'rtf',
        mime: 'application/rtf'
      };
    }
    if (check([0x00, 0x61, 0x73, 0x6D])) {
      return {
        ext: 'wasm',
        mime: 'application/wasm'
      };
    }
    if (check([0x77, 0x4F, 0x46, 0x46]) && (check([0x00, 0x01, 0x00, 0x00], {
      offset: 4
    }) || check([0x4F, 0x54, 0x54, 0x4F], {
      offset: 4
    }))) {
      return {
        ext: 'woff',
        mime: 'font/woff'
      };
    }
    if (check([0x77, 0x4F, 0x46, 0x32]) && (check([0x00, 0x01, 0x00, 0x00], {
      offset: 4
    }) || check([0x4F, 0x54, 0x54, 0x4F], {
      offset: 4
    }))) {
      return {
        ext: 'woff2',
        mime: 'font/woff2'
      };
    }
    if (check([0x4C, 0x50], {
      offset: 34
    }) && (check([0x00, 0x00, 0x01], {
      offset: 8
    }) || check([0x01, 0x00, 0x02], {
      offset: 8
    }) || check([0x02, 0x00, 0x02], {
      offset: 8
    }))) {
      return {
        ext: 'eot',
        mime: 'application/vnd.ms-fontobject'
      };
    }
    if (check([0x00, 0x01, 0x00, 0x00, 0x00])) {
      return {
        ext: 'ttf',
        mime: 'font/ttf'
      };
    }
    if (check([0x4F, 0x54, 0x54, 0x4F, 0x00])) {
      return {
        ext: 'otf',
        mime: 'font/otf'
      };
    }
    if (check([0x00, 0x00, 0x01, 0x00])) {
      return {
        ext: 'ico',
        mime: 'image/x-icon'
      };
    }
    if (check([0x00, 0x00, 0x02, 0x00])) {
      return {
        ext: 'cur',
        mime: 'image/x-icon'
      };
    }
    if (check([0x46, 0x4C, 0x56, 0x01])) {
      return {
        ext: 'flv',
        mime: 'video/x-flv'
      };
    }
    if (check([0x25, 0x21])) {
      return {
        ext: 'ps',
        mime: 'application/postscript'
      };
    }
    if (check([0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00])) {
      return {
        ext: 'xz',
        mime: 'application/x-xz'
      };
    }
    if (check([0x53, 0x51, 0x4C, 0x69])) {
      return {
        ext: 'sqlite',
        mime: 'application/x-sqlite3'
      };
    }
    if (check([0x4E, 0x45, 0x53, 0x1A])) {
      return {
        ext: 'nes',
        mime: 'application/x-nintendo-nes-rom'
      };
    }
    if (check([0x43, 0x72, 0x32, 0x34])) {
      return {
        ext: 'crx',
        mime: 'application/x-google-chrome-extension'
      };
    }
    if (check([0x4D, 0x53, 0x43, 0x46]) || check([0x49, 0x53, 0x63, 0x28])) {
      return {
        ext: 'cab',
        mime: 'application/vnd.ms-cab-compressed'
      };
    }

    // Needs to be before `ar` check
    if (check([0x21, 0x3C, 0x61, 0x72, 0x63, 0x68, 0x3E, 0x0A, 0x64, 0x65, 0x62, 0x69, 0x61, 0x6E, 0x2D, 0x62, 0x69, 0x6E, 0x61, 0x72, 0x79])) {
      return {
        ext: 'deb',
        mime: 'application/x-deb'
      };
    }
    if (check([0x21, 0x3C, 0x61, 0x72, 0x63, 0x68, 0x3E])) {
      return {
        ext: 'ar',
        mime: 'application/x-unix-archive'
      };
    }
    if (check([0xED, 0xAB, 0xEE, 0xDB])) {
      return {
        ext: 'rpm',
        mime: 'application/x-rpm'
      };
    }
    if (check([0x1F, 0xA0]) || check([0x1F, 0x9D])) {
      return {
        ext: 'Z',
        mime: 'application/x-compress'
      };
    }
    if (check([0x4C, 0x5A, 0x49, 0x50])) {
      return {
        ext: 'lz',
        mime: 'application/x-lzip'
      };
    }
    if (check([0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1])) {
      return {
        ext: 'msi',
        mime: 'application/x-msi'
      };
    }
    if (check([0x06, 0x0E, 0x2B, 0x34, 0x02, 0x05, 0x01, 0x01, 0x0D, 0x01, 0x02, 0x01, 0x01, 0x02])) {
      return {
        ext: 'mxf',
        mime: 'application/mxf'
      };
    }
    if (check([0x47], {
      offset: 4
    }) && (check([0x47], {
      offset: 192
    }) || check([0x47], {
      offset: 196
    }))) {
      return {
        ext: 'mts',
        mime: 'video/mp2t'
      };
    }
    if (check([0x42, 0x4C, 0x45, 0x4E, 0x44, 0x45, 0x52])) {
      return {
        ext: 'blend',
        mime: 'application/x-blender'
      };
    }
    if (check([0x42, 0x50, 0x47, 0xFB])) {
      return {
        ext: 'bpg',
        mime: 'image/bpg'
      };
    }
    if (check([0x00, 0x00, 0x00, 0x0C, 0x6A, 0x50, 0x20, 0x20, 0x0D, 0x0A, 0x87, 0x0A])) {
      // JPEG-2000 family

      if (check([0x6A, 0x70, 0x32, 0x20], {
        offset: 20
      })) {
        return {
          ext: 'jp2',
          mime: 'image/jp2'
        };
      }
      if (check([0x6A, 0x70, 0x78, 0x20], {
        offset: 20
      })) {
        return {
          ext: 'jpx',
          mime: 'image/jpx'
        };
      }
      if (check([0x6A, 0x70, 0x6D, 0x20], {
        offset: 20
      })) {
        return {
          ext: 'jpm',
          mime: 'image/jpm'
        };
      }
      if (check([0x6D, 0x6A, 0x70, 0x32], {
        offset: 20
      })) {
        return {
          ext: 'mj2',
          mime: 'image/mj2'
        };
      }
    }
    if (check([0x46, 0x4F, 0x52, 0x4D])) {
      return {
        ext: 'aif',
        mime: 'audio/aiff'
      };
    }
    if (checkString('<?xml ')) {
      return {
        ext: 'xml',
        mime: 'application/xml'
      };
    }
    if (check([0x42, 0x4F, 0x4F, 0x4B, 0x4D, 0x4F, 0x42, 0x49], {
      offset: 60
    })) {
      return {
        ext: 'mobi',
        mime: 'application/x-mobipocket-ebook'
      };
    }

    // File Type Box (https://en.wikipedia.org/wiki/ISO_base_media_file_format)
    if (check([0x66, 0x74, 0x79, 0x70], {
      offset: 4
    })) {
      if (check([0x6D, 0x69, 0x66, 0x31], {
        offset: 8
      })) {
        return {
          ext: 'heic',
          mime: 'image/heif'
        };
      }
      if (check([0x6D, 0x73, 0x66, 0x31], {
        offset: 8
      })) {
        return {
          ext: 'heic',
          mime: 'image/heif-sequence'
        };
      }
      if (check([0x68, 0x65, 0x69, 0x63], {
        offset: 8
      }) || check([0x68, 0x65, 0x69, 0x78], {
        offset: 8
      })) {
        return {
          ext: 'heic',
          mime: 'image/heic'
        };
      }
      if (check([0x68, 0x65, 0x76, 0x63], {
        offset: 8
      }) || check([0x68, 0x65, 0x76, 0x78], {
        offset: 8
      })) {
        return {
          ext: 'heic',
          mime: 'image/heic-sequence'
        };
      }
    }
    if (check([0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A])) {
      return {
        ext: 'ktx',
        mime: 'image/ktx'
      };
    }
    if (check([0x44, 0x49, 0x43, 0x4D], {
      offset: 128
    })) {
      return {
        ext: 'dcm',
        mime: 'application/dicom'
      };
    }

    // Musepack, SV7
    if (check([0x4D, 0x50, 0x2B])) {
      return {
        ext: 'mpc',
        mime: 'audio/x-musepack'
      };
    }

    // Musepack, SV8
    if (check([0x4D, 0x50, 0x43, 0x4B])) {
      return {
        ext: 'mpc',
        mime: 'audio/x-musepack'
      };
    }
    if (check([0x42, 0x45, 0x47, 0x49, 0x4E, 0x3A])) {
      return {
        ext: 'ics',
        mime: 'text/calendar'
      };
    }
    if (check([0x67, 0x6C, 0x54, 0x46, 0x02, 0x00, 0x00, 0x00])) {
      return {
        ext: 'glb',
        mime: 'model/gltf-binary'
      };
    }
    if (check([0xD4, 0xC3, 0xB2, 0xA1]) || check([0xA1, 0xB2, 0xC3, 0xD4])) {
      return {
        ext: 'pcap',
        mime: 'application/vnd.tcpdump.pcap'
      };
    }
    return null;
  };
  module.exports = fileType;
  // TODO: Remove this for the next major release
  module.exports.default = fileType;
  Object.defineProperty(fileType, 'minimumBytes', {
    value: 4100
  });
  module.exports.stream = readableStream => new Promise((resolve, reject) => {
    // Using `eval` to work around issues when bundling with Webpack
    const stream = eval('require')('stream'); // eslint-disable-line no-eval

    readableStream.once('readable', () => {
      const pass = new stream.PassThrough();
      const chunk = readableStream.read(module.exports.minimumBytes) || readableStream.read();
      try {
        pass.fileType = fileType(chunk);
      } catch (error) {
        reject(error);
      }
      readableStream.unshift(chunk);
      if (stream.pipeline) {
        resolve(stream.pipeline(readableStream, pass, () => {}));
      } else {
        resolve(readableStream.pipe(pass));
      }
    });
  });
})(fileType$1);
var fileTypeExports = fileType$1.exports;

const fileType = fileTypeExports;
const imageExts = new Set(['jpg', 'png', 'gif', 'webp', 'flif', 'cr2', 'tif', 'bmp', 'jxr', 'psd', 'ico', 'bpg', 'jp2', 'jpm', 'jpx', 'heic', 'cur', 'dcm']);
const imageType$1 = input => {
  const ret = fileType(input);
  return imageExts.has(ret && ret.ext) ? ret : null;
};
imageType$2.exports = imageType$1;
// TODO: Remove this for the next major release
imageType$2.exports.default = imageType$1;
Object.defineProperty(imageType$1, 'minimumBytes', {
  value: fileType.minimumBytes
});
var imageTypeExports = imageType$2.exports;
var imageType = /*@__PURE__*/getDefaultExportFromCjs(imageTypeExports);

/**
 * Decode a BMP. See the fast-bmp npm module.
 * @param data - The data to decode.
 * @returns The decoded image or mask.
 */
function decodeBmp(data) {
  const decodedData = decode$3(data);
  if (decodedData.bitsPerPixel === 1) {
    const mask = new Mask(decodedData.width, decodedData.height, {
      data: decodedData.data
    });
    return mask.convertColor('GREY');
  } else {
    let colorModel;
    switch (decodedData.channels) {
      case 1:
        colorModel = 'GREY';
        break;
      case 3:
        colorModel = 'RGB';
        break;
      default:
        colorModel = 'RGBA';
        break;
    }
    return new Image(decodedData.width, decodedData.height, {
      colorModel,
      data: decodedData.data
    });
  }
}

const tagsById$2 = {
  0x829a: 'ExposureTime',
  0x829d: 'FNumber',
  0x8822: 'ExposureProgram',
  0x8824: 'SpectralSensitivity',
  0x8827: 'ISOSpeedRatings',
  0x8828: 'OECF',
  0x8830: 'SensitivityType',
  0x8831: 'StandardOutputSensitivity',
  0x8832: 'RecommendedExposureIndex',
  0x8833: 'ISOSpeed',
  0x8834: 'ISOSpeedLatitudeyyy',
  0x8835: 'ISOSpeedLatitudezzz',
  0x9000: 'ExifVersion',
  0x9003: 'DateTimeOriginal',
  0x9004: 'DateTimeDigitized',
  0x9101: 'ComponentsConfiguration',
  0x9102: 'CompressedBitsPerPixel',
  0x9201: 'ShutterSpeedValue',
  0x9202: 'ApertureValue',
  0x9203: 'BrightnessValue',
  0x9204: 'ExposureBiasValue',
  0x9205: 'MaxApertureValue',
  0x9206: 'SubjectDistance',
  0x9207: 'MeteringMode',
  0x9208: 'LightSource',
  0x9209: 'Flash',
  0x920a: 'FocalLength',
  0x9214: 'SubjectArea',
  0x927c: 'MakerNote',
  0x9286: 'UserComment',
  0x9290: 'SubsecTime',
  0x9291: 'SubsecTimeOriginal',
  0x9292: 'SubsecTimeDigitized',
  0xa000: 'FlashpixVersion',
  0xa001: 'ColorSpace',
  0xa002: 'PixelXDimension',
  0xa003: 'PixelYDimension',
  0xa004: 'RelatedSoundFile',
  0xa20b: 'FlashEnergy',
  0xa20c: 'SpatialFrequencyResponse',
  0xa20e: 'FocalPlaneXResolution',
  0xa20f: 'FocalPlaneYResolution',
  0xa210: 'FocalPlaneResolutionUnit',
  0xa214: 'SubjectLocation',
  0xa215: 'ExposureIndex',
  0xa217: 'SensingMethod',
  0xa300: 'FileSource',
  0xa301: 'SceneType',
  0xa302: 'CFAPattern',
  0xa401: 'CustomRendered',
  0xa402: 'ExposureMode',
  0xa403: 'WhiteBalance',
  0xa404: 'DigitalZoomRatio',
  0xa405: 'FocalLengthIn35mmFilm',
  0xa406: 'SceneCaptureType',
  0xa407: 'GainControl',
  0xa408: 'Contrast',
  0xa409: 'Saturation',
  0xa40a: 'Sharpness',
  0xa40b: 'DeviceSettingDescription',
  0xa40c: 'SubjectDistanceRange',
  0xa420: 'ImageUniqueID',
  0xa430: 'CameraOwnerName',
  0xa431: 'BodySerialNumber',
  0xa432: 'LensSpecification',
  0xa433: 'LensMake',
  0xa434: 'LensModel',
  0xa435: 'LensSerialNumber',
  0xa500: 'Gamma'
};
const tagsByName$2 = {};
for (const i in tagsById$2) {
  tagsByName$2[tagsById$2[i]] = Number(i);
}

var exif = /*#__PURE__*/Object.freeze({
	__proto__: null,
	tagsById: tagsById$2,
	tagsByName: tagsByName$2
});

const tagsById$1 = {
  0x0000: 'GPSVersionID',
  0x0001: 'GPSLatitudeRef',
  0x0002: 'GPSLatitude',
  0x0003: 'GPSLongitudeRef',
  0x0004: 'GPSLongitude',
  0x0005: 'GPSAltitudeRef',
  0x0006: 'GPSAltitude',
  0x0007: 'GPSTimeStamp',
  0x0008: 'GPSSatellites',
  0x0009: 'GPSStatus',
  0x000a: 'GPSMeasureMode',
  0x000b: 'GPSDOP',
  0x000c: 'GPSSpeedRef',
  0x000d: 'GPSSpeed',
  0x000e: 'GPSTrackRef',
  0x000f: 'GPSTrack',
  0x0010: 'GPSImgDirectionRef',
  0x0011: 'GPSImgDirection',
  0x0012: 'GPSMapDatum',
  0x0013: 'GPSDestLatitudeRef',
  0x0014: 'GPSDestLatitude',
  0x0015: 'GPSDestLongitudeRef',
  0x0016: 'GPSDestLongitude',
  0x0017: 'GPSDestBearingRef',
  0x0018: 'GPSDestBearing',
  0x0019: 'GPSDestDistanceRef',
  0x001a: 'GPSDestDistance',
  0x001b: 'GPSProcessingMethod',
  0x001c: 'GPSAreaInformation',
  0x001d: 'GPSDateStamp',
  0x001e: 'GPSDifferential',
  0x001f: 'GPSHPositioningError'
};
const tagsByName$1 = {};
for (const i in tagsById$1) {
  tagsByName$1[tagsById$1[i]] = Number(i);
}

var gps = /*#__PURE__*/Object.freeze({
	__proto__: null,
	tagsById: tagsById$1,
	tagsByName: tagsByName$1
});

const tagsById = {
  // Baseline tags
  0x00fe: 'NewSubfileType',
  0x00ff: 'SubfileType',
  0x0100: 'ImageWidth',
  0x0101: 'ImageLength',
  0x0102: 'BitsPerSample',
  0x0103: 'Compression',
  0x0106: 'PhotometricInterpretation',
  0x0107: 'Threshholding',
  0x0108: 'CellWidth',
  0x0109: 'CellLength',
  0x010a: 'FillOrder',
  0x010e: 'ImageDescription',
  0x010f: 'Make',
  0x0110: 'Model',
  0x0111: 'StripOffsets',
  0x0112: 'Orientation',
  0x0115: 'SamplesPerPixel',
  0x0116: 'RowsPerStrip',
  0x0117: 'StripByteCounts',
  0x0118: 'MinSampleValue',
  0x0119: 'MaxSampleValue',
  0x011a: 'XResolution',
  0x011b: 'YResolution',
  0x011c: 'PlanarConfiguration',
  0x0120: 'FreeOffsets',
  0x0121: 'FreeByteCounts',
  0x0122: 'GrayResponseUnit',
  0x0123: 'GrayResponseCurve',
  0x0128: 'ResolutionUnit',
  0x0131: 'Software',
  0x0132: 'DateTime',
  0x013b: 'Artist',
  0x013c: 'HostComputer',
  0x0140: 'ColorMap',
  0x0152: 'ExtraSamples',
  0x8298: 'Copyright',
  // Extension tags
  0x010d: 'DocumentName',
  0x011d: 'PageName',
  0x011e: 'XPosition',
  0x011f: 'YPosition',
  0x0124: 'T4Options',
  0x0125: 'T6Options',
  0x0129: 'PageNumber',
  0x012d: 'TransferFunction',
  0x013d: 'Predictor',
  0x013e: 'WhitePoint',
  0x013f: 'PrimaryChromaticities',
  0x0141: 'HalftoneHints',
  0x0142: 'TileWidth',
  0x0143: 'TileLength',
  0x0144: 'TileOffsets',
  0x0145: 'TileByteCounts',
  0x0146: 'BadFaxLines',
  0x0147: 'CleanFaxData',
  0x0148: 'ConsecutiveBadFaxLines',
  0x014a: 'SubIFDs',
  0x014c: 'InkSet',
  0x014d: 'InkNames',
  0x014e: 'NumberOfInks',
  0x0150: 'DotRange',
  0x0151: 'TargetPrinter',
  0x0153: 'SampleFormat',
  0x0154: 'SMinSampleValue',
  0x0155: 'SMaxSampleValue',
  0x0156: 'TransferRange',
  0x0157: 'ClipPath',
  0x0158: 'XClipPathUnits',
  0x0159: 'YClipPathUnits',
  0x015a: 'Indexed',
  0x015b: 'JPEGTables',
  0x015f: 'OPIProxy',
  0x0190: 'GlobalParametersIFD',
  0x0191: 'ProfileType',
  0x0192: 'FaxProfile',
  0x0193: 'CodingMethods',
  0x0194: 'VersionYear',
  0x0195: 'ModeNumber',
  0x01b1: 'Decode',
  0x01b2: 'DefaultImageColor',
  0x0200: 'JPEGProc',
  0x0201: 'JPEGInterchangeFormat',
  0x0202: 'JPEGInterchangeFormatLength',
  0x0203: 'JPEGRestartInterval',
  0x0205: 'JPEGLosslessPredictors',
  0x0206: 'JPEGPointTransforms',
  0x0207: 'JPEGQTables',
  0x0208: 'JPEGDCTables',
  0x0209: 'JPEGACTables',
  0x0211: 'YCbCrCoefficients',
  0x0212: 'YCbCrSubSampling',
  0x0213: 'YCbCrPositioning',
  0x0214: 'ReferenceBlackWhite',
  0x022f: 'StripRowCounts',
  0x02bc: 'XMP',
  0x800d: 'ImageID',
  0x87ac: 'ImageLayer',
  // Private tags
  0x80a4: 'WangAnnotatio',
  0x82a5: 'MDFileTag',
  0x82a6: 'MDScalePixel',
  0x82a7: 'MDColorTable',
  0x82a8: 'MDLabName',
  0x82a9: 'MDSampleInfo',
  0x82aa: 'MDPrepDate',
  0x82ab: 'MDPrepTime',
  0x82ac: 'MDFileUnits',
  0x830e: 'ModelPixelScaleTag',
  0x83bb: 'IPTC',
  0x847e: 'INGRPacketDataTag',
  0x847f: 'INGRFlagRegisters',
  0x8480: 'IrasBTransformationMatrix',
  0x8482: 'ModelTiepointTag',
  0x85d8: 'ModelTransformationTag',
  0x8649: 'Photoshop',
  0x8769: 'ExifIFD',
  0x8773: 'ICCProfile',
  0x87af: 'GeoKeyDirectoryTag',
  0x87b0: 'GeoDoubleParamsTag',
  0x87b1: 'GeoAsciiParamsTag',
  0x8825: 'GPSIFD',
  0x885c: 'HylaFAXFaxRecvParams',
  0x885d: 'HylaFAXFaxSubAddress',
  0x885e: 'HylaFAXFaxRecvTime',
  0x935c: 'ImageSourceData',
  0xa005: 'InteroperabilityIFD',
  0xa480: 'GDAL_METADATA',
  0xa481: 'GDAL_NODATA',
  0xc427: 'OceScanjobDescription',
  0xc428: 'OceApplicationSelector',
  0xc429: 'OceIdentificationNumber',
  0xc42a: 'OceImageLogicCharacteristics',
  0xc612: 'DNGVersion',
  0xc613: 'DNGBackwardVersion',
  0xc614: 'UniqueCameraModel',
  0xc615: 'LocalizedCameraModel',
  0xc616: 'CFAPlaneColor',
  0xc617: 'CFALayout',
  0xc618: 'LinearizationTable',
  0xc619: 'BlackLevelRepeatDim',
  0xc61a: 'BlackLevel',
  0xc61b: 'BlackLevelDeltaH',
  0xc61c: 'BlackLevelDeltaV',
  0xc61d: 'WhiteLevel',
  0xc61e: 'DefaultScale',
  0xc61f: 'DefaultCropOrigin',
  0xc620: 'DefaultCropSize',
  0xc621: 'ColorMatrix1',
  0xc622: 'ColorMatrix2',
  0xc623: 'CameraCalibration1',
  0xc624: 'CameraCalibration2',
  0xc625: 'ReductionMatrix1',
  0xc626: 'ReductionMatrix2',
  0xc627: 'AnalogBalance',
  0xc628: 'AsShotNeutral',
  0xc629: 'AsShotWhiteXY',
  0xc62a: 'BaselineExposure',
  0xc62b: 'BaselineNoise',
  0xc62c: 'BaselineSharpness',
  0xc62d: 'BayerGreenSplit',
  0xc62e: 'LinearResponseLimit',
  0xc62f: 'CameraSerialNumber',
  0xc630: 'LensInfo',
  0xc631: 'ChromaBlurRadius',
  0xc632: 'AntiAliasStrength',
  0xc634: 'DNGPrivateData',
  0xc635: 'MakerNoteSafety',
  0xc65a: 'CalibrationIlluminant1',
  0xc65b: 'CalibrationIlluminant2',
  0xc65c: 'BestQualityScale',
  0xc660: 'AliasLayerMetadata'
};
const tagsByName = {};
for (const i in tagsById) {
  tagsByName[tagsById[i]] = Number(i);
}

var standard = /*#__PURE__*/Object.freeze({
	__proto__: null,
	tagsById: tagsById,
	tagsByName: tagsByName
});

function guessStripByteCounts(ifd) {
  if (ifd.compression !== 1) {
    throw new Error('missing mandatory StripByteCounts field in compressed image');
  }
  const bytesPerStrip = ifd.rowsPerStrip * ifd.width * ifd.samplesPerPixel * (ifd.bitsPerSample / 8);
  return new Array(ifd.stripOffsets.length).fill(bytesPerStrip);
}

// Section 14: Differencing Predictor (p. 64)
function applyHorizontalDifferencing8Bit(data, width, components) {
  let i = 0;
  while (i < data.length) {
    for (let j = components; j < width * components; j += components) {
      for (let k = 0; k < components; k++) {
        data[i + j + k] = data[i + j + k] + data[i + j - (components - k)] & 255;
      }
    }
    i += width * components;
  }
}
function applyHorizontalDifferencing16Bit(data, width, components) {
  let i = 0;
  while (i < data.length) {
    for (let j = components; j < width * components; j += components) {
      for (let k = 0; k < components; k++) {
        data[i + j + k] = data[i + j + k] + data[i + j - (components - k)] & 65535;
      }
    }
    i += width * components;
  }
}

const tags = {
  standard,
  exif,
  gps
};
class IFD {
  kind;
  data;
  fields;
  exif;
  gps;
  _hasMap;
  _map;
  constructor(kind) {
    if (!kind) {
      throw new Error('missing kind');
    }
    this.data = new Uint8Array();
    this.fields = new Map();
    this.kind = kind;
    this._hasMap = false;
    this._map = {};
  }
  get(tag) {
    if (typeof tag === 'number') {
      return this.fields.get(tag);
    } else if (typeof tag === 'string') {
      return this.fields.get(tags[this.kind].tagsByName[tag]);
    } else {
      throw new Error('expected a number or string');
    }
  }
  get map() {
    if (!this._hasMap) {
      const taglist = tags[this.kind].tagsById;
      for (const key of this.fields.keys()) {
        if (taglist[key]) {
          this._map[taglist[key]] = this.fields.get(key);
        }
      }
      this._hasMap = true;
    }
    return this._map;
  }
}

const types = new Map([[1, [1, readByte]],
// BYTE
[2, [1, readASCII]],
// ASCII
[3, [2, readShort]],
// SHORT
[4, [4, readLong]],
// LONG
[5, [8, readRational]],
// RATIONAL
[6, [1, readSByte]],
// SBYTE
[7, [1, readByte]],
// UNDEFINED
[8, [2, readSShort]],
// SSHORT
[9, [4, readSLong]],
// SLONG
[10, [8, readSRational]],
// SRATIONAL
[11, [4, readFloat]],
// FLOAT
[12, [8, readDouble]] // DOUBLE
]);
function getByteLength(type, count) {
  const val = types.get(type);
  if (!val) throw new Error(`type not found: ${type}`);
  return val[0] * count;
}
function readData(decoder, type, count) {
  const val = types.get(type);
  if (!val) throw new Error(`type not found: ${type}`);
  return val[1](decoder, count);
}
function readByte(decoder, count) {
  if (count === 1) return decoder.readUint8();
  const array = new Uint8Array(count);
  for (let i = 0; i < count; i++) {
    array[i] = decoder.readUint8();
  }
  return array;
}
function readASCII(decoder, count) {
  const strings = [];
  let currentString = '';
  for (let i = 0; i < count; i++) {
    // eslint-disable-next-line unicorn/prefer-code-point
    const char = String.fromCharCode(decoder.readUint8());
    if (char === '\0') {
      strings.push(currentString);
      currentString = '';
    } else {
      currentString += char;
    }
  }
  if (strings.length === 1) {
    return strings[0];
  } else {
    return strings;
  }
}
function readShort(decoder, count) {
  if (count === 1) return decoder.readUint16();
  const array = new Uint16Array(count);
  for (let i = 0; i < count; i++) {
    array[i] = decoder.readUint16();
  }
  return array;
}
function readLong(decoder, count) {
  if (count === 1) return decoder.readUint32();
  const array = new Uint32Array(count);
  for (let i = 0; i < count; i++) {
    array[i] = decoder.readUint32();
  }
  return array;
}
function readRational(decoder, count) {
  if (count === 1) {
    return decoder.readUint32() / decoder.readUint32();
  }
  const rationals = new Array(count);
  for (let i = 0; i < count; i++) {
    rationals[i] = decoder.readUint32() / decoder.readUint32();
  }
  return rationals;
}
function readSByte(decoder, count) {
  if (count === 1) return decoder.readInt8();
  const array = new Int8Array(count);
  for (let i = 0; i < count; i++) {
    array[i] = decoder.readInt8();
  }
  return array;
}
function readSShort(decoder, count) {
  if (count === 1) return decoder.readInt16();
  const array = new Int16Array(count);
  for (let i = 0; i < count; i++) {
    array[i] = decoder.readInt16();
  }
  return array;
}
function readSLong(decoder, count) {
  if (count === 1) return decoder.readInt32();
  const array = new Int32Array(count);
  for (let i = 0; i < count; i++) {
    array[i] = decoder.readInt32();
  }
  return array;
}
function readSRational(decoder, count) {
  if (count === 1) {
    return decoder.readInt32() / decoder.readInt32();
  }
  const rationals = new Array(count);
  for (let i = 0; i < count; i++) {
    rationals[i] = decoder.readInt32() / decoder.readInt32();
  }
  return rationals;
}
function readFloat(decoder, count) {
  if (count === 1) return decoder.readFloat32();
  const array = new Float32Array(count);
  for (let i = 0; i < count; i++) {
    array[i] = decoder.readFloat32();
  }
  return array;
}
function readDouble(decoder, count) {
  if (count === 1) return decoder.readFloat64();
  const array = new Float64Array(count);
  for (let i = 0; i < count; i++) {
    array[i] = decoder.readFloat64();
  }
  return array;
}

const CLEAR_CODE = 256;
const EOI_CODE = 257;
// 0-255 from the table + 256 for clear code + 257 for end of information code.
const TABLE_START = 258;
const MIN_BIT_LENGTH = 9;
let stringTable = [];
function initializeStringTable() {
  if (stringTable.length === 0) {
    for (let i = 0; i < 256; i++) {
      stringTable.push([i]);
    }
    // Fill the table with dummy data.
    // Elements at indices > 257 will be replaced during decompression.
    const dummyString = [];
    for (let i = 256; i < 4096; i++) {
      stringTable.push(dummyString);
    }
  }
}
const andTable = [511, 1023, 2047, 4095];
const bitJumps = [0, 0, 0, 0, 0, 0, 0, 0, 0, 511, 1023, 2047, 4095];
class LzwDecoder {
  stripArray;
  nextData = 0;
  nextBits = 0;
  bytePointer = 0;
  tableLength = TABLE_START;
  currentBitLength = MIN_BIT_LENGTH;
  outData;
  constructor(data) {
    this.stripArray = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
    this.outData = new IOBuffer(data.byteLength);
    this.initializeTable();
  }
  decode() {
    let code = 0;
    let oldCode = 0;
    while ((code = this.getNextCode()) !== EOI_CODE) {
      if (code === CLEAR_CODE) {
        this.initializeTable();
        code = this.getNextCode();
        if (code === EOI_CODE) {
          break;
        }
        this.writeString(this.stringFromCode(code));
        oldCode = code;
      } else if (this.isInTable(code)) {
        this.writeString(this.stringFromCode(code));
        this.addStringToTable(this.stringFromCode(oldCode).concat(this.stringFromCode(code)[0]));
        oldCode = code;
      } else {
        const outString = this.stringFromCode(oldCode).concat(this.stringFromCode(oldCode)[0]);
        this.writeString(outString);
        this.addStringToTable(outString);
        oldCode = code;
      }
    }
    const outArray = this.outData.toArray();
    return new DataView(outArray.buffer, outArray.byteOffset, outArray.byteLength);
  }
  initializeTable() {
    initializeStringTable();
    this.tableLength = TABLE_START;
    this.currentBitLength = MIN_BIT_LENGTH;
  }
  writeString(string) {
    this.outData.writeBytes(string);
  }
  stringFromCode(code) {
    // At this point, `code` must be defined in the table.
    return stringTable[code];
  }
  isInTable(code) {
    return code < this.tableLength;
  }
  addStringToTable(string) {
    stringTable[this.tableLength++] = string;
    if (stringTable.length > 4096) {
      stringTable = [];
      throw new Error('LZW decoding error. Please open an issue at https://github.com/image-js/tiff/issues/new/choose (include a test image).');
    }
    if (this.tableLength === bitJumps[this.currentBitLength]) {
      this.currentBitLength++;
    }
  }
  getNextCode() {
    this.nextData = this.nextData << 8 | this.stripArray[this.bytePointer++] & 0xff;
    this.nextBits += 8;
    if (this.nextBits < this.currentBitLength) {
      this.nextData = this.nextData << 8 | this.stripArray[this.bytePointer++] & 0xff;
      this.nextBits += 8;
    }
    const code = this.nextData >> this.nextBits - this.currentBitLength & andTable[this.currentBitLength - 9];
    this.nextBits -= this.currentBitLength;
    // This should not really happen but is present in other codes as well.
    // See: https://github.com/sugark/Tiffus/blob/15a60123813d1612f4ae9e4fab964f9f7d71cf63/src/org/eclipse/swt/internal/image/TIFFLZWDecoder.java
    if (this.bytePointer > this.stripArray.length) {
      return 257;
    }
    return code;
  }
}
function decompressLzw(stripData) {
  return new LzwDecoder(stripData).decode();
}

// eslint-disable-next-line prefer-named-capture-group
const dateTimeRegex = /^(\d{4}):(\d{2}):(\d{2}) (\d{2}):(\d{2}):(\d{2})$/;
class TiffIfd extends IFD {
  constructor() {
    super('standard');
  }
  // Custom fields
  get size() {
    return this.width * this.height;
  }
  get width() {
    return this.imageWidth;
  }
  get height() {
    return this.imageLength;
  }
  get components() {
    return this.samplesPerPixel;
  }
  get date() {
    const date = new Date();
    const result = dateTimeRegex.exec(this.dateTime);
    if (result === null) {
      throw new Error(`invalid dateTime: ${this.dateTime}`);
    }
    date.setFullYear(Number(result[1]), Number(result[2]) - 1, Number(result[3]));
    date.setHours(Number(result[4]), Number(result[5]), Number(result[6]));
    return date;
  }
  // IFD fields
  get newSubfileType() {
    return this.get('NewSubfileType');
  }
  get imageWidth() {
    return this.get('ImageWidth');
  }
  get imageLength() {
    return this.get('ImageLength');
  }
  get bitsPerSample() {
    const data = this.get('BitsPerSample');
    if (data && typeof data !== 'number') {
      return data[0];
    }
    return data;
  }
  get alpha() {
    const extraSamples = this.extraSamples;
    if (!extraSamples) return false;
    return extraSamples[0] !== 0;
  }
  get associatedAlpha() {
    const extraSamples = this.extraSamples;
    if (!extraSamples) return false;
    return extraSamples[0] === 1;
  }
  get extraSamples() {
    return alwaysArray(this.get('ExtraSamples'));
  }
  get compression() {
    return this.get('Compression') || 1;
  }
  get type() {
    return this.get('PhotometricInterpretation');
  }
  get fillOrder() {
    return this.get('FillOrder') || 1;
  }
  get documentName() {
    return this.get('DocumentName');
  }
  get imageDescription() {
    return this.get('ImageDescription');
  }
  get stripOffsets() {
    return alwaysArray(this.get('StripOffsets'));
  }
  get orientation() {
    return this.get('Orientation');
  }
  get samplesPerPixel() {
    return this.get('SamplesPerPixel') || 1;
  }
  get rowsPerStrip() {
    return this.get('RowsPerStrip') || 2 ** 32 - 1;
  }
  get stripByteCounts() {
    return alwaysArray(this.get('StripByteCounts'));
  }
  get minSampleValue() {
    return this.get('MinSampleValue') || 0;
  }
  get maxSampleValue() {
    return this.get('MaxSampleValue') || 2 ** this.bitsPerSample - 1;
  }
  get xResolution() {
    return this.get('XResolution');
  }
  get yResolution() {
    return this.get('YResolution');
  }
  get planarConfiguration() {
    return this.get('PlanarConfiguration') || 1;
  }
  get resolutionUnit() {
    return this.get('ResolutionUnit') || 2;
  }
  get dateTime() {
    return this.get('DateTime');
  }
  get predictor() {
    return this.get('Predictor') || 1;
  }
  get sampleFormat() {
    const data = alwaysArray(this.get('SampleFormat') || 1);
    return data[0];
  }
  get sMinSampleValue() {
    return this.get('SMinSampleValue') || this.minSampleValue;
  }
  get sMaxSampleValue() {
    return this.get('SMaxSampleValue') || this.maxSampleValue;
  }
  get palette() {
    const totalColors = 2 ** this.bitsPerSample;
    const colorMap = this.get('ColorMap');
    if (!colorMap) return undefined;
    if (colorMap.length !== 3 * totalColors) {
      throw new Error(`ColorMap size must be ${totalColors}`);
    }
    const palette = [];
    for (let i = 0; i < totalColors; i++) {
      palette.push([colorMap[i], colorMap[i + totalColors], colorMap[i + 2 * totalColors]]);
    }
    return palette;
  }
  get tileWidth() {
    return this.get('TileWidth');
  }
  get tileHeight() {
    return this.get('TileLength');
  }
  get tileOffsets() {
    return alwaysArray(this.get('TileOffsets'));
  }
  get tileByteCounts() {
    return alwaysArray(this.get('TileByteCounts'));
  }
  get tiled() {
    return this.tileWidth !== undefined && this.tileHeight !== undefined && this.tileOffsets !== undefined && this.tileByteCounts !== undefined;
  }
}
function alwaysArray(value) {
  if (typeof value === 'number') return [value];
  return value;
}

function decompressZlib(stripData) {
  const stripUint8 = new Uint8Array(stripData.buffer, stripData.byteOffset, stripData.byteLength);
  const inflated = decompressSync(stripUint8);
  return new DataView(inflated.buffer, inflated.byteOffset, inflated.byteLength);
}

const defaultOptions = {
  ignoreImageData: false
};
class TIFFDecoder extends IOBuffer {
  _nextIFD;
  constructor(data) {
    super(data);
    this._nextIFD = 0;
  }
  get isMultiPage() {
    let c = 0;
    this.decodeHeader();
    while (this._nextIFD) {
      c++;
      this.decodeIFD({
        ignoreImageData: true
      }, true);
      if (c === 2) {
        return true;
      }
    }
    if (c === 1) {
      return false;
    }
    throw unsupported('ifdCount', c);
  }
  get pageCount() {
    let c = 0;
    this.decodeHeader();
    while (this._nextIFD) {
      c++;
      this.decodeIFD({
        ignoreImageData: true
      }, true);
    }
    if (c > 0) {
      return c;
    }
    throw unsupported('ifdCount', c);
  }
  decode(options = {}) {
    const {
      pages
    } = options;
    checkPages(pages);
    const maxIndex = pages ? Math.max(...pages) : Infinity;
    options = {
      ...defaultOptions,
      ...options
    };
    const result = [];
    this.decodeHeader();
    let index = 0;
    while (this._nextIFD) {
      if (pages) {
        if (pages.includes(index)) {
          result.push(this.decodeIFD(options, true));
        } else {
          this.decodeIFD({
            ignoreImageData: true
          }, true);
        }
        if (index === maxIndex) {
          break;
        }
      } else {
        result.push(this.decodeIFD(options, true));
      }
      index++;
    }
    if (index < maxIndex && maxIndex !== Infinity) {
      throw new RangeError(`Index ${maxIndex} is out of bounds. The stack only contains ${index} images.`);
    }
    return result;
  }
  decodeHeader() {
    // Byte offset
    const value = this.readUint16();
    if (value === 0x4949) {
      this.setLittleEndian();
    } else if (value === 0x4d4d) {
      this.setBigEndian();
    } else {
      throw new Error(`invalid byte order: 0x${value.toString(16)}`);
    }
    // Magic number
    if (this.readUint16() !== 42) {
      throw new Error('not a TIFF file');
    }
    // Offset of the first IFD
    this._nextIFD = this.readUint32();
  }
  decodeIFD(options, tiff) {
    this.seek(this._nextIFD);
    let ifd;
    if (tiff) {
      ifd = new TiffIfd();
    } else {
      if (!options.kind) {
        throw new Error(`kind is missing`);
      }
      ifd = new IFD(options.kind);
    }
    const numEntries = this.readUint16();
    for (let i = 0; i < numEntries; i++) {
      this.decodeIFDEntry(ifd);
    }
    if (!options.ignoreImageData) {
      if (!(ifd instanceof TiffIfd)) {
        throw new Error('must be a tiff ifd');
      }
      this.decodeImageData(ifd);
    }
    this._nextIFD = this.readUint32();
    return ifd;
  }
  decodeIFDEntry(ifd) {
    const offset = this.offset;
    const tag = this.readUint16();
    const type = this.readUint16();
    const numValues = this.readUint32();
    if (type < 1 || type > 12) {
      this.skip(4); // unknown type, skip this value
      return;
    }
    const valueByteLength = getByteLength(type, numValues);
    if (valueByteLength > 4) {
      this.seek(this.readUint32());
    }
    const value = readData(this, type, numValues);
    ifd.fields.set(tag, value);
    // Read sub-IFDs
    if (tag === 0x8769 || tag === 0x8825) {
      const currentOffset = this.offset;
      let kind = 'exif';
      if (tag === 0x8769) {
        kind = 'exif';
      } else if (tag === 0x8825) {
        kind = 'gps';
      }
      this._nextIFD = value;
      ifd[kind] = this.decodeIFD({
        kind,
        ignoreImageData: true
      }, false);
      this.offset = currentOffset;
    }
    // go to the next entry
    this.seek(offset);
    this.skip(12);
  }
  decodeImageData(ifd) {
    const orientation = ifd.orientation;
    if (orientation && orientation !== 1) {
      throw unsupported('orientation', orientation);
    }
    switch (ifd.type) {
      case 0: // WhiteIsZero
      case 1: // BlackIsZero
      case 2: // RGB
      case 3:
        // Palette color
        if (ifd.tiled) {
          this.readTileData(ifd);
        } else {
          this.readStripData(ifd);
        }
        break;
      default:
        throw unsupported('image type', ifd.type);
    }
    this.applyPredictor(ifd);
    this.convertAlpha(ifd);
    if (ifd.bitsPerSample === 1) {
      this.split1BitData(ifd);
    }
    if (ifd.type === 0) {
      // WhiteIsZero: we invert the values
      const bitDepth = ifd.bitsPerSample;
      const maxValue = 2 ** bitDepth - 1;
      for (let i = 0; i < ifd.data.length; i++) {
        ifd.data[i] = maxValue - ifd.data[i];
      }
    }
  }
  split1BitData(ifd) {
    const {
      imageWidth,
      imageLength,
      samplesPerPixel
    } = ifd;
    const data = new Uint8Array(imageLength * imageWidth * samplesPerPixel);
    const bytesPerRow = Math.ceil(imageWidth * samplesPerPixel / 8);
    let dataIndex = 0;
    for (let row = 0; row < imageLength; row++) {
      const rowStartByte = row * bytesPerRow;
      for (let col = 0; col < imageWidth * samplesPerPixel; col++) {
        const byteIndex = rowStartByte + Math.floor(col / 8);
        const bitIndex = 7 - col % 8;
        const bit = ifd.data[byteIndex] >> bitIndex & 1;
        data[dataIndex++] = bit;
      }
    }
    ifd.data = data;
  }
  static uncompress(data, compression = 1) {
    switch (compression) {
      // No compression, nothing to do
      case 1:
        {
          return data;
        }
      // LZW compression
      case 5:
        {
          return decompressLzw(data);
        }
      // Zlib and Deflate compressions. They are identical.
      case 8:
      case 32946:
        {
          return decompressZlib(data);
        }
      case 2:
        // CCITT Group 3 1-Dimensional Modified Huffman run length encoding
        throw unsupported('Compression', 'CCITT Group 3');
      case 32773:
        // PackBits compression
        throw unsupported('Compression', 'PackBits');
      default:
        throw unsupported('Compression', compression);
    }
  }
  createSampleReader(sampleFormat, bitDepth, littleEndian) {
    if (bitDepth === 8 || bitDepth === 1) {
      return (data, index) => data.getUint8(index);
    } else if (bitDepth === 16) {
      return (data, index) => data.getUint16(2 * index, littleEndian);
    } else if (bitDepth === 32 && sampleFormat === 3) {
      return (data, index) => data.getFloat32(4 * index, littleEndian);
    } else if (bitDepth === 64 && sampleFormat === 3) {
      return (data, index) => data.getFloat64(8 * index, littleEndian);
    } else {
      throw unsupported('bitDepth', bitDepth);
    }
  }
  readStripData(ifd) {
    // General Image Dimensions
    const width = ifd.width;
    const height = ifd.height;
    const size = ifd.bitsPerSample !== 1 ? width * ifd.samplesPerPixel * height : Math.ceil(width * ifd.samplesPerPixel / 8) * height;
    // Compressed Strip Layout
    const stripOffsets = ifd.stripOffsets;
    const stripByteCounts = ifd.stripByteCounts || guessStripByteCounts(ifd);
    const littleEndian = this.isLittleEndian();
    // For 1-bit images, calculate pixels per strip correctly
    const stripLength = ifd.bitsPerSample !== 1 ? width * ifd.samplesPerPixel * ifd.rowsPerStrip : Math.ceil(width * ifd.samplesPerPixel / 8) * ifd.rowsPerStrip;
    const readSamples = this.createSampleReader(ifd.sampleFormat, ifd.bitsPerSample, littleEndian);
    // Output Data Buffer
    const output = getDataArray(size, ifd.bitsPerSample, ifd.sampleFormat);
    // Iterate over Number of Strips
    let start = 0;
    for (let i = 0; i < stripOffsets.length; i++) {
      // Extract Strip Data, Uncompress
      const stripData = new DataView(this.buffer, this.byteOffset + stripOffsets[i], stripByteCounts[i]);
      const uncompressed = TIFFDecoder.uncompress(stripData, ifd.compression);
      // Last strip can be smaller
      const length = Math.min(stripLength, size - start);
      // Write Uncompressed Strip Data to Output (Linear Layout)
      for (let index = 0; index < length; ++index) {
        const value = readSamples(uncompressed, index);
        output[start + index] = value;
      }
      start += length;
    }
    ifd.data = output;
    // For 1-bit images, we need to convert the data to bits
  }
  readTileData(ifd) {
    if (!ifd.tileWidth || !ifd.tileHeight) {
      return;
    }
    const width = ifd.width;
    const height = ifd.height;
    const size = ifd.bitsPerSample !== 1 ? width * height * ifd.samplesPerPixel : Math.ceil(width * ifd.samplesPerPixel / 8) * height;
    const twidth = ifd.tileWidth;
    const theight = ifd.tileHeight;
    const nwidth = Math.ceil(width / twidth);
    const nheight = Math.ceil(height / theight);
    const tileOffsets = ifd.tileOffsets;
    const tileByteCounts = ifd.tileByteCounts;
    const littleEndian = this.isLittleEndian();
    const readSamples = this.createSampleReader(ifd.sampleFormat, ifd.bitsPerSample, littleEndian);
    const output = getDataArray(size, ifd.bitsPerSample, ifd.sampleFormat);
    for (let nx = 0; nx < nwidth; ++nx) {
      for (let ny = 0; ny < nheight; ++ny) {
        const nind = ny * nwidth + nx;
        const tileData = new DataView(this.buffer, this.byteOffset + tileOffsets[nind], tileByteCounts[nind]);
        const uncompressed = TIFFDecoder.uncompress(tileData, ifd.compression);
        if (ifd.bitsPerSample === 1) {
          // For 1-bit: read sequentially by bytes
          const bytesPerRow = Math.ceil(width / 8);
          const tileBytesPerRow = Math.ceil(twidth / 8);
          for (let ty = 0; ty < theight && ny * theight + ty < height; ty++) {
            const iy = ny * theight + ty;
            const srcStart = ty * tileBytesPerRow;
            const dstStart = iy * bytesPerRow + Math.floor(nx * twidth / 8);
            // Copy the row of bytes from tile to output
            const bytesToCopy = Math.min(tileBytesPerRow, bytesPerRow - Math.floor(nx * twidth / 8));
            for (let b = 0; b < bytesToCopy; b++) {
              output[dstStart + b] = readSamples(uncompressed, srcStart + b);
            }
          }
        } else {
          // For 8/16/32-bit: read by pixels
          for (let ty = 0; ty < theight; ty++) {
            for (let tx = 0; tx < twidth; tx++) {
              const ix = nx * twidth + tx;
              const iy = ny * theight + ty;
              if (ix >= width || iy >= height) continue;
              const tilePixelIndex = ty * twidth + tx;
              const value = readSamples(uncompressed, tilePixelIndex);
              const outputPixelIndex = (iy * width + ix) * ifd.samplesPerPixel;
              output[outputPixelIndex] = value;
            }
          }
        }
      }
    }
    ifd.data = output;
  }
  applyPredictor(ifd) {
    const bitDepth = ifd.bitsPerSample;
    switch (ifd.predictor) {
      case 1:
        {
          // No prediction scheme, nothing to do
          break;
        }
      case 2:
        {
          if (bitDepth === 8) {
            applyHorizontalDifferencing8Bit(ifd.data, ifd.width, ifd.components);
          } else if (bitDepth === 16) {
            applyHorizontalDifferencing16Bit(ifd.data, ifd.width, ifd.components);
          } else {
            throw new Error(`Horizontal differencing is only supported for images with a bit depth of ${bitDepth}`);
          }
          break;
        }
      default:
        throw new Error(`invalid predictor: ${ifd.predictor}`);
    }
  }
  convertAlpha(ifd) {
    if (ifd.alpha && ifd.associatedAlpha) {
      const {
        data,
        components,
        maxSampleValue
      } = ifd;
      for (let i = 0; i < data.length; i += components) {
        const alphaValue = data[i + components - 1];
        for (let j = 0; j < components - 1; j++) {
          data[i + j] = Math.round(data[i + j] * maxSampleValue / alphaValue);
        }
      }
    }
  }
}
function getDataArray(size, bitDepth, sampleFormat) {
  if (bitDepth === 8 || bitDepth === 1) {
    return new Uint8Array(size);
  } else if (bitDepth === 16) {
    return new Uint16Array(size);
  } else if (bitDepth === 32 && sampleFormat === 3) {
    return new Float32Array(size);
  } else if (bitDepth === 64 && sampleFormat === 3) {
    return new Float64Array(size);
  } else {
    throw unsupported('bit depth / sample format', `${bitDepth} / ${sampleFormat}`);
  }
}
function unsupported(type, value) {
  return new Error(`Unsupported ${type}: ${value}`);
}
function checkPages(pages) {
  if (pages) {
    for (const page of pages) {
      if (page < 0 || !Number.isInteger(page)) {
        throw new RangeError(`Index ${page} is invalid. Must be a positive integer.`);
      }
    }
  }
}

function decodeTIFF(data, options) {
  const decoder = new TIFFDecoder(data);
  return decoder.decode(options);
}

function decode$1(data) {
  const buffer = new IOBuffer(data);
  const result = {};
  buffer.setBigEndian();
  const val = buffer.readUint16();
  if (val !== 0xffd8) {
    throw new Error('SOI marker not found. Not a valid JPEG file');
  }
  const next = buffer.readUint16();
  if (next === 0xffe1) {
    buffer.skip(2);
    const header = buffer.readBytes(6);
    if (header[0] === 69 &&
    // E
    header[1] === 120 &&
    // x
    header[2] === 105 &&
    // i
    header[3] === 102 &&
    // f
    header[4] === 0 && header[5] === 0) {
      result.exif = decodeTIFF(new Uint8Array(buffer.buffer, buffer.byteOffset + 12, buffer.byteLength - 12), {
        pages: [0],
        ignoreImageData: true
      });
    }
  }
  return result;
}

/**
 * Get metadata from an IFD.
 * @param ifd - The IFD.
 * @returns The metadata.
 */
function getMetadata(ifd) {
  return {
    tiff: {
      fields: ifd.fields,
      tags: ifd.map
    },
    exif: ifd.exif
  };
}

/**
 * Decode a jpeg. See the jpeg-js npm module.
 * @param buffer - The data to decode.
 * @returns The decoded image.
 */
function decodeJpeg(buffer) {
  const jpeg = jpegJs.decode(buffer, {
    useTArray: true,
    maxMemoryUsageInMB: Number.POSITIVE_INFINITY,
    maxResolutionInMP: Number.POSITIVE_INFINITY
  });
  const decodedExif = decode$1(buffer);
  // TODO : handle stacks (many IFDs?)
  const meta = decodedExif.exif?.[0] ? getMetadata(decodedExif.exif[0]) : undefined;
  return new Image(jpeg.width, jpeg.height, {
    data: jpeg.data,
    colorModel: 'RGBA',
    meta
  });
}

/**
 * Decode a PNG. See the fast-png npm module.
 * @param buffer - The data to decode.
 * @returns The decoded image.
 */
function decodePng(buffer) {
  const png = decodePng$1(buffer);
  let colorModel;
  const bitDepth = png.depth;
  if (png.palette) {
    return loadPalettePng(png);
  }
  if (bitDepth === 1) {
    return new Image(png.width, png.height, {
      data: decodeBinary(png),
      colorModel: 'GREY'
    });
  }
  switch (png.channels) {
    case 1:
      colorModel = 'GREY';
      break;
    case 2:
      colorModel = 'GREYA';
      break;
    case 3:
      colorModel = 'RGB';
      break;
    case 4:
      colorModel = 'RGBA';
      break;
    default:
      throw new RangeError(`invalid number of channels: ${png.channels}`);
  }
  const resolution = getResolution(png);
  return new Image(png.width, png.height, {
    colorModel,
    bitDepth,
    data: png.data,
    resolution
  });
}
/**
 * Compute PNG data from palette information and return a new image.
 * @param png - Decoded PNG.
 * @returns The new image.
 */
function loadPalettePng(png) {
  assert(png.palette);
  const pixels = png.width * png.height;
  const data = new Uint8Array(pixels * png.palette[0].length);
  const pixelsPerByte = 8 / png.depth;
  const factor = png.depth < 8 ? pixelsPerByte : 1;
  const mask = Number.parseInt('1'.repeat(png.depth), 2);
  let dataIndex = 0;
  for (let i = 0; i < pixels; i++) {
    const index = Math.floor(i / factor);
    let value = png.data[index];
    if (png.depth < 8) {
      value = value >>> png.depth * (pixelsPerByte - 1 - i % pixelsPerByte) & mask;
    }
    const paletteValue = png.palette[value];
    for (const paletteChannel of paletteValue) {
      data[dataIndex++] = paletteChannel;
    }
  }
  const resolution = getResolution(png);
  return new Image(png.width, png.height, {
    data,
    colorModel: png.palette[0].length === 4 ? 'RGBA' : 'RGB',
    resolution
  });
}
function decodeBinary(png) {
  const totalPixels = png.width * png.height;
  const result = new Uint8Array(totalPixels);
  const pngData = png.data;
  const padding = png.width % 8;
  const bytesPerLine = Math.ceil(png.width / 8);
  let pixelIndex = 0;
  for (let byteIndex = 0; byteIndex < pngData.length && pixelIndex < totalPixels; byteIndex++) {
    const byte = pngData[byteIndex];
    const limit = byteIndex % bytesPerLine === 0 ? 8 - padding : 0;
    for (let bitIndex = 7; bitIndex >= limit && pixelIndex < totalPixels; bitIndex--) {
      const bit = byte >> bitIndex & 1;
      result[pixelIndex++] = bit * 255;
    }
  }
  return result;
}
/**
 * Gets image's resolution from its parsed data.
 * @param png - Parsed .png image.
 * @returns Object with resolution data if exists.
 */
function getResolution(png) {
  if (png.resolution) {
    return png.resolution.unit === 1 ? /*If the resolution unit is meters*/{
      x: png.resolution.x,
      y: png.resolution.y,
      unit: 'meter'
    } : /*If resolution unit is unknown */{
      x: png.resolution.x,
      y: png.resolution.y,
      unit: 'unknown'
    };
  } else {
    return undefined;
  }
}

/**
 * Decode a TIFF. See the tiff module.
 * @param buffer - The data to decode.
 * @returns The decoded image.
 */
function decodeTiff(buffer) {
  const result = decodeTIFF(buffer, {
    pages: [0]
  });
  return getImageFromIFD(result[0]);
}
/**
 * Create image from a single IFD.
 * @param ifd - The IFD.
 * @returns The decoded image.
 */
function getImageFromIFD(ifd) {
  if (ifd.data instanceof Float32Array || ifd.data instanceof Float64Array) {
    throw new Error('Float TIFF data is not supported.');
  }
  const resolution = getTiffResolution(ifd);
  if (ifd.type === 3) {
    const hasAlpha = ifd.samplesPerPixel === 2;
    const pixelLength = hasAlpha ? 4 : 3;
    const data = new Uint16Array(pixelLength * ifd.width * ifd.height);
    const palette = ifd.palette;
    let ptr = 0;
    if (hasAlpha) {
      for (let index = 0; index < ifd.data.length; index += ifd.samplesPerPixel) {
        const color = palette[ifd.data[index]];
        data[ptr++] = color[0];
        data[ptr++] = color[1];
        data[ptr++] = color[2];
        // To ensure that the value is 16 bits.
        data[ptr++] = Math.round(ifd.data[index + 1] / 2 ** ifd.bitsPerSample * 65535);
      }
    } else {
      for (let index = 0; index < ifd.data.length; index += ifd.samplesPerPixel) {
        const color = palette[ifd.data[index]];
        data[ptr++] = color[0];
        data[ptr++] = color[1];
        data[ptr++] = color[2];
      }
    }
    return new Image(ifd.width, ifd.height, {
      data,
      colorModel: hasAlpha ? 'RGBA' : 'RGB',
      bitDepth: 16,
      meta: getMetadata(ifd),
      resolution
    });
  } else if (ifd.type === 1 || ifd.type === 0) {
    if (ifd.bitsPerSample !== 1) {
      return new Image(ifd.width, ifd.height, {
        data: ifd.data,
        bitDepth: ifd.bitsPerSample,
        colorModel: ifd.alpha ? 'GREYA' : 'GREY',
        meta: getMetadata(ifd),
        resolution
      });
    } else {
      return new Image(ifd.width, ifd.height, {
        data: ifd.data.map(pixel => pixel * 255),
        bitDepth: 8,
        colorModel: 'GREY',
        meta: getMetadata(ifd),
        resolution
      });
    }
  } else {
    return new Image(ifd.width, ifd.height, {
      data: ifd.data,
      bitDepth: ifd.bitsPerSample,
      colorModel: ifd.alpha ? 'RGBA' : 'RGB',
      meta: getMetadata(ifd),
      resolution
    });
  }
}
/**
 * Gets image resolution from its metadata and converts it into Pixels per meter, when it's possible. Also keeps original resolution values and units.
 * @param ifd - Tiff metadata.
 * @returns Resolution object.
 */
function getTiffResolution(ifd) {
  if (!ifd.xResolution || !ifd.yResolution) {
    return undefined;
  }
  switch (ifd.resolutionUnit) {
    case 1:
      return {
        x: ifd.xResolution,
        y: ifd.yResolution,
        unit: 'unknown'
      };
    case 3:
      return {
        x: ifd.xResolution,
        y: ifd.yResolution,
        unit: 'centimeter'
      };
    default:
      return {
        x: ifd.xResolution,
        y: ifd.yResolution,
        unit: 'inch'
      };
  }
}

/**
 * Decode input data. Data format is automatically detected.
 * Possible formats: png, jpeg and tiff.
 * @param data - Data to decode.
 * @returns The decoded image.
 */
function decode(data) {
  const typedArray = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
  const type = imageType(typedArray);
  return M$2(type).with({
    mime: 'image/png'
  }, () => decodePng(typedArray)).with({
    mime: 'image/jpeg'
  }, () => decodeJpeg(typedArray)).with({
    mime: 'image/tiff'
  }, () => decodeTiff(typedArray)).with({
    mime: 'image/bmp'
  }, () => decodeBmp(typedArray)).otherwise(() => {
    throw new RangeError(`invalid data format: ${type?.mime}`);
  });
}

/**
 * Read an image from the disk.
 * The file format is automatically selected based on the first few bytes.
 * This method is only implemented for Node.js.
 * @param path - The path to the image.
 * @returns Image instance.
 */
async function read(path) {
  const nodeApi = getNodeApiOrThrow('read');
  const data = await nodeApi.fs.promises.readFile(path);
  return decode(data);
}
/**
 * Synchronous version of {@link read}.
 * This method is only implemented for Node.js.
 * @param path - The path to the image.
 * @returns Image instance.
 */
function readSync(path) {
  const nodeApi = getNodeApiOrThrow('readSync');
  return decode(nodeApi.fs.readFileSync(path));
}

/**
 * Read an image from an HTML canvas element.
 * @param canvas - Canvas element.
 * @returns The read image.
 */
function readCanvas(canvas) {
  const ctx = canvas.getContext('2d');
  assert(ctx);
  const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
  return new Image(imageData.width, imageData.height, {
    data: new Uint8Array(imageData.data.buffer, imageData.data.byteOffset, imageData.data.byteLength),
    colorModel: 'RGBA'
  });
}

// TODO: Create nodejs version that throws an error
/**
 * Read an image from an HTML image source.
 * @param img - Image source such as an <img> or <svg> element.
 * @returns The read image.
 */
function readImg(img) {
  const canvas = document.createElement('canvas');
  canvas.width = img.width;
  canvas.height = img.height;
  const ctx = canvas.getContext('2d');
  assert(ctx);
  ctx.drawImage(img, 0, 0);
  return readCanvas(canvas);
}

/**
 * Fetches image URL and decodes it.
 * @param dataUrl - Image URL.
 * @returns decoded image data.
 */
async function fetchURL(dataUrl) {
  const response = await fetch(dataUrl);
  const arrayBuffer = await response.arrayBuffer();
  const image = decode(new DataView(arrayBuffer));
  return image;
}

/**
 * Convert HSV (hue, saturation, value) color code to RGB.
 * - Hue: angle in the color wheel (from red to purple), in range 0-359.
 * - Saturation: how strong the color is (from white to bright color), in range 0-255.
 * - Value: basically the brightness (from black to intense color), in range 0-255.
 * @param hsv - The HSV color.
 * @returns The RGB color.
 */
function hsvToRgb(hsv) {
  const h = hsv[0];
  const s = hsv[1] / 255;
  const v = hsv[2] / 255;
  const C = s * v;
  const X = C * (1 - Math.abs(h / 60 % 2 - 1));
  const m = v - C;
  let r, g, b;
  if (h >= 0 && h < 60) {
    r = C;
    g = X;
    b = 0;
  } else if (h >= 60 && h < 120) {
    r = X;
    g = C;
    b = 0;
  } else if (h >= 120 && h < 180) {
    r = 0;
    g = C;
    b = X;
  } else if (h >= 180 && h < 240) {
    r = 0;
    g = X;
    b = C;
  } else if (h >= 240 && h < 300) {
    r = X;
    g = 0;
    b = C;
  } else {
    r = C;
    g = 0;
    b = X;
  }
  const rgb = new Uint8Array(3);
  rgb[0] = (r + m) * 255;
  rgb[1] = (g + m) * 255;
  rgb[2] = (b + m) * 255;
  return rgb;
}

/**
 * Convert RGB array to 32 bits number where alpha is set to 255.
 * @param rgb - The RGB color array.
 * @returns 32 bits number encoding RGBA color.
 */
function rgbToNumber(rgb) {
  return 0xff000000 + (rgb[2] << 16) + (rgb[1] << 8) + rgb[0];
}

/**
 * Return a map where ROIs are red (negative) or green (positive) depending on the ROI index.
 * @param options - Color maps options.
 * @returns The colored map.
 */
function getBinaryMap(options) {
  const {
    nbNegative,
    nbPositive,
    whiteHue = 120,
    blackHue = 0,
    roiKind = 'bw'
  } = options;
  const colorMap = new Uint32Array(nbNegative + nbPositive + 1);
  // negative values
  if (roiKind === 'bw' || roiKind === 'black') {
    for (let i = -nbNegative; i < 0; i++) {
      const hsv = [blackHue, 255, 255];
      colorMap[i + nbNegative] = rgbToNumber(hsvToRgb(hsv));
    }
  }
  if (roiKind === 'bw' || roiKind === 'white') {
    // positive values
    for (let i = 1; i <= nbPositive; i++) {
      const hsv = [whiteHue, 255, 255];
      colorMap[i + nbNegative] = rgbToNumber(hsvToRgb(hsv));
    }
  }
  return colorMap;
}

/**
 * Return a map where ROIs are all different hues.
 * @param options - Get temperature map options.
 * @returns The colored map.
 */
function getRainbowMap(options) {
  const {
    nbNegative,
    nbPositive,
    roiKind = 'bw'
  } = options;
  const colorMap = new Uint32Array(nbNegative + nbPositive + 1);
  const hueRange = 360;
  const step = M$2(roiKind).with('bw', () => hueRange / (nbNegative + nbPositive)).with('black', () => hueRange / nbNegative).with('white', () => hueRange / nbPositive).exhaustive();
  // negative values
  let hue = 0;
  if (roiKind === 'bw' || roiKind === 'black') {
    for (let i = -nbNegative; i < 0; i++) {
      const hsv = [hue, 255, 255];
      colorMap[i + nbNegative] = rgbToNumber(hsvToRgb(hsv));
      hue += step;
    }
  }
  // positive values
  if (roiKind === 'bw' || roiKind === 'white') {
    for (let i = 1; i <= nbPositive; i++) {
      const hsv = [hue, 255, 255];
      colorMap[i + nbNegative] = rgbToNumber(hsvToRgb(hsv));
      hue += step;
    }
  }
  return colorMap;
}

/**
 * Return a map where ROIs are different shades of red (positive) or blue (negative) depending on the ROI index. It it the saturation of the HSV color model that is varied.
 * @param options - Get temperature map options.
 * @returns The colored map.
 */
function getSaturationMap(options) {
  const {
    nbNegative,
    nbPositive,
    roiKind = 'bw',
    whiteHue = 0,
    blackHue = 240
  } = options;
  const colorMap = new Uint32Array(nbNegative + nbPositive + 1);
  const range = 255 - 63; // saturation range for good contrast
  const negativeStep = range / nbNegative;
  const positiveStep = range / nbPositive;
  // negative values
  let counter = 0;
  if (roiKind === 'bw' || roiKind === 'black') {
    for (let i = -nbNegative; i < 0; i++) {
      const hsv = [blackHue, 255 - counter++ * negativeStep, 255];
      colorMap[i + nbNegative] = rgbToNumber(hsvToRgb(hsv));
    }
  }
  // positive values
  counter = 0;
  if (roiKind === 'bw' || roiKind === 'white') {
    for (let i = 1; i <= nbPositive; i++) {
      const hsv = [whiteHue, 255 - counter++ * positiveStep, 255];
      colorMap[i + nbNegative] = rgbToNumber(hsvToRgb(hsv));
    }
  }
  return colorMap;
}

/**
 * Return a map of 32 bits integers corresponding to the colors of each ROI.
 * @param options - Get color map options.
 * @returns The color map.
 */
function getColorMap(options) {
  const {
    mode = 'binary'
  } = options;
  options = {
    roiKind: 'bw',
    ...options
  };
  return M$2(mode).with('binary', () => getBinaryMap(options)).with('saturation', () => getSaturationMap(options)).with('rainbow', () => getRainbowMap(options)).exhaustive();
}

const RoisColorMode = {
  /**
   * Only two acceptable values: red or green.
   */
  BINARY: 'binary',
  /**
   * Palette of reds and blues.
   */
  SATURATION: 'saturation',
  /**
   * All possible hues (gradient of colors).
   */
  RAINBOW: 'rainbow'
};
/**
 * Generate an image with all the ROIs of various colors.
 * @param roiMapManager - The ROI map manager.
 * @param options - Color ROIs options.
 * @returns The colored image.
 */
function colorRois(roiMapManager, options = {}) {
  const {
    roiKind = 'bw',
    mode = 'binary'
  } = options;
  const map = roiMapManager.getMap();
  const image = new Image(map.width, map.height, {
    colorModel: 'RGBA'
  });
  const colorMap = getColorMap({
    roiKind,
    mode,
    nbNegative: map.nbNegative,
    nbPositive: map.nbPositive
  });
  const data32 = new Uint32Array(image.getRawImage().data.buffer);
  for (let index = 0; index < image.size; index++) {
    data32[index] = colorMap[map.data[index] + map.nbNegative];
  }
  return image;
}

/**
 * Return an array with the coordinates of the pixels that are on the border of the ROI.
 * The reference is the top-left corner of the ROI.
 * @param roi - ROI to process.
 * @param options - Get border points options.
 * @returns The array of border pixels.
 */
function getBorderPoints(roi, options = {}) {
  const mask = roi.getMask();
  return mask.getBorderPoints(options);
}

/**
 * Finds external contour of the roi from its mask.
 * @param roi - roi to find contour from.
 * @param options - GetExternalContourOptions.
 * @returns Array of contour points.
 */
function getExternalContour(roi, options) {
  const mask = roi.getMask();
  return mask.getExternalContour(options);
}

/**
 * Generate a mask of an ROI.
 * @param roi - The ROI to generate a mask for.
 * @param options - Get mask options.
 * @returns The ROI mask.
 */
function getMask(roi, options = {}) {
  const {
    solidFill = false
  } = options;
  const mask = new Mask(roi.width, roi.height, {
    origin: roi.origin
  });
  for (let row = 0; row < roi.height; row++) {
    for (let column = 0; column < roi.width; column++) {
      if (roi.getMapValue(roi.origin.column + column, roi.origin.row + row) === roi.id) {
        mask.setBit(column, row, 1);
      } else {
        mask.setBit(column, row, 0);
      }
    }
  }
  if (solidFill) {
    mask.solidFill({
      out: mask
    });
  }
  return mask;
}

/**
 * Calculates ellipse on around ROI.
 * @param roi - Region of interest.
 * @returns Ellipse.
 */
function getEllipse(roi) {
  const xCenter = roi.centroid.column;
  const yCenter = roi.centroid.row;
  const xCentered = roi.relativePoints.map(point => point.column - xCenter);
  const yCentered = roi.relativePoints.map(point => point.row - yCenter);
  const centeredXVariance = xVariance(xCentered, {
    unbiased: false
  });
  const centeredYVariance = xVariance(yCentered, {
    unbiased: false
  });
  const centeredCovariance = xyCovariance({
    x: xCentered,
    y: yCentered
  }, {
    unbiased: false
  });
  //spectral decomposition of the sample covariance matrix
  const sampleCovarianceMatrix = [[centeredXVariance, centeredCovariance], [centeredCovariance, centeredYVariance]];
  const e = new EigenvalueDecomposition(sampleCovarianceMatrix);
  const eigenvalues = e.realEigenvalues;
  const vectors = e.eigenvectorMatrix;
  assert(eigenvalues[0] <= eigenvalues[1]);
  let radiusMajor = Math.sqrt(eigenvalues[1]);
  let radiusMinor = Math.sqrt(eigenvalues[0]);
  const vectorMajor = vectors.getColumn(1);
  const vectorMinor = vectors.getColumn(0);
  let majorAxisPoint1 = {
    column: xCenter + radiusMajor * vectorMajor[0],
    row: yCenter + radiusMajor * vectorMajor[1]
  };
  let majorAxisPoint2 = {
    column: xCenter - radiusMajor * vectorMajor[0],
    row: yCenter - radiusMajor * vectorMajor[1]
  };
  let minorAxisPoint1 = {
    column: xCenter + radiusMinor * vectorMinor[0],
    row: yCenter + radiusMinor * vectorMinor[1]
  };
  let minorAxisPoint2 = {
    column: xCenter - radiusMinor * vectorMinor[0],
    row: yCenter - radiusMinor * vectorMinor[1]
  };
  let majorLength = Math.hypot(majorAxisPoint1.column - majorAxisPoint2.column, majorAxisPoint1.row - majorAxisPoint2.row);
  let minorLength = Math.hypot(minorAxisPoint1.column - majorAxisPoint2.column, minorAxisPoint1.row - minorAxisPoint2.row);
  let ellipseSurface = minorLength / 2 * majorLength / 2 * Math.PI;
  if (ellipseSurface !== roi.surface) {
    const scaleFactor = Math.sqrt(roi.surface / ellipseSurface);
    radiusMajor *= scaleFactor;
    radiusMinor *= scaleFactor;
    majorAxisPoint1 = {
      column: xCenter + radiusMajor * vectorMajor[0],
      row: yCenter + radiusMajor * vectorMajor[1]
    };
    majorAxisPoint2 = {
      column: xCenter - radiusMajor * vectorMajor[0],
      row: yCenter - radiusMajor * vectorMajor[1]
    };
    minorAxisPoint1 = {
      column: xCenter + radiusMinor * vectorMinor[0],
      row: yCenter + radiusMinor * vectorMinor[1]
    };
    minorAxisPoint2 = {
      column: xCenter - radiusMinor * vectorMinor[0],
      row: yCenter - radiusMinor * vectorMinor[1]
    };
    majorLength *= scaleFactor;
    minorLength *= scaleFactor;
    ellipseSurface *= scaleFactor ** 2;
  }
  return {
    center: {
      column: xCenter,
      row: yCenter
    },
    majorAxis: {
      points: [majorAxisPoint1, majorAxisPoint2],
      length: majorLength,
      angle: toDegrees(getAngle(majorAxisPoint1, majorAxisPoint2))
    },
    minorAxis: {
      points: [minorAxisPoint1, minorAxisPoint2],
      length: minorLength,
      angle: toDegrees(getAngle(minorAxisPoint1, minorAxisPoint2))
    },
    surface: ellipseSurface
  };
}

class Roi {
  /**
   * Original map with all the ROI IDs.
   */
  map;
  /**
   * ID of the ROI. Positive for white ROIs and negative for black ones.
   */
  id;
  /**
   * Origin of the ROI. The top-left corner of the rectangle around
   * the ROI relative to the original image.
   */
  origin;
  /**
   * Width of the ROI.
   */
  width;
  /**
   * Height of the ROI.
   */
  height;
  /**
   * Surface of the ROI.
   */
  surface;
  /**
   * Cached values of properties to improve performance.
   */
  #computed;
  constructor(map, id, width, height, origin, surface) {
    this.map = map;
    this.id = id;
    this.origin = origin;
    this.width = width;
    this.height = height;
    this.surface = surface;
    this.#computed = {};
  }
  /**
   * Return the value at the given coordinates in an ROI map.
   * @param column - Column of the value.
   * @param row - Row of the value.
   * @returns The value at the given coordinates.
   */
  getMapValue(column, row) {
    return this.map.data[this.map.width * row + column];
  }
  /**
   * Returns the ratio between the width and the height of the bounding rectangle of the ROI.
   * @returns The width by height ratio.
   */
  getRatio() {
    return this.width / this.height;
  }
  /**
   * Generates a mask of an ROI. You can specify the kind of mask you want using the `kind` option.
   * @param options - Get Mask options.
   * @returns The ROI mask.
   */
  getMask(options) {
    return getMask(this, options);
  }
  /**
   * Computes the diameter of a circle that has the same perimeter as the particle image.
   * @returns Ped value in pixels.
   */
  get ped() {
    return this.perimeter / Math.PI;
  }
  /**
   * Return an array with the coordinates of the pixels that are on the border of the ROI.
   * The points are defined as [column, row].
   * @param options - Get border points options.
   * @returns The array of border pixels.
   */
  getBorderPoints(options) {
    return getBorderPoints(this, options);
  }
  /**
   * Finds external contour of the roi from its mask.
   * @param options - GetExternalContourOptions.
   * @returns Array of contour points.
   */
  getExternalContour(options) {
    return getExternalContour(this, options);
  }
  /**
   * Returns an array of ROIs IDs that are included in the current ROI.
   * This will be useful to know if there are some holes in the ROI.
   * @returns InternalIDs.
   */
  get internalIDs() {
    return this.#getComputed('internalIDs', () => {
      const internal = [this.id];
      const roiMap = this.map;
      const data = roiMap.data;
      if (this.height > 2) {
        for (let column = 0; column < this.width; column++) {
          const target = this.#computeIndex(0, column);
          if (internal.includes(data[target])) {
            const id = data[target + roiMap.width];
            if (!internal.includes(id) && !this.boxIDs.includes(id)) {
              internal.push(id);
            }
          }
        }
      }
      const array = new Array(4);
      for (let column = 1; column < this.width - 1; column++) {
        for (let row = 1; row < this.height - 1; row++) {
          const target = this.#computeIndex(row, column);
          if (internal.includes(data[target])) {
            // We check if one of the neighbor is not yet in.
            array[0] = data[target - 1];
            array[1] = data[target + 1];
            array[2] = data[target - roiMap.width];
            array[3] = data[target + roiMap.width];
            for (let i = 0; i < 4; i++) {
              const id = array[i];
              if (!internal.includes(id) && !this.boxIDs.includes(id)) {
                internal.push(id);
              }
            }
          }
        }
      }
      return internal;
    });
  }
  /**
   * Returns an array of ROIs IDs that touch the current ROI.
   * @returns The array of Borders.
   */
  get externalBorders() {
    return this.#getComputed('externalBorders', () => {
      // Takes all the borders and removes the internal one ...
      const borders = this.borders;
      const externalBorders = [];
      const externalIDs = [];
      const internals = this.internalIDs;
      for (const border of borders) {
        if (!internals.includes(border.connectedID)) {
          const element = {
            connectedID: border.connectedID,
            length: border.length
          };
          externalIDs.push(element.connectedID);
          externalBorders.push(element);
        }
      }
      return externalBorders;
    });
  }
  /**
   * Calculates and caches the number of sides by which each pixel is touched externally.
   * @returns An object which tells how many pixels are exposed externally to how many sides.
   */
  get perimeterInfo() {
    return this.#getComputed('perimeterInfo', () => {
      const roiMap = this.map;
      const data = roiMap.data;
      let one = 0;
      let two = 0;
      let three = 0;
      let four = 0;
      const externalIDs = new Set(this.externalBorders.map(element => element.connectedID));
      for (let column = 0; column < this.width; column++) {
        for (let row = 0; row < this.height; row++) {
          const target = this.#computeIndex(row, column);
          if (data[target] === this.id) {
            let nbAround = 0;
            if (column === 0) {
              nbAround++;
            } else if (externalIDs.has(data[target - 1])) {
              nbAround++;
            }
            if (column === roiMap.width - 1) {
              nbAround++;
            } else if (externalIDs.has(data[target + 1])) {
              nbAround++;
            }
            if (row === 0) {
              nbAround++;
            } else if (externalIDs.has(data[target - roiMap.width])) {
              nbAround++;
            }
            if (row === roiMap.height - 1) {
              nbAround++;
            } else if (externalIDs.has(data[target + roiMap.width])) {
              nbAround++;
            }
            switch (nbAround) {
              case 1:
                one++;
                break;
              case 2:
                two++;
                break;
              case 3:
                three++;
                break;
              case 4:
                four++;
                break;
            }
          }
        }
      }
      return {
        one,
        two,
        three,
        four
      };
    });
  }
  /**
   * Perimeter of the ROI.
   * The perimeter is calculated using the sum of all the external borders of the ROI to which we subtract:
   * (2 - √2) * the number of pixels that have 2 external borders
   * 2 * (2 - √2) * the number of pixels that have 3 external borders
   * @returns Perimeter value in pixels.
   */
  get perimeter() {
    const info = this.perimeterInfo;
    const delta = 2 - Math.sqrt(2);
    return info.one + info.two * 2 + info.three * 3 + info.four * 4 - delta * (info.two + info.three * 2 + info.four);
  }
  /**
   * Computes ROI points relative to ROIs point of `origin`.
   * @returns Array of points with relative ROI coordinates.
   */
  get relativePoints() {
    return this.#getComputed(`relativePoints`, () => {
      const points = Array.from(this.points(false));
      return points;
    });
  }
  /**
   * Computes ROI points relative to Image's/Mask's point of `origin`.
   * @returns Array of points with absolute ROI coordinates.
   */
  get absolutePoints() {
    return this.#getComputed(`absolutePoints`, () => {
      const points = Array.from(this.points(true));
      return points;
    });
  }
  get boxIDs() {
    return this.#getComputed('boxIDs', () => {
      const surroundingIDs = new Set(); // Allows to get a unique list without indexOf.
      const roiMap = this.map;
      const data = roiMap.data;
      // We check the first line and the last line.
      for (const row of [0, this.height - 1]) {
        for (let column = 0; column < this.width; column++) {
          const target = this.#computeIndex(row, column);
          if (column - this.origin.column > 0 && data[target] === this.id && data[target - 1] !== this.id) {
            const value = data[target - 1];
            surroundingIDs.add(value);
          }
          if (roiMap.width - column - this.origin.column > 1 && data[target] === this.id && data[target + 1] !== this.id) {
            const value = data[target + 1];
            surroundingIDs.add(value);
          }
        }
      }
      // We check the first column and the last column.
      for (const column of [0, this.width - 1]) {
        for (let row = 0; row < this.height; row++) {
          const target = this.#computeIndex(row, column);
          if (row - this.origin.row > 0 && data[target] === this.id && data[target - roiMap.width] !== this.id) {
            const value = data[target - roiMap.width];
            surroundingIDs.add(value);
          }
          if (roiMap.height - row - this.origin.row > 1 && data[target] === this.id && data[target + roiMap.width] !== this.id) {
            const value = data[target + roiMap.width];
            surroundingIDs.add(value);
          }
        }
      }
      return Array.from(surroundingIDs); // The selection takes the whole rectangle.
    });
  }
  /**
   * Computes the diameter of a circle of equal projection area (EQPC).
   * It is a diameter of a circle that has the same surface as the ROI.
   * @returns `eqpc` value in pixels.
   */
  get eqpc() {
    return 2 * Math.sqrt(this.surface / Math.PI);
  }
  /**
   * Computes ellipse of ROI. It is the smallest ellipse that fits the ROI.
   * @returns Ellipse
   */
  get ellipse() {
    return this.#getComputed('ellipse', () => {
      return getEllipse(this);
    });
  }
  /**
   * Number of holes in the ROI and their total surface.
   * Used to calculate fillRatio.
   * @returns The surface of holes in ROI in pixels.
   */
  get holesInfo() {
    return this.#getComputed('holesInfo', () => {
      let surface = 0;
      const data = this.map.data;
      for (let column = 1; column < this.width - 1; column++) {
        for (let row = 1; row < this.height - 1; row++) {
          const target = this.#computeIndex(row, column);
          if (this.internalIDs.includes(data[target]) && data[target] !== this.id) {
            surface++;
          }
        }
      }
      return {
        number: this.internalIDs.length - 1,
        surface
      };
    });
  }
  /**
   * Calculates and caches border's length and their IDs.
   * @returns Borders' length and their IDs.
   */
  get borders() {
    return this.#getComputed('borders', () => {
      const roiMap = this.map;
      const data = roiMap.data;
      const surroudingIDs = new Set();
      const surroundingBorders = new Map();
      const visitedData = new Set();
      const dx = [1, 0, -1, 0];
      const dy = [0, 1, 0, -1];
      for (let column = this.origin.column; column <= this.origin.column + this.width; column++) {
        for (let row = this.origin.row; row <= this.origin.row + this.height; row++) {
          const target = column + row * roiMap.width;
          if (data[target] === this.id) {
            for (let dir = 0; dir < 4; dir++) {
              const newX = column + dx[dir];
              const newY = row + dy[dir];
              if (newX >= 0 && newY >= 0 && newX < roiMap.width && newY < roiMap.height) {
                const neighbour = newX + newY * roiMap.width;
                if (data[neighbour] !== this.id && !visitedData.has(neighbour)) {
                  visitedData.add(neighbour);
                  surroudingIDs.add(data[neighbour]);
                  let surroundingBorder = surroundingBorders.get(data[neighbour]);
                  if (!surroundingBorder) {
                    surroundingBorders.set(data[neighbour], 1);
                  } else {
                    surroundingBorders.set(data[neighbour], ++surroundingBorder);
                  }
                }
              }
            }
          }
        }
      }
      const id = Array.from(surroudingIDs);
      return id.map(id => {
        return {
          connectedID: id,
          length: surroundingBorders.get(id)
        };
      });
    });
  }
  /**
   * Computes fill ratio of the ROI. It is calculated by dividing ROI's actual surface over the surface combined with holes, to see how holes affect its surface.
   * @returns Fill ratio value.
   */
  get fillRatio() {
    return this.surface / (this.surface + this.holesInfo.surface);
  }
  /**
   * Computes sphericity of the ROI.
   * Sphericity is a measure of the degree to which a particle approximates the shape of a sphere, and is independent of its size. The value is always between 0 and 1. The less spheric the ROI is the smaller is the number.
   * @returns Sphericity value.
   */
  get sphericity() {
    return 2 * Math.sqrt(this.surface * Math.PI) / this.perimeter;
  }
  /**
   * Computes the surface of the ROI, including the surface of the holes.
   * @returns Surface including holes measured in pixels.
   */
  get filledSurface() {
    return this.surface + this.holesInfo.surface;
  }
  /**
   * The solidity describes the extent to which a shape is convex or concave.
   * The solidity of a completely convex shape is 1, the farther the it deviates from 1, the greater the extent of concavity in the shape of the ROI.
   * @returns Solidity value.
   */
  get solidity() {
    return this.surface / this.convexHull.surface;
  }
  //TODO Should be refactored to not need creating a new Mask.
  /**
   *Computes convex hull. It is the smallest convex set that contains it.
   * @see https://en.wikipedia.org/wiki/Convex_hull
   * @returns Convex hull.
   */
  get convexHull() {
    return this.#getComputed('convexHull', () => {
      return getConvexHull(this.getMask());
    });
  }
  /**
   * Computes the minimum bounding rectangle.
   * In digital image processing, the bounding box is merely the coordinates of the rectangular border that fully encloses a digital image when it is placed over a page, a canvas, a screen or other similar bidimensional background.
   * @returns The minimum bounding rectangle.
   */
  get mbr() {
    return this.#getComputed('mbr', () => {
      return getMbr(this.getMask());
    });
  }
  /*
  * Computes roundness of ROI.
  * Roundness is the measure of how closely the shape of an object approaches that of a mathematically perfect circle.
  (See slide 24 https://static.horiba.com/fileadmin/Horiba/Products/Scientific/Particle_Characterization/Webinars/Slides/TE011.pdf) */
  get roundness() {
    return 4 * this.surface / (Math.PI * this.feret.maxDiameter.length ** 2);
  }
  /**
   * This is not a diameter in its actual sense but the common basis of a group of diameters derived from the distance of two tangents to the contour of the particle in a well-defined orientation.
   * In simpler words, the method corresponds to the measurement by a slide gauge (slide gauge principle).
   * In general it is defined as the distance between two parallel tangents of the particle at an arbitrary angle. The minimum Feret diameter is often used as the diameter equivalent to a sieve analysis.
   * @returns The maximum and minimum Feret Diameters.
   */
  get feret() {
    return this.#getComputed('feret', () => {
      return getFeret(this.getMask());
    });
  }
  /**
   * A JSON object with all the data about ROI.
   * @returns All current ROI properties as one object.
   */
  toJSON() {
    return {
      id: this.id,
      origin: this.origin,
      height: this.height,
      width: this.width,
      surface: this.surface,
      eqpc: this.eqpc,
      ped: this.ped,
      feret: this.feret,
      fillRatio: this.fillRatio,
      sphericity: this.sphericity,
      roundness: this.roundness,
      solidity: this.solidity,
      perimeter: this.perimeter,
      convexHull: this.convexHull,
      mbr: this.mbr,
      filledSurface: this.filledSurface,
      centroid: this.centroid
    };
  }
  /**
   * Computes a center of mass of the current ROI.
   * @returns point
   */
  get centroid() {
    return this.#getComputed('centroid', () => {
      const roiMap = this.map;
      const data = roiMap.data;
      let sumColumn = 0;
      let sumRow = 0;
      for (let column = 0; column < this.width; column++) {
        for (let row = 0; row < this.height; row++) {
          const target = this.#computeIndex(row, column);
          if (data[target] === this.id) {
            sumColumn += column;
            sumRow += row;
          }
        }
      }
      return {
        column: sumColumn / this.surface + this.origin.column,
        row: sumRow / this.surface + this.origin.row
      };
    });
  }
  //  A helper function to cache already calculated properties.
  #getComputed(property, callback) {
    if (this.#computed[property] === undefined) {
      const result = callback();
      this.#computed[property] = result;
      return result;
    }
    return this.#computed[property];
  }
  //TODO Make this private.
  /**
   * Calculates the correct index on the map of ROI.
   * @param y - Map row
   * @param x - Map column
   * @returns Index within the ROI map.
   */
  #computeIndex(y, x) {
    const roiMap = this.map;
    return (y + this.origin.row) * roiMap.width + x + this.origin.column;
  }
  /**
   * Generator function to calculate point's coordinates.
   * @param absolute - controls whether coordinates should be relative to ROI's point of `origin` (relative), or relative to ROI's position on the Image/Mask (absolute).
   * @yields Coordinates of each point of ROI.
   */
  *points(absolute) {
    for (let row = 0; row < this.height; row++) {
      for (let column = 0; column < this.width; column++) {
        const target = (row + this.origin.row) * this.map.width + column + this.origin.column;
        if (this.map.data[target] === this.id) {
          if (absolute) {
            yield {
              column: this.origin.column + column,
              row: this.origin.row + row
            };
          } else {
            yield {
              column,
              row
            };
          }
        }
      }
    }
  }
}

/**
 * Generate an array of ROIs based on an ROI map manager.
 * @param roiMapManager - Roi map manager to use.
 */
function computeRois(roiMapManager) {
  const map = roiMapManager.getMap();
  const whites = new Array(map.nbPositive);
  const blacks = new Array(map.nbNegative);
  for (let i = 0; i < map.nbPositive; i++) {
    whites[i] = {
      minRow: map.height,
      minColumn: map.width,
      maxRow: -1,
      maxColumn: -1,
      surface: 0,
      id: i + 1
    };
  }
  for (let i = 0; i < map.nbNegative; i++) {
    blacks[i] = {
      borderLengths: [],
      borderIDs: [],
      minRow: map.height,
      minColumn: map.width,
      maxRow: -1,
      maxColumn: -1,
      surface: 0,
      id: -i - 1
    };
  }
  for (let row = 0; row < map.height; row++) {
    for (let column = 0; column < map.width; column++) {
      const currentIndex = roiMapManager.getMapValue(column, row);
      if (currentIndex === 0) {
        continue;
      }
      let currentRoi;
      if (currentIndex < 0) {
        currentRoi = blacks[-currentIndex - 1];
      } else {
        currentRoi = whites[currentIndex - 1];
      }
      currentRoi.surface++;
      if (row < currentRoi.minRow) {
        currentRoi.minRow = row;
      }
      if (row > currentRoi.maxRow) {
        currentRoi.maxRow = row;
      }
      if (column < currentRoi.minColumn) {
        currentRoi.minColumn = column;
      }
      if (column > currentRoi.maxColumn) {
        currentRoi.maxColumn = column;
      }
    }
  }
  roiMapManager.whiteRois = new Array(map.nbPositive);
  roiMapManager.blackRois = new Array(map.nbNegative);
  for (let i = 0; i < map.nbNegative; i++) {
    const width = blacks[i].maxColumn - blacks[i].minColumn + 1;
    const height = blacks[i].maxRow - blacks[i].minRow + 1;
    const origin = {
      row: blacks[i].minRow,
      column: blacks[i].minColumn
    };
    const id = blacks[i].id;
    const surface = blacks[i].surface;
    const blackRoi = new Roi(map, id, width, height, origin, surface);
    roiMapManager.blackRois[i] = blackRoi;
  }
  for (let i = 0; i < map.nbPositive; i++) {
    const width = whites[i].maxColumn - whites[i].minColumn + 1;
    const height = whites[i].maxRow - whites[i].minRow + 1;
    const origin = {
      row: whites[i].minRow,
      column: whites[i].minColumn
    };
    const id = whites[i].id;
    const surface = whites[i].surface;
    const whiteRoi = new Roi(map, id, width, height, origin, surface);
    roiMapManager.whiteRois[i] = whiteRoi;
  }
}

const RoiKind = {
  BLACK: 'black',
  WHITE: 'white',
  BW: 'bw'
};
/**
 * Return an array of ROIs matching the options.
 * @param roiMapManager - The ROI map manager containing the ROIs.
 * @param options - Get ROIs options.
 * @returns The array of ROIs.
 */
function getRois(roiMapManager, options = {}) {
  const {
    minSurface = 0,
    maxSurface = Number.MAX_SAFE_INTEGER,
    kind = 'white'
  } = options;
  if (roiMapManager.blackRois.length === 0 && roiMapManager.whiteRois.length === 0) {
    computeRois(roiMapManager);
  }
  const rois = M$2(kind).with('black', () => roiMapManager.blackRois).with('white', () => roiMapManager.whiteRois).with('bw', () => [...roiMapManager.whiteRois, ...roiMapManager.blackRois]).exhaustive();
  return rois.filter(roi => roi.surface >= minSurface && roi.surface <= maxSurface);
}

class RoiMapManager {
  map;
  whiteRois;
  blackRois;
  constructor(map) {
    this.map = map;
    this.whiteRois = [];
    this.blackRois = [];
  }
  /**
   * Return the ROI map of the RoiMapManager.
   * @returns - The ROI map.
   */
  getMap() {
    return this.map;
  }
  /**
   * Return the value at the given coordinates in an ROI map.
   * @param column - Column of the value.
   * @param row - Row of the value.
   * @returns The value at the given coordinates.
   */
  getMapValue(column, row) {
    return this.map.data[this.map.width * row + column];
  }
  /**
   * Returns the ROI map as a correct width and height matrix.
   * @returns The ROI map matrix.
   */
  getMapMatrix() {
    return Matrix$1.from1DArray(this.map.height, this.map.width, this.map.data).to2DArray();
  }
  getRois(options = {}) {
    return getRois(this, options);
  }
  getRoiById(roiID) {
    const rois = this.getRois({
      kind: 'bw'
    });
    const foundRoi = rois.find(roi => roi.id === roiID);
    if (!foundRoi) {
      throw new Error(`invalid ID: ${roiID}`);
    }
    return foundRoi;
  }
  static fromMask(mask, options = {}) {
    return fromMask(mask, options);
  }
}

/**
 * Extract the ROIs of an image.
 * @param mask - Mask to extract the ROIs from.
 * @param options - From mask options.
 * @returns The corresponding ROI manager.
 */
function fromMask(mask, options = {}) {
  const {
    allowCorners = false
  } = options;
  const MAX_TODO_ARRAY_FILTER = 65535; // 65535 should be enough for most of the cases
  const MAX_POSITIVE_ID = 2 ** 31 - 1;
  const MAX_NEGATIVE_ID = -2147483647;
  // based on a binary image we will create plenty of small images
  const data = new Int32Array(mask.size); // maxValue: maxPositiveId, minValue: maxNegativeId
  // split will always return an array of images
  let positiveId = 0;
  let negativeId = 0;
  const columnToProcess = new Uint16Array(MAX_TODO_ARRAY_FILTER + 1);
  const rowToProcess = new Uint16Array(MAX_TODO_ARRAY_FILTER + 1);
  for (let column = 0; column < mask.width; column++) {
    for (let row = 0; row < mask.height; row++) {
      if (data[row * mask.width + column] === 0) {
        // need to process the whole surface
        analyseSurface(column, row);
      }
    }
  }
  // x column
  // y row
  function analyseSurface(column, row) {
    let from = 0;
    let to = 0;
    const targetState = mask.getBit(column, row);
    const id = targetState ? ++positiveId : --negativeId;
    assert(positiveId <= MAX_POSITIVE_ID && negativeId >= MAX_NEGATIVE_ID, 'too many regions of interest');
    columnToProcess[0] = column;
    rowToProcess[0] = row;
    while (from <= to) {
      const currentColumn = columnToProcess[from & MAX_TODO_ARRAY_FILTER];
      const currentRow = rowToProcess[from & MAX_TODO_ARRAY_FILTER];
      data[currentRow * mask.width + currentColumn] = id;
      // need to check all around mask pixel
      if (currentColumn > 0 && data[currentRow * mask.width + currentColumn - 1] === 0 && mask.getBit(currentColumn - 1, currentRow) === targetState) {
        // LEFT
        to++;
        columnToProcess[to & MAX_TODO_ARRAY_FILTER] = currentColumn - 1;
        rowToProcess[to & MAX_TODO_ARRAY_FILTER] = currentRow;
        data[currentRow * mask.width + currentColumn - 1] = MAX_NEGATIVE_ID;
      }
      if (currentRow > 0 && data[(currentRow - 1) * mask.width + currentColumn] === 0 && mask.getBit(currentColumn, currentRow - 1) === targetState) {
        // TOP
        to++;
        columnToProcess[to & MAX_TODO_ARRAY_FILTER] = currentColumn;
        rowToProcess[to & MAX_TODO_ARRAY_FILTER] = currentRow - 1;
        data[(currentRow - 1) * mask.width + currentColumn] = MAX_NEGATIVE_ID;
      }
      if (currentColumn < mask.width - 1 && data[currentRow * mask.width + currentColumn + 1] === 0 && mask.getBit(currentColumn + 1, currentRow) === targetState) {
        // RIGHT
        to++;
        columnToProcess[to & MAX_TODO_ARRAY_FILTER] = currentColumn + 1;
        rowToProcess[to & MAX_TODO_ARRAY_FILTER] = currentRow;
        data[currentRow * mask.width + currentColumn + 1] = MAX_NEGATIVE_ID;
      }
      if (currentRow < mask.height - 1 && data[(currentRow + 1) * mask.width + currentColumn] === 0 && mask.getBit(currentColumn, currentRow + 1) === targetState) {
        // BOTTOM
        to++;
        columnToProcess[to & MAX_TODO_ARRAY_FILTER] = currentColumn;
        rowToProcess[to & MAX_TODO_ARRAY_FILTER] = currentRow + 1;
        data[(currentRow + 1) * mask.width + currentColumn] = MAX_NEGATIVE_ID;
      }
      if (allowCorners) {
        if (currentColumn > 0 && currentRow > 0 && data[(currentRow - 1) * mask.width + currentColumn - 1] === 0 && mask.getBit(currentColumn - 1, currentRow - 1) === targetState) {
          // TOP LEFT
          to++;
          columnToProcess[to & MAX_TODO_ARRAY_FILTER] = currentColumn - 1;
          rowToProcess[to & MAX_TODO_ARRAY_FILTER] = currentRow - 1;
          data[(currentRow - 1) * mask.width + currentColumn - 1] = MAX_NEGATIVE_ID;
        }
        if (currentColumn < mask.width - 1 && currentRow > 0 && data[(currentRow - 1) * mask.width + currentColumn + 1] === 0 && mask.getBit(currentColumn + 1, currentRow - 1) === targetState) {
          // TOP RIGHT
          to++;
          columnToProcess[to & MAX_TODO_ARRAY_FILTER] = currentColumn + 1;
          rowToProcess[to & MAX_TODO_ARRAY_FILTER] = currentRow - 1;
          data[(currentRow - 1) * mask.width + currentColumn + 1] = MAX_NEGATIVE_ID;
        }
        if (currentColumn > 0 && currentRow < mask.height - 1 && data[(currentRow + 1) * mask.width + currentColumn - 1] === 0 && mask.getBit(currentColumn - 1, currentRow + 1) === targetState) {
          // BOTTOM LEFT
          to++;
          columnToProcess[to & MAX_TODO_ARRAY_FILTER] = currentColumn - 1;
          rowToProcess[to & MAX_TODO_ARRAY_FILTER] = currentRow + 1;
          data[(currentRow + 1) * mask.width + currentColumn - 1] = MAX_NEGATIVE_ID;
        }
        if (currentColumn < mask.width - 1 && currentRow < mask.height - 1 && data[(currentRow + 1) * mask.width + currentColumn + 1] === 0 && mask.getBit(currentColumn + 1, currentRow + 1) === targetState) {
          // BOTTOM RIGHT
          to++;
          columnToProcess[to & MAX_TODO_ARRAY_FILTER] = currentColumn + 1;
          rowToProcess[to & MAX_TODO_ARRAY_FILTER] = currentRow + 1;
          data[(currentRow + 1) * mask.width + currentColumn + 1] = MAX_NEGATIVE_ID;
        }
      }
      from++;
      assert(to - from <= MAX_TODO_ARRAY_FILTER, 'fromMask can not finish, the array to manage internal data is not big enough.' + 'You could improve mask by changing MAX_ARRAY');
    }
  }
  return new RoiMapManager({
    width: mask.width,
    height: mask.height,
    data,
    nbNegative: Math.abs(negativeId),
    nbPositive: positiveId
  });
}

function commonjsRequire(path) {
	throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');
}

var priorityQueue = {exports: {}};

(function (module, exports$1) {
  (function (f) {
    {
      module.exports = f();
    }
  })(function () {
    return function e(t, n, r) {
      function s(o, u) {
        if (!n[o]) {
          if (!t[o]) {
            var a = typeof commonjsRequire == "function" && commonjsRequire;
            if (!u && a) return a(o, true);
            if (i) return i(o, true);
            var f = new Error("Cannot find module '" + o + "'");
            throw f.code = "MODULE_NOT_FOUND", f;
          }
          var l = n[o] = {
            exports: {}
          };
          t[o][0].call(l.exports, function (e) {
            var n = t[o][1][e];
            return s(n ? n : e);
          }, l, l.exports, e, t, n, r);
        }
        return n[o].exports;
      }
      var i = typeof commonjsRequire == "function" && commonjsRequire;
      for (var o = 0; o < r.length; o++) s(r[o]);
      return s;
    }({
      1: [function (_dereq_, module, exports$1) {
        var AbstractPriorityQueue,
          ArrayStrategy,
          BHeapStrategy,
          BinaryHeapStrategy,
          PriorityQueue,
          extend = function (child, parent) {
            for (var key in parent) {
              if (hasProp.call(parent, key)) child[key] = parent[key];
            }
            function ctor() {
              this.constructor = child;
            }
            ctor.prototype = parent.prototype;
            child.prototype = new ctor();
            child.__super__ = parent.prototype;
            return child;
          },
          hasProp = {}.hasOwnProperty;
        AbstractPriorityQueue = _dereq_('./PriorityQueue/AbstractPriorityQueue');
        ArrayStrategy = _dereq_('./PriorityQueue/ArrayStrategy');
        BinaryHeapStrategy = _dereq_('./PriorityQueue/BinaryHeapStrategy');
        BHeapStrategy = _dereq_('./PriorityQueue/BHeapStrategy');
        PriorityQueue = function (superClass) {
          extend(PriorityQueue, superClass);
          function PriorityQueue(options) {
            options || (options = {});
            options.strategy || (options.strategy = BinaryHeapStrategy);
            options.comparator || (options.comparator = function (a, b) {
              return (a || 0) - (b || 0);
            });
            PriorityQueue.__super__.constructor.call(this, options);
          }
          return PriorityQueue;
        }(AbstractPriorityQueue);
        PriorityQueue.ArrayStrategy = ArrayStrategy;
        PriorityQueue.BinaryHeapStrategy = BinaryHeapStrategy;
        PriorityQueue.BHeapStrategy = BHeapStrategy;
        module.exports = PriorityQueue;
      }, {
        "./PriorityQueue/AbstractPriorityQueue": 2,
        "./PriorityQueue/ArrayStrategy": 3,
        "./PriorityQueue/BHeapStrategy": 4,
        "./PriorityQueue/BinaryHeapStrategy": 5
      }],
      2: [function (_dereq_, module, exports$1) {
        module.exports = function () {
          function AbstractPriorityQueue(options) {
            var ref;
            if ((options != null ? options.strategy : void 0) == null) {
              throw 'Must pass options.strategy, a strategy';
            }
            if ((options != null ? options.comparator : void 0) == null) {
              throw 'Must pass options.comparator, a comparator';
            }
            this.priv = new options.strategy(options);
            this.length = (options != null ? (ref = options.initialValues) != null ? ref.length : void 0 : void 0) || 0;
          }
          AbstractPriorityQueue.prototype.queue = function (value) {
            this.length++;
            this.priv.queue(value);
            return void 0;
          };
          AbstractPriorityQueue.prototype.dequeue = function (value) {
            if (!this.length) {
              throw 'Empty queue';
            }
            this.length--;
            return this.priv.dequeue();
          };
          AbstractPriorityQueue.prototype.peek = function (value) {
            if (!this.length) {
              throw 'Empty queue';
            }
            return this.priv.peek();
          };
          AbstractPriorityQueue.prototype.clear = function () {
            this.length = 0;
            return this.priv.clear();
          };
          return AbstractPriorityQueue;
        }();
      }, {}],
      3: [function (_dereq_, module, exports$1) {
        var binarySearchForIndexReversed;
        binarySearchForIndexReversed = function (array, value, comparator) {
          var high, low, mid;
          low = 0;
          high = array.length;
          while (low < high) {
            mid = low + high >>> 1;
            if (comparator(array[mid], value) >= 0) {
              low = mid + 1;
            } else {
              high = mid;
            }
          }
          return low;
        };
        module.exports = function () {
          function ArrayStrategy(options) {
            var ref;
            this.options = options;
            this.comparator = this.options.comparator;
            this.data = ((ref = this.options.initialValues) != null ? ref.slice(0) : void 0) || [];
            this.data.sort(this.comparator).reverse();
          }
          ArrayStrategy.prototype.queue = function (value) {
            var pos;
            pos = binarySearchForIndexReversed(this.data, value, this.comparator);
            this.data.splice(pos, 0, value);
            return void 0;
          };
          ArrayStrategy.prototype.dequeue = function () {
            return this.data.pop();
          };
          ArrayStrategy.prototype.peek = function () {
            return this.data[this.data.length - 1];
          };
          ArrayStrategy.prototype.clear = function () {
            this.data.length = 0;
            return void 0;
          };
          return ArrayStrategy;
        }();
      }, {}],
      4: [function (_dereq_, module, exports$1) {
        module.exports = function () {
          function BHeapStrategy(options) {
            var arr, j, k, len, ref, ref1, shift, value;
            this.comparator = (options != null ? options.comparator : void 0) || function (a, b) {
              return a - b;
            };
            this.pageSize = (options != null ? options.pageSize : void 0) || 512;
            this.length = 0;
            shift = 0;
            while (1 << shift < this.pageSize) {
              shift += 1;
            }
            if (1 << shift !== this.pageSize) {
              throw 'pageSize must be a power of two';
            }
            this._shift = shift;
            this._emptyMemoryPageTemplate = arr = [];
            for (j = 0, ref = this.pageSize; 0 <= ref ? j < ref : j > ref; 0 <= ref ? ++j : --j) {
              arr.push(null);
            }
            this._memory = [];
            this._mask = this.pageSize - 1;
            if (options.initialValues) {
              ref1 = options.initialValues;
              for (k = 0, len = ref1.length; k < len; k++) {
                value = ref1[k];
                this.queue(value);
              }
            }
          }
          BHeapStrategy.prototype.queue = function (value) {
            this.length += 1;
            this._write(this.length, value);
            this._bubbleUp(this.length, value);
            return void 0;
          };
          BHeapStrategy.prototype.dequeue = function () {
            var ret, val;
            ret = this._read(1);
            val = this._read(this.length);
            this.length -= 1;
            if (this.length > 0) {
              this._write(1, val);
              this._bubbleDown(1, val);
            }
            return ret;
          };
          BHeapStrategy.prototype.peek = function () {
            return this._read(1);
          };
          BHeapStrategy.prototype.clear = function () {
            this.length = 0;
            this._memory.length = 0;
            return void 0;
          };
          BHeapStrategy.prototype._write = function (index, value) {
            var page;
            page = index >> this._shift;
            while (page >= this._memory.length) {
              this._memory.push(this._emptyMemoryPageTemplate.slice(0));
            }
            return this._memory[page][index & this._mask] = value;
          };
          BHeapStrategy.prototype._read = function (index) {
            return this._memory[index >> this._shift][index & this._mask];
          };
          BHeapStrategy.prototype._bubbleUp = function (index, value) {
            var compare, indexInPage, parentIndex, parentValue;
            compare = this.comparator;
            while (index > 1) {
              indexInPage = index & this._mask;
              if (index < this.pageSize || indexInPage > 3) {
                parentIndex = index & ~this._mask | indexInPage >> 1;
              } else if (indexInPage < 2) {
                parentIndex = index - this.pageSize >> this._shift;
                parentIndex += parentIndex & ~(this._mask >> 1);
                parentIndex |= this.pageSize >> 1;
              } else {
                parentIndex = index - 2;
              }
              parentValue = this._read(parentIndex);
              if (compare(parentValue, value) < 0) {
                break;
              }
              this._write(parentIndex, value);
              this._write(index, parentValue);
              index = parentIndex;
            }
            return void 0;
          };
          BHeapStrategy.prototype._bubbleDown = function (index, value) {
            var childIndex1, childIndex2, childValue1, childValue2, compare;
            compare = this.comparator;
            while (index < this.length) {
              if (index > this._mask && !(index & this._mask - 1)) {
                childIndex1 = childIndex2 = index + 2;
              } else if (index & this.pageSize >> 1) {
                childIndex1 = (index & ~this._mask) >> 1;
                childIndex1 |= index & this._mask >> 1;
                childIndex1 = childIndex1 + 1 << this._shift;
                childIndex2 = childIndex1 + 1;
              } else {
                childIndex1 = index + (index & this._mask);
                childIndex2 = childIndex1 + 1;
              }
              if (childIndex1 !== childIndex2 && childIndex2 <= this.length) {
                childValue1 = this._read(childIndex1);
                childValue2 = this._read(childIndex2);
                if (compare(childValue1, value) < 0 && compare(childValue1, childValue2) <= 0) {
                  this._write(childIndex1, value);
                  this._write(index, childValue1);
                  index = childIndex1;
                } else if (compare(childValue2, value) < 0) {
                  this._write(childIndex2, value);
                  this._write(index, childValue2);
                  index = childIndex2;
                } else {
                  break;
                }
              } else if (childIndex1 <= this.length) {
                childValue1 = this._read(childIndex1);
                if (compare(childValue1, value) < 0) {
                  this._write(childIndex1, value);
                  this._write(index, childValue1);
                  index = childIndex1;
                } else {
                  break;
                }
              } else {
                break;
              }
            }
            return void 0;
          };
          return BHeapStrategy;
        }();
      }, {}],
      5: [function (_dereq_, module, exports$1) {
        module.exports = function () {
          function BinaryHeapStrategy(options) {
            var ref;
            this.comparator = (options != null ? options.comparator : void 0) || function (a, b) {
              return a - b;
            };
            this.length = 0;
            this.data = ((ref = options.initialValues) != null ? ref.slice(0) : void 0) || [];
            this._heapify();
          }
          BinaryHeapStrategy.prototype._heapify = function () {
            var i, j, ref;
            if (this.data.length > 0) {
              for (i = j = 1, ref = this.data.length; 1 <= ref ? j < ref : j > ref; i = 1 <= ref ? ++j : --j) {
                this._bubbleUp(i);
              }
            }
            return void 0;
          };
          BinaryHeapStrategy.prototype.queue = function (value) {
            this.data.push(value);
            this._bubbleUp(this.data.length - 1);
            return void 0;
          };
          BinaryHeapStrategy.prototype.dequeue = function () {
            var last, ret;
            ret = this.data[0];
            last = this.data.pop();
            if (this.data.length > 0) {
              this.data[0] = last;
              this._bubbleDown(0);
            }
            return ret;
          };
          BinaryHeapStrategy.prototype.peek = function () {
            return this.data[0];
          };
          BinaryHeapStrategy.prototype.clear = function () {
            this.length = 0;
            this.data.length = 0;
            return void 0;
          };
          BinaryHeapStrategy.prototype._bubbleUp = function (pos) {
            var parent, x;
            while (pos > 0) {
              parent = pos - 1 >>> 1;
              if (this.comparator(this.data[pos], this.data[parent]) < 0) {
                x = this.data[parent];
                this.data[parent] = this.data[pos];
                this.data[pos] = x;
                pos = parent;
              } else {
                break;
              }
            }
            return void 0;
          };
          BinaryHeapStrategy.prototype._bubbleDown = function (pos) {
            var last, left, minIndex, right, x;
            last = this.data.length - 1;
            while (true) {
              left = (pos << 1) + 1;
              right = left + 1;
              minIndex = pos;
              if (left <= last && this.comparator(this.data[left], this.data[minIndex]) < 0) {
                minIndex = left;
              }
              if (right <= last && this.comparator(this.data[right], this.data[minIndex]) < 0) {
                minIndex = right;
              }
              if (minIndex !== pos) {
                x = this.data[minIndex];
                this.data[minIndex] = this.data[pos];
                this.data[pos] = x;
                pos = minIndex;
              } else {
                break;
              }
            }
            return void 0;
          };
          return BinaryHeapStrategy;
        }();
      }, {}]
    }, {}, [1])(1);
  });
})(priorityQueue);
var priorityQueueExports = priorityQueue.exports;
var PriorityQueue = /*@__PURE__*/getDefaultExportFromCjs(priorityQueueExports);

/**
 * This method allows to create a ROIMap using the water shed algorithm. By default this algorithm
 * will fill the holes and therefore the lowest value of the image (black zones).
 * If no points are given, the function will look for all the minimal points.
 * If no mask is given the algorithm will completely fill the image.
 * Please take care about the value that has be in the mask ! In order to be coherent with the expected mask,
 * meaning that if it is a dark zone, the mask will be dark the normal behavior to fill a zone
 * is that the mask pixel is clear (value of 0) !
 * If you are looking for 'maxima' the image must be inverted before applying the algorithm
 * @param image - Image that the filter will be applied to.
 * @param options - WaterShedOptions
 * @returns RoiMapManager
 */
function waterShed(image, options) {
  let {
    points
  } = options;
  const {
    mask,
    threshold = 1
  } = options;
  const currentImage = image;
  checkProcessable$1(image, {
    bitDepth: [8, 16],
    components: 1
  });
  const fillMaxValue = threshold * image.maxValue;
  // WaterShed is done from points in the image. We can either specify those points in options,
  // or it is gonna take the minimum locals of the image by default.
  if (!points) {
    points = getExtrema(image, {
      kind: 'minimum',
      mask
    });
  }
  const maskExpectedValue = 0;
  const data = new Int32Array(currentImage.size);
  const width = currentImage.width;
  const height = currentImage.height;
  const toProcess = new PriorityQueue({
    comparator: (a, b) => a.intensity - b.intensity,
    strategy: PriorityQueue.BinaryHeapStrategy
  });
  for (let i = 0; i < points.length; i++) {
    const index = points[i].column + points[i].row * width;
    data[index] = -i - 1;
    const intensity = currentImage.getValueByIndex(index, 0);
    if (intensity <= fillMaxValue) {
      toProcess.queue({
        column: points[i].column,
        row: points[i].row,
        intensity
      });
    }
  }
  const dxs = [1, 0, -1, 0, 1, 1, -1, -1];
  const dys = [0, 1, 0, -1, 1, -1, 1, -1];
  // Then we iterate through each points
  while (toProcess.length > 0) {
    const currentPoint = toProcess.dequeue();
    const currentValueIndex = currentPoint.column + currentPoint.row * width;
    for (let dir = 0; dir < 4; dir++) {
      const newX = currentPoint.column + dxs[dir];
      const newY = currentPoint.row + dys[dir];
      if (newX >= 0 && newY >= 0 && newX < width && newY < height) {
        const currentNeighbourIndex = newX + newY * width;
        if (!mask || mask.getBitByIndex(currentNeighbourIndex) === maskExpectedValue) {
          const intensity = currentImage.getValueByIndex(currentNeighbourIndex, 0);
          if (intensity <= fillMaxValue && data[currentNeighbourIndex] === 0) {
            data[currentNeighbourIndex] = data[currentValueIndex];
            toProcess.queue({
              column: currentPoint.column + dxs[dir],
              row: currentPoint.row + dys[dir],
              intensity
            });
          }
        }
      }
    }
  }
  const nbNegative = points.length;
  const nbPositive = 0;
  return new RoiMapManager({
    data,
    nbPositive,
    nbNegative,
    width: image.width,
    height: image.height
  });
}

/**
 * This method checks if a process can be applied on the stack.
 * @param stack - Stack to verify.
 * @param options - Check processable options.
 */
function checkProcessable(stack, options = {}) {
  const {
    sameDimensions = false,
    alpha
  } = options;
  let {
    bitDepth
  } = options;
  if (sameDimensions) {
    const width = stack.getImage(0).width;
    const height = stack.getImage(0).height;
    for (let i = 1; i < stack.size; i++) {
      const currentImage = stack.getImage(i);
      if (currentImage.width !== width || currentImage.height !== height) {
        throw new RangeError(`images must all have same dimensions to apply this algorithm`);
      }
    }
  }
  if (alpha !== undefined && alpha !== stack.alpha) {
    throw new RangeError(`stack images ${alpha ? 'should' : 'should not'} have an alpha channel to apply this algorithm`);
  }
  if (bitDepth) {
    if (!Array.isArray(bitDepth)) {
      bitDepth = [bitDepth];
    }
    if (!bitDepth.includes(stack.bitDepth)) {
      throw new RangeError(`image bitDepth must be ${format(bitDepth)} to apply this algorithm`);
    }
  }
}

/**
 * Get the sum of all the histograms of the stack's images. If no channel is specified in the options, the images must be GREY.
 * @param stack - Stack to process.
 * @param options - Histogram options.
 * @returns The histogram of the stack.
 */
function histogram(stack, options) {
  checkProcessable(stack, {
    bitDepth: [8, 16]
  });
  const {
    slots = 2 ** stack.bitDepth,
    channel = 0
  } = options;
  const result = new Uint32Array(slots);
  for (let i = 0; i < stack.size; i++) {
    const image = stack.getImage(i);
    const histogram = image.histogram({
      channel,
      slots
    });
    for (const [index, value] of histogram.entries()) {
      result[index] += value;
    }
  }
  return result;
}

/**
 *  Returns a new image with the maximum values of each pixel from the stack.
 * @param stack - Stack to process.
 * @returns The maximum image.
 */
function maxImage(stack) {
  checkProcessable(stack, {
    sameDimensions: true
  });
  const newImage = Image.createFrom(stack.getImage(0));
  const nbChannels = newImage.channels;
  for (let i = 0; i < stack.size; i++) {
    for (let j = 0; j < newImage.size; j++) {
      for (let channel = 0; channel < nbChannels; channel++) {
        newImage.setValueByIndex(j, channel, Math.max(newImage.getValueByIndex(j, channel), stack.getValueByIndex(i, j, channel)));
      }
    }
  }
  return newImage;
}

/**
 *  Returns a new image with the average values of each pixel of the images of the stack.
 * @param stack - Stack to process.
 * @returns The mean image.
 */
function meanImage(stack) {
  checkProcessable(stack, {
    sameDimensions: true,
    bitDepth: [8, 16]
  });
  const image = stack.getImage(0);
  const dataSize = image.size * stack.channels;
  const sum = new Uint32Array(dataSize).fill(0);
  for (let i = 0; i < stack.size; i++) {
    for (let j = 0; j < image.size; j++) {
      for (let channel = 0; channel < stack.channels; channel++) {
        sum[j * stack.channels + channel] += stack.getValueByIndex(i, j, channel);
      }
    }
  }
  const meanImage = Image.createFrom(image);
  for (let i = 0; i < image.size; i++) {
    for (let channel = 0; channel < stack.channels; channel++) {
      const index = i * stack.channels + channel;
      meanImage.setValueByIndex(i, channel, sum[index] / stack.size);
    }
  }
  return meanImage;
}

// @ts-expect-error: median-quisckselect has no types
/**
 *  Returns a new image with the median values of each pixel of the images of the stack.
 * @param stack - Stack to process.
 * @returns The median image.
 */
function medianImage(stack) {
  checkProcessable(stack, {
    sameDimensions: true,
    bitDepth: [8, 16]
  });
  const image = stack.getImage(0);
  const result = Image.createFrom(image);
  for (let j = 0; j < image.size; j++) {
    for (let channel = 0; channel < stack.channels; channel++) {
      const currentValues = new Array(stack.size);
      for (let i = 0; i < stack.size; i++) {
        currentValues[i] = stack.getValueByIndex(i, j, channel);
      }
      result.setValueByIndex(j, channel, quickMedian(currentValues));
    }
  }
  return result;
}

/**
 * Decodes APNG image into a Stack
 * @param data - APNG data.
 * @returns stack of frames.
 */
function decodeStackFromApng(data) {
  const decodedApng = decodeApng(data);
  const images = [];
  let colorModel;
  switch (decodedApng.channels) {
    case 1:
      if (decodedApng.palette) {
        colorModel = decodedApng.palette[0].length === 3 ? 'RGB' : 'RGBA';
      } else {
        colorModel = 'GREY';
      }
      break;
    case 2:
      colorModel = 'GREYA';
      break;
    case 3:
      colorModel = 'RGB';
      break;
    default:
      colorModel = 'RGBA';
      break;
  }
  if (decodedApng.palette) {
    for (const image of decodedApng.frames) {
      images.push(new Image(decodedApng.width, decodedApng.height, {
        data: convertIndexedData(image.data, decodedApng.palette),
        colorModel
      }));
    }
  } else {
    for (const image of decodedApng.frames) {
      images.push(new Image(decodedApng.width, decodedApng.height, {
        data: image.data,
        colorModel
      }));
    }
  }
  const stack = new Stack(images);
  return stack;
}
function convertIndexedData(data, palette) {
  const result = new Uint8Array(data.length * palette[0].length);
  for (let i = 0; i < data.length; i++) {
    for (let channel = 0; channel < palette[0].length; channel++) {
      result[i * palette[0].length + channel] = palette[data[i]][channel];
    }
  }
  return result;
}

/**
 * Decode a TIFF and create a stack of images.
 * @param buffer - The data to decode.
 * @returns The stack of images.
 */
function decodeStackFromTiff(buffer) {
  const decoded = decodeTIFF(buffer);
  const images = [];
  for (const IFD of decoded) {
    images.push(getImageFromIFD(IFD));
  }
  return new Stack(images);
}

/**
 * Decode input data and create stack. Data format is automatically detected.
 * Possible formats: tiff.
 * @param data - Data to decode.
 * @returns The decoded image.
 */
function decodeStack(data) {
  const typedArray = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
  const type = imageType(typedArray);
  return M$2(type).with({
    mime: 'image/tiff'
  }, () => decodeStackFromTiff(typedArray)).with({
    mime: 'image/png'
  }, () => decodeStackFromApng(typedArray)).otherwise(() => {
    throw new RangeError(`invalid data format: ${type?.mime}`);
  });
}

/**
 *  Returns a new image with the minimum values of each pixel from the stack.
 * @param stack - Stack to process.
 * @returns The minimum image.
 */
function minImage(stack) {
  checkProcessable(stack, {
    sameDimensions: true
  });
  const newImage = Image.createFrom(stack.getImage(0));
  newImage.fill(newImage.maxValue);
  const nbChannels = newImage.channels;
  for (let i = 0; i < stack.size; i++) {
    for (let j = 0; j < newImage.size; j++) {
      for (let channel = 0; channel < nbChannels; channel++) {
        newImage.setValueByIndex(j, channel, Math.min(newImage.getValueByIndex(j, channel), stack.getValueByIndex(i, j, channel)));
      }
    }
  }
  return newImage;
}

/**
 *  Returns a new 16 bits depth image with the sum of each pixel of the images of the stack.
 * @param stack - Stack to process.
 * @returns The sum image.
 */
function sum(stack) {
  checkProcessable(stack, {
    sameDimensions: true,
    bitDepth: 8
  });
  // Because 255*257 = 2**16 - 1
  if (stack.size > 257) {
    throw new Error('Maximal valid stack size is 257');
  }
  const image = stack.getImage(0);
  const dataSize = image.size * stack.channels;
  const sum = new Uint16Array(dataSize).fill(0);
  for (let i = 0; i < stack.size; i++) {
    for (let j = 0; j < image.size; j++) {
      for (let channel = 0; channel < stack.channels; channel++) {
        sum[j * stack.channels + channel] += stack.getValueByIndex(i, j, channel);
      }
    }
  }
  return new Image(image.width, image.height, {
    data: sum,
    colorModel: stack.colorModel,
    bitDepth: 16
  });
}

/**
 * Verify all images of array have the same bit depth and color model.
 * @param images - Images to process
 */
function checkImagesValid(images) {
  const colorModel = images[0].colorModel;
  const bitDepth = images[0].bitDepth;
  for (const image of images) {
    if (image.colorModel !== colorModel || image.bitDepth !== bitDepth) {
      throw new RangeError(`images must all have the same bit depth and color model`);
    }
  }
}
/**
 * Checks if all the images of an array are the same dimensions.
 * @param images - Images array.
 * @returns `true` if all images have the same dimensions.
 */
function verifySameDimensions(images) {
  const width = images[0].width;
  const height = images[0].height;
  for (const image of images) {
    if (image.width !== width || image.height !== height) {
      return false;
    }
  }
  return true;
}

class Stack {
  /**
   * The array of images.
   */
  images;
  /**
   * The stack size.
   */
  size;
  /**
   * Do the images have an alpha channel?
   */
  alpha;
  /**
   * The color model of the images.
   */
  colorModel;
  /**
   * The bit depth of the images.
   */
  bitDepth;
  /**
   * Whether all the images of the stack have the same dimensions.
   */
  sameDimensions;
  /**
   * The number of channels of the images.
   */
  channels;
  /**
   * Create a new stack from an array of images.
   * The images must have the same bit depth and color model.
   * @param images - Array of images from which to create the stack.
   */
  constructor(images) {
    checkImagesValid(images);
    this.images = images;
    this.size = images.length;
    this.alpha = images[0].alpha;
    this.colorModel = images[0].colorModel;
    this.channels = images[0].channels;
    this.bitDepth = images[0].bitDepth;
    this.sameDimensions = verifySameDimensions(images);
  }
  *[Symbol.iterator]() {
    for (const image of this.images) {
      yield image;
    }
  }
  /**
   * Clone a stack. The images are a copy of the original images.
   * @returns A new stack with the same images.
   */
  clone() {
    return new Stack(this.images.map(image => image.clone()));
  }
  /**
   * Get the images of the stack. Mainly for debugging purposes.
   * @returns The images.
   */
  getImages() {
    return this.images;
  }
  /**
   * Get the image at the given index.
   * @param index - The index of the image.
   * @returns The image.
   */
  getImage(index) {
    return this.images[index];
  }
  /**
   * Get a value from an image of the stack.
   * @param stackIndex - Index of the image in the stack.
   * @param row - Row index of the pixel.
   * @param column - Column index of the pixel.
   * @param channel - The channel to retrieve.
   * @returns The value at the given position.
   */
  getValue(stackIndex, row, column, channel) {
    return this.images[stackIndex].getValue(row, column, channel);
  }
  /**
   * Get a value from an image of the stack. Specify the pixel position using its index.
   * @param stackIndex - Index of the image in the stack.
   * @param index - The index of the pixel.
   * @param channel - The channel to retrieve.
   * @returns The value at the given position.
   */
  getValueByIndex(stackIndex, index, channel) {
    return this.images[stackIndex].getValueByIndex(index, channel);
  }
  /**
   * Return the image containing the minimum values of all the images in the stack for
   * each pixel. All the images must have the same dimensions.
   * @returns The minimum image.
   */
  minImage() {
    return minImage(this);
  }
  /**
   * Return the image containing the maximum values of all the images in the stack for
   * each pixel. All the images must have the same dimensions.
   * @returns The maximum image.
   */
  maxImage() {
    return maxImage(this);
  }
  /**
   * Return the image containing the median values of all the images in the stack for
   * each pixel. All the images must have the same dimensions.
   * @returns The median image.
   */
  medianImage() {
    return medianImage(this);
  }
  /**
   * Return the image containing the average values of all the images in the stack for
   * each pixel. All the images must have the same dimensions.
   * @returns The mean image.
   */
  meanImage() {
    return meanImage(this);
  }
  /**
   * Return a 16 bits depth image containing the sum values of all the images in the stack for
   * each pixel.
   * @returns The sum image.
   */
  sum() {
    return sum(this);
  }
  /**
   * Get the sum of all the histograms of the stack's images. If no channel is specified in the options, the images must be GREY.
   * @param options - Histogram options.
   * @returns The histogram of the stack.
   */
  histogram(options = {}) {
    return histogram(this, options);
  }
  /**
   * Align all the images of the stack on the image at the given index.
   * @param refIndex - The index of the reference image.
   */
  // public alignImages(refIndex: number): Stack {}
  /**
   * Map a function on all the images of the stack.
   * @param callback - Function to apply on each image.
   * @returns New stack with the modified images.
   */
  map(callback) {
    return new Stack(this.images.map(callback));
  }
  /**
   * Filter the images in the stack.
   * @param callback - Function to decide which images to keep.
   * @returns New filtered stack.
   */
  filter(callback) {
    return new Stack(this.images.filter(callback));
  }
}

const channelLabels = {
  GREY: ['Grey'],
  GREYA: ['Grey', 'Alpha'],
  RGB: ['Red', 'Green', 'Blue'],
  RGBA: ['Red', 'Green', 'Blue', 'Alpha'],
  BINARY: ['Mask']
};

/**
 * Draws text on an image.
 * @param image - Image to write text on.
 * @param text - Text to write on the image.
 * @param options - Out Options
 * @returns Image with drawn text.
 */
function drawText(image, text, options) {
  if (Array.isArray(text) && text.length === 0) {
    throw new Error('At least one text element must be provided');
  }
  const newImage = getOutputImage(image, options, {
    clone: true
  });
  const defaultFont = options?.font ?? '12px Helvetica';
  const defaultColor = options?.fontColor ?? [255, 255, 255, 255];
  const ctx = getCanvasContext(image.width, image.height);
  if (!Array.isArray(text)) {
    drawTextElement(image, ctx, text, defaultFont, defaultColor);
  } else {
    for (const label of text) {
      drawTextElement(image, ctx, label, defaultFont, defaultColor);
    }
  }
  layerCanvas(newImage.getRawImage().data, ctx.getImageData(0, 0, image.width, image.height).data, image.channels, image.bitDepth);
  return newImage;
}
function drawTextElement(image, ctx, text, defaultFont, defaultColor) {
  ctx.font = text.font ?? defaultFont;
  const fontColor = text.fontColor ?? defaultColor;
  validateValues(fontColor, image);
  const alpha = fontColor[3] ? fontColor[3] / 255 : 1;
  const normalizedColor = [fontColor[0] ?? 0, fontColor[1] ?? 0, fontColor[2] ?? 0, alpha];
  ctx.fillStyle = `rgba(${normalizedColor.join(',')})`;
  ctx.fillText(String(text.content), text.position.column, text.position.row);
}
/**
 * Draws labels on the image data from canvas.
 * @param imageData - Image data to draw text on.
 * @param canvasData - Canvas data to draw on the image.
 * @param numberOfChannels - Number of channels of the initial image.
 * @param bitDepth - Bit depth of the initial image.
 */
function layerCanvas(imageData, canvasData, numberOfChannels, bitDepth) {
  const config = CHANNEL_CONFIGS[numberOfChannels] || CHANNEL_CONFIGS[1];
  const pixelCount = canvasData.length >>> 2;
  const bitShift = bitDepth - 8;
  let imageIndex = 0;
  let canvasIndex = 0;
  for (let pixel = 0; pixel < pixelCount; pixel++) {
    const canvasAlpha = canvasData[canvasIndex + 3] / 255;
    // Skip transparent canvas pixels completely
    if (canvasAlpha === 0) {
      imageIndex += numberOfChannels;
      canvasIndex += 4;
      continue;
    }
    const invAlpha = 1 - canvasAlpha;
    for (const channel of config.channelOffsets) {
      const targetIndex = imageIndex + channel;
      imageData[targetIndex] = Math.round(canvasData[canvasIndex + channel] * canvasAlpha + imageData[targetIndex] * invAlpha) << bitShift;
    }
    if (config.hasAlpha) {
      const alphaIndex = imageIndex + config.alphaOffset;
      const imageAlpha = (imageData[alphaIndex] >>> bitShift) / 255;
      const newAlpha = canvasAlpha + imageAlpha * (1 - canvasAlpha);
      imageData[alphaIndex] = Math.round(newAlpha * 255) << bitShift;
    }
    imageIndex += numberOfChannels;
    canvasIndex += 4;
  }
}
const CHANNEL_CONFIGS = {
  // GREY
  1: {
    channelOffsets: [0],
    hasAlpha: false,
    alphaOffset: undefined
  },
  // GREYA
  2: {
    channelOffsets: [0],
    hasAlpha: true,
    alphaOffset: 1
  },
  3: {
    // RGB
    channelOffsets: [0, 1, 2],
    hasAlpha: false,
    alphaOffset: undefined
  },
  4: {
    // RGBA
    channelOffsets: [0, 1, 2],
    hasAlpha: true,
    alphaOffset: 3
  }
};

export { BorderType, DerivativeFilter, GreyAlgorithm, Image, ImageColorModel, ImageCoordinates, ImageFormat, InterpolationType, Mask, Montage, MontageDisposition, Roi, RoiKind, RoiMapManager, RoisColorMode, Stack, ThresholdAlgorithm, add, alignMinDifference, and, blur, bottomHat, bruteForceOneMatch, cannyEdgeDetector, channelLabels, clearBorder, close, colorModels, colorRois, computeConvolutionValue, computeMse, computePsnr, computeRmse, computeRois, computeThreshold, convertBinaryToGrey, convertBinaryToRgb, convertBitDepth, convertColor, copyAlpha, copyTo, correctBackground, correctColor, crop, cropAlpha, cropRectangle, crosscheck, decode, decodeJpeg, decodePng, decodeStack, decodeTiff, defaultPng, derivativeFilter, dilate, directConvolution, divide, drawCircleOnImage, drawKeypoints, drawLineOnImage, drawLineOnMask, drawMarker, drawMarkers, drawMatches, drawPoints, drawPolygonOnImage, drawPolygonOnMask, drawPolylineOnImage, drawPolylineOnMask, drawRectangle, drawText, encode, encodeDataURL, encodeJpeg, encodePng, erode, extendBorders, extract, fetchURL, flip, floodFill, fromMask, gaussianBlur, getAffineTransform, getBestKeypointsInRadius, getBorderPoints, getBriefDescriptors, getCrosscheckMatches, getDirection, getExtrema, getFastKeypoints, getHarrisScore, getImageFromIFD, getIntensityCentroid, getMask, getOrientedFastKeypoints, getPerspectiveWarp, getRegressionVariables, getRois, getShiTomasiScore, gradientFilter, grey, histogram$1 as histogram, hypotenuse, increaseContrast, invert, level, mean, median, medianFilter, merge, morphologicalGradient, multiply, open, or, order4Points, overlapImages, paintMaskOnImage, paintMaskOnMask, pixelate, rawDirectConvolution, read, readCanvas, readImg, readSync, removeClosePoints, resize, rotate, separableConvolution, solidFill, split, subtract, threshold, topHat, transform, transformRotate, variance, waterShed, write, writeCanvas, writeSync };
//# sourceMappingURL=image-js.esm.js.map
