Skip to content

mubaidr/contours.ts

Repository files navigation

Contours.ts

Extract contours & shapes from an image, for browsers and node.js.

NPM

CI codecov codebeat badge

All Contributors

Features

Extract Contours

Approximate Contours to Common Shapes (Triangle, Rectangle, Square, Circle)

How to use

Install

using pckage manager:

npm i contours.ts

Or

add to your webpage:

<script src="unpkg.com/contours.ts"></script>

Or

download manually:

Contours.ts

Examples

Input Type

ContourFinder expects image data (multi-channel image data is suported) in following format:

/*
const imageData: {
  data: number[] | Uint8ClampedArray
  width: number
  height: number
} = {
  data: [0,0,0],
  width: 1,
  height: 1
}
*/

Get Contours

import { ContourFinder } from 'contours.ts'
const { contours } = new ContourFinder(imageData, {
  blur: true, // blurs the image data
  threshold: 85, // threshold image data
})

console.log(contours)

/*
logs:
[
  [{x: 0, y: 0}, {x: 1, y: 0}], // contour
  [{x: 0, y: 0}, {x: 1, y: 1}, {x: 2, y: 2}, {x: 3, y: 3}] // another contour
]
*/

Simplify Contours

import { ContourFinder } from 'contours.ts'
// simplify contours using Ramer–Douglas–Peucker algorithm
const { contours } = new ContourFinder(imageData).simplify(epsilon)

console.log(contours)

/*
logs:
[
  [{x: 0, y: 0}, {x: 1, y: 0}], // contour
  [{x: 0, y: 0}, {x: 3, y: 3}] // another contour
]
*/

Approximate Shapes

import { ContourFinder } from 'contours.ts'
// Or approximate contours to shapes
const { contours, shapeCollection } = new ContourFinder(imageData).approximate()

console.log(shapeCollection)

/*
logs:
[
  {
    points: [[{x: 0, y: 0}]],
    lines: [[{x: 0, y: 0}, {x: 3, y: 3}]],
    triangles: [],
    squares: [
      [{ x: 0, y: 0 },
      { x: 5, y: 0 },
      { x: 5, y: 5 },
      { x: 0, y: 5 },]
    ],
    recangles: [],
    circles: [],
    polygons: [],
  }
]
*/

Contributions

Contirbutions are welcome, code is heavily commented and tests are defined using jest

License

Distributed under the MIT License. See LICENSE for more information.

Contact

Muhammad Ubaid Raza - @mubaidr - mubaidr@gmail.com

Acknowledgements

This project is heavily inspired by the these:

Contributors ✨

Thanks goes to these wonderful people (emoji key):


Ben Foxall

💻

This project follows the all-contributors specification. Contributions of any kind welcome!

About

Extract shapes & contours in an image, for browsers and node.js.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published