triangle

package module
v1.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 19, 2022 License: MIT Imports: 10 Imported by: 5

README

build Go Reference license release homebrew

▲ Triangle is a tool for generating triangulated image using delaunay triangulation. It takes a source image and converts it to an abstract image composed of tiles of triangles.

Sample image

The process
  • First the image is blured out to smoth out the sharp pixel edges. The more blured an image is the more diffused the generated output will be.
  • Second the resulted image is converted to grayscale mode.
  • Then a sobel filter operator is applied on the grayscaled image to obtain the image edges. An optional threshold value is applied to filter out the representative pixels of the resulted image.
  • Lastly the delaunay algorithm is applied on the pixels obtained from the previous step.
blur = tri.Stackblur(img, uint32(width), uint32(height), uint32(*blurRadius))
gray = tri.Grayscale(blur)
sobel = tri.SobelFilter(gray, float64(*sobelThreshold))
points = tri.GetEdgePoints(sobel, *pointsThreshold, *maxPoints)

triangles = delaunay.Init(width, height).Insert(points).GetTriangles()
Features
  • Can process recursively whole directories and subdirectories concurrently.
  • Supports various image types.
  • There is no need to specify the file type, the CLI tool can recognize automatically the input and output file type.
  • Can accept image URL as parameter for the -in flag.
  • Possibility to save the generated image as an SVG file.
  • The generated SVG file can be accessed from the Web browser directly.
  • Clean and intuitive API. The API not only that accepts image files but can also work with image data. This means that the Draw method can be invoked even on data streams. Check this demo for reference.
  • Support for pipe names (possibility to pipe in and pipe out the source and destination image).
TODO
  • Standalone and native GUI application

Head over to this subtopic to get a better understanding of the supported features.

Installation and usage

$ go get -u -f github.com/esimov/triangle/cmd/triangle
$ go install

You can also download the binary file from the releases folder.

MacOS (Brew) install

The library can be installed via Homebrew too.

$ brew install triangle

Supported commands

$ triangle --help

The following flags are supported:

Flag Default Description
in n/a Source image
out n/a Destination image
blur 4 Blur radius
pts 2500 Maximum number of points
noise 0 Noise factor
th 20 Points threshold
sobel 10 Sobel filter threshold
solid false Use solid stroke color (yes/no)
wf 0 Wireframe mode (0: without stroke, 1: with stroke, 2: stroke only)
stroke 1 Stroke width
gray false Output in grayscale mode
web false Open the SVG file in the web browser
bg ' ' Background color (specified as hex value)
c system spec. Number of files to process concurrently

Key features

Process multiple images from a directory concurrently

The CLI tool also let you process multiple images from a directory concurrently. You only need to provide the source and the destination folder by using the -in and -out flags.

$ triangle -in <input_folder> -out <output-folder>

You can provide also an image file URL for the -in flag.

$ triangle -in <image_url> -out <output-folder>
Pipe names

The CLI tool accepts also pipe names, which means you can use stdin and stdout without the need of providing a value for the -in and -out flag directly since these defaults to -. For this reason it's possible to use curl for example for downloading an image from the internet and invoke the triangulation process over it directly without the need of getting the image first and calling ▲ Triangle afterwards.

Here are some examples using pipe names:

$ curl -s <image_url> | triangle > out.jpg
$ cat input/source.jpg | triangle > out.jpg
$ triangle -in input/source.jpg > out.jpg
$ cat input/source.jpg | triangle -out out.jpg
$ triangle -out out.jpg < input/source.jpg
Background color

You can specify a background color in case of transparent background images (.png) by using the -bg flag. This flag accepts a hexadecimal string value. For example setting the flag to -bg=#ffffff00 will set the alpha channel of the resulted image transparent.

Output as image or SVG

By default the output is saved to an image file, but you can export the resulted vertices even to an SVG file. The CLI tool can recognize the output type directly from the file extension. This is a handy addition for those who wish to generate large images without guality loss.

$ triangle -in samples/input.jpg -out output.svg

Using with -web flag you can access the generated svg file directly on the web browser.

$ triangle -in samples/input.jpg -out output.svg -web=true
Supported output types

The following output file types are supported: .jpg, .jpeg, .png, .bmp, .svg.

Tweaks

Setting a lower points threshold, the resulted image will be more like a cubic painting. You can even add a noise factor, generating a more artistic, grainy image.

Here are some examples you can experiment with:

$ triangle -in samples/input.jpg -out output.png -wf=0 -pts=3500 -stroke=2 -blur=2
$ triangle -in samples/input.jpg -out output.png -wf=2 -pts=5500 -stroke=1 -blur=10

Examples

Sample_0 Sample_1 Sample_11 Sample_8

License

Copyright © 2018 Endre Simo

This project is under the MIT License. See the LICENSE file for the full license text.

Documentation

Overview

Package triangle is an image processing library which converts images to computer generated art using delaunay triangulation.

The package provides a command line utility supporting various customization options. Check the supported commands by typing:

$ triangle --help

Using Go interfaces the API can expose the result either as raster or vector type.

Example to generate triangulated image and output the result as raster type:

package main

import (
	"fmt"
	"github.com/esimov/triangle"
)

func main() {
	p := &triangle.Processor{
		// Initialize struct variables
	}

	img := &triangle.Image{*p}
	_, _, err = img.Draw(file, fq, func() {})
	if err != nil {
		fmt.Printf("Error on triangulation process: %s", err.Error())
	}
}

Example to generate triangulated image and output the result as SVG:

package main

import (
	"fmt"
	"github.com/esimov/triangle"
)

func main() {
	p := &triangle.Processor{
		// Initialize struct variables
	}

	svg := &triangle.SVG{
		Title:         "Delaunay image triangulator",
		Lines:         []triangle.Line{},
		Description:   "Convert images to computer generated art using delaunay triangulation.",
		StrokeWidth:   p.StrokeWidth,
		StrokeLineCap: "round", //butt, round, square
		Processor:     *p,
	}
	_, _, err = svg.Draw(file, fq, func() {
		// Call the closure function
	})
	if err != nil {
		fmt.Printf("Error on triangulation process: %s", err.Error())
	}
}

Index

Constants

View Source
const (
	// WithoutWireframe - generates triangles without stroke
	WithoutWireframe = iota
	// WithWireframe - generates triangles with stroke
	WithWireframe
	// WireframeOnly - generates triangles only with wireframe
	WireframeOnly
)

Variables

This section is empty.

Functions

func Grayscale

func Grayscale(src *image.NRGBA) *image.NRGBA

Grayscale converts the image to grayscale mode.

func ImgToNRGBA added in v1.3.0

func ImgToNRGBA(img image.Image) *image.NRGBA

ImgToNRGBA converts any image type to *image.NRGBA with min-point at (0, 0).

func Max added in v1.3.0

func Max[T constraints.Ordered](values ...T) T

Max returns the biggest value between two numbers.

func Min added in v1.3.0

func Min[T constraints.Ordered](values ...T) T

Min returns the smallest value between two numbers.

func Noise

func Noise(amount int, pxl image.Image, w, h int) *image.NRGBA64

Noise applies a noise factor, like Adobe's grain filter in order to create a despeckle like image.

func SobelFilter

func SobelFilter(img *image.NRGBA, threshold float64) *image.NRGBA

SobelFilter uses the sobel threshold operator to detect the image edges. See https://en.wikipedia.org/wiki/Sobel_operator

func StackBlur added in v1.0.2

func StackBlur(img *image.NRGBA, radius uint32) *image.NRGBA

StackBlur applies a blur filter to the provided image. The radius defines the bluring average.

Types

type Delaunay

type Delaunay struct {
	// contains filtered or unexported fields
}

Delaunay defines the main components of the triangulation.

func (*Delaunay) GetTriangles

func (d *Delaunay) GetTriangles() []Triangle

GetTriangles returns the generated triangles.

func (*Delaunay) Init

func (d *Delaunay) Init(width, height int) *Delaunay

Init initialize the Delaunay structure.

func (*Delaunay) Insert

func (d *Delaunay) Insert(points []Point) *Delaunay

Insert will insert new triangles into the triangles slice.

type Drawer added in v1.0.2

type Drawer interface {
	Draw(image.Image, Processor, Fn) (image.Image, []Triangle, []Point, error)
}

Drawer interface defines the Draw method. This interface should be implemented by every struct which declares a Draw method. By using this method the image can be triangulated as raster type or SVG.

type Fn added in v1.2.4

type Fn func()

Fn is a callback function used on SVG generation.

type Image added in v1.0.2

type Image struct {
	Processor
}

Image extends the Processor struct.

func (*Image) DecodeImage added in v1.3.0

func (im *Image) DecodeImage(input io.Reader) (image.Image, error)

DecodeImage calls the decodeImage utility function which decodes an image file type to the generic image.Image type.

func (*Image) Draw added in v1.0.2

func (im *Image) Draw(src image.Image, proc Processor, fn Fn) (image.Image, []Triangle, []Point, error)

Draw triangulates the source image and outputs the result to a raster type. It returns the number of triangles generated, the number of points and the error in case exists.

type Line added in v1.0.2

type Line struct {
	P0          Node
	P1          Node
	P2          Node
	P3          Node
	FillColor   color.RGBA
	StrokeColor color.RGBA
}

Line defines the SVG line parameters.

type Node

type Node struct {
	X, Y float64
}

Node defines a struct having as components the node X and Y coordinate position.

type Point

type Point struct {
	X, Y float64
}

Point defines a struct having as components the point X and Y coordinate position.

type Processor added in v1.0.1

type Processor struct {
	// BlurRadius defines the intensity of the applied blur filter.
	BlurRadius int
	// SobelThreshold defines the threshold intesinty of the sobel edge detector.
	// By increasing this value the contours of the detected objects will be more evident.
	SobelThreshold int
	// PointsThreshold defines the threshold of computed pixel value below a point is generated.
	PointsThreshold int
	// PointRate defines the point rate by which the generated polygons will be multiplied by.
	// The lower this value the bigger the polygons will be.
	PointRate float64
	// BlurFactor defines the factor used to populate the matrix table in conjunction with the convolution filter operator.
	// This value will affect the outcome of the final triangulated image.
	BlurFactor int
	// EdgeFactor defines the factor used to populate the matrix table in conjunction with the convolution filter operator.
	// The bigger this value is the more cubic alike will be the final image.
	EdgeFactor int
	// MaxPoints holds the maximum number of generated points the vertices/triangles will be generated from.
	MaxPoints int
	// Wireframe defines the visual appearence of the generated vertices (WithoutWireframe|WithWireframe|WireframeOnly).
	Wireframe int
	// Noise defines the intensity of the noise factor used to give a noisy, despeckle like touch of the final image.
	Noise int
	// StrokeWidth defines the contour width in case of using WithWireframe | WireframeOnly mode.
	StrokeWidth float64
	// IsStrokeSolid - when this is set as true, the applied stroke color will be black.
	IsStrokeSolid bool
	// Grayscale will generate the output in grayscale mode.
	Grayscale bool
	// OutputToSVG saves the generated triangles to an SVG file.
	OutputToSVG bool
	// ShowInBrowser shows the generated svg file in the browser.
	ShowInBrowser bool
	// BgColor defines the background color in case of using transparent images as source files.
	// By default the background is transparent, but it can be changed using a hexadecimal format, like #fff or #ffff00.
	BgColor string
}

Processor encompasses all of the currently supported processing options.

func (*Processor) GetPoints added in v1.3.0

func (p *Processor) GetPoints(img *image.NRGBA, threshold, maxPoints int) []Point

GetPoints retrieves the triangle points after the Sobel threshold has been applied.

type SVG added in v1.0.2

type SVG struct {
	Width         int
	Height        int
	Title         string
	Lines         []Line
	Color         color.RGBA
	Description   string
	StrokeLineCap string
	StrokeWidth   float64
	Processor
}

SVG extends the Processor struct with the SVG parameters.

func (*SVG) DecodeImage added in v1.3.0

func (svg *SVG) DecodeImage(input io.Reader) (image.Image, error)

DecodeImage calls the decodeImage utility function which decodes an image file type to the generic image.Image type.

func (*SVG) Draw added in v1.0.2

func (svg *SVG) Draw(src image.Image, proc Processor, fn Fn) (image.Image, []Triangle, []Point, error)

Draw triangulates the source image and outputs the result to an SVG file. It has the same method signature as the rester Draw method, only that accepts a callback function for further processing, like opening the generated SVG file in the web browser. It returns the number of triangles generated, the number of points and the error in case exists.

type Triangle

type Triangle struct {
	Nodes []Node
	// contains filtered or unexported fields
}

Triangle defines the basic components of a triangle, having as elements the nodes, its edges and the circumcircle which describes the triangle circumference.

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL