Coder Social home page Coder Social logo

esimov / triangle Goto Github PK

View Code? Open in Web Editor NEW
2.0K 28.0 110.0 18.08 MB

Convert images to computer generated art using delaunay triangulation.

License: MIT License

Go 97.11% Makefile 0.29% Shell 2.59%
delaunay image-processing generative generative-art pixel triangulation triangle golang

triangle's Introduction

Triangle logo

build Go Report Card 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.
  • A convolution filter operator is applied over the image data in order to adjust its final aspect prior running the delaunay triangulation process.
  • Lastly the delaunay algorithm is applied on the pixels obtained from the previous step.

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 install github.com/esimov/triangle/v2/cmd/[email protected] 

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

API usage

proc := &triangle.Processor{
	MaxPoints:  2500,
	BlurRadius: 2,
	PointRate:  0.75,
	BlurFactor: 1,
	EdgeFactor: 6,
}

img := &triangle.Image{
	Processor: *proc,
}

input, err := os.Open("input.jpg")
if err != nil {
	log.Fatalf("error opening the source file: %v", err)
}

// decode image
src, err := img.DecodeImage(input)
if err != nil {
	log.Fatalf("error decoding the image: %v", err)
}
res, _, _, err := img.Draw(src, *proc, func() {})
if err != nil {
	log.Fatalf("error generating the triangles: %v", err)
}

output, err := os.Create("output.png")
if err != nil {
	log.Fatalf("error opening the destination file: %v", err)
}

// encode image
png.Encode(output, res)

Supported commands

$ triangle --help

The following flags are supported:

Flag Default Description
in n/a Source image
out n/a Destination image
bl 2 Blur radius
nf 0 Noise factor
bf 1 Blur factor
ef 6 Edge factor
pr 0.075 Point rate
pth 10 Points threshold
pts 2500 Maximum number of points
so 10 Sobel filter threshold
sl false Use solid stroke color (yes/no)
wf 0 Wireframe mode (0: without stroke, 1: with stroke, 2: stroke only)
st 1 Stroke width
gr false Output in grayscale mode
web false Open the SVG file in the web browser
bg ' ' Background color (specified as hex value)
cw 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 -st=2 -bl=2
$ triangle -in samples/input.jpg -out output.png -wf=2 -pts=5500 -st=1 -bl=10

Examples

Triangle1 Triangle2 Triangle3

License

Copyright © 2018 Endre Simo

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

triangle's People

Contributors

0xflotus avatar chenrui333 avatar esimov avatar imikod avatar plutov avatar whereswaldon avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

triangle's Issues

Apple Silicon Support?

I have a project which uses glumpy and am trying to get it running natively on my new MacBook. Is there any plan to compile this package for ARM?

Python 3.8.13 | packaged by conda-forge | (default, Mar 25 2022, 06:05:16) 
[Clang 12.0.1 ] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import triangle
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/patrickbryant/miniforge3/envs/py38/lib/python3.8/site-packages/triangle/__init__.py", line 13, in <module>
    from .tri import (
  File "/Users/patrickbryant/miniforge3/envs/py38/lib/python3.8/site-packages/triangle/tri.py", line 1, in <module>
    from .core import triang
ImportError: dlopen(/Users/patrickbryant/miniforge3/envs/py38/lib/python3.8/site-packages/triangle/core.cpython-38-darwin.so, 0x0002): tried: '/core.cpython-38-darwin.so' (no such file), '/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/lib//core.cpython-38-darwin.so' (no such file), '/Users/patrickbryant/miniforge3/envs/py38/lib/python3.8/site-packages/triangle/core.cpython-38-darwin.so' (mach-o file, but is an incompatible architecture (have 'x86_64', need 'arm64e'))

Overlapping/excessive triangles

So, whenever I try to triangulate an image, there is a problem with some random triangles that are drawn above the necessary ones. Sometimes they are a something like a line, and sometimes they are gigantic. I tried to change value of all of the parameters/flags but no luck.
In the attached files is the source and generated images with flags: -pts 5000 -blur 1.

173
173
img31
img31

Transparent images

Is there a way to make images with transparent elements or a transparent background?

SVG output

First of all thanks for this awesome library!

Is there a reason I am getting the following message while .svg is included in the readme?

File type not supported: .svg

Cannot find go install

I am a total noob with go, and so I followed your direction to install triangle, but there is no "go install" anywhere...

My directory:
screen shot 2018-02-05 at 9 05 38 pm

"Help" sometimes skip descriptions

In 1.3.0 --help option randomly skips descriptions
Screenshots made in Windows Terminal app (from Microsoft Store) with Windows Powershell command line
image
image
image

doesn't seem to work

	file, err := os.Open("face.jpg")
	if err != nil {
		log.Fatalf("Error opening the file: %v", err)
	}
	defer file.Close()

	// File to write to
	nf, err := os.Create("trig.jpeg")
	if err != nil {
		log.Fatalf("Error writing the file: %s", err)
	}

	// Run Triangle algorithm
	p := &triangle.Processor{
		// Initialize struct variables
	}
	img := &triangle.Image{*p}
	_, _,_, err = img.Draw(file, nf, func() {})
	if err != nil {
		log.Fatalf("Error creating triangles: %s", err)
	}

I keep getting error: Error creating triangles: image: unknown format

Backward compatible?

It's the new API backward compatible?

Also, if I have a 2x2 image and I set maxpoints to 1, what does that mean?

Parameter details

It would be good know in more detail what these parameters do:

type Processor struct {
	BlurRadius     
	SobelThreshold
	PointsThreshold
	MaxPoints
	Wireframe     
	Noise          
	StrokeWidth     
	IsStrokeSolid   
	Grayscale     
	OutputToSVG     
	ShowInBrowser 
	BgColor      
}

I'm trying to adjust the MaxPoints based on the area of the detected face: https://github.com/rocketlaunchr/facemask
so that the face's beauty is still apparent without giving away the person's identity.

It would be good if MaxPoints was 0 and BlurRadius was provided, that the algorithm blurs but does not perform the triangulation process.

Panic for image with specific dimension

Version: 1.0.3
When a 1px height (e.g. 1x1, 10x1, 100x1) image is given as an input, triangle fails to run.
(FYI a 1px width (e.g. 1x10, 1x100) image is successfully processed)

% triangle -in test.jpg -out out.jpg
Generating triangulated image... -panic: runtime error: index out of range

goroutine 1 [running]:
github.com/esimov/triangle.StackBlur(0xc0000aa6c0, 0xc000000004, 0xc0000aa6c0)
	/private/tmp/triangle-20190310-60366-glg0jh/triangle-1.0.3/src/github.com/esimov/triangle/stackblur.go:259 +0xf29
github.com/esimov/triangle.(*Image).Draw(0xc0000ddbe8, 0x140d280, 0xc0000b4070, 0x140d280, 0xc000010010, 0x1431be0, 0x0, 0x1, 0x1c08400, 0x20300000000000, ...)
	/private/tmp/triangle-20190310-60366-glg0jh/triangle-1.0.3/src/github.com/esimov/triangle/process.go:102 +0x3ad
main.main()
	/private/tmp/triangle-20190310-60366-glg0jh/triangle-1.0.3/src/github.com/esimov/triangle/cmd/triangle/main.go:178 +0xd98

Failing to process such an image is fine, but is it possible to give a more informative message (like "the input is too small")?

can't load package: package

issue installation:

go install
can't load package: package .: no Go files in /home/roboto

go install triangle

can't load package: package triangle: cannot find package "triangle" in any of:
        /usr/lib/go/src/triangle (from $GOROOT)
        /home/roboto/go/src/triangle (from $GOPATH)

go env

GOARCH="amd64"
GOBIN="/home/roboto/go/bin"
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOOS="linux"
GOPATH="/home/roboto/go"
GORACE=""
GOROOT="/usr/lib/go"
GOTOOLDIR="/usr/lib/go/pkg/tool/linux_amd64"
GCCGO="gccgo"
CC="gcc"
GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0 -fdebug-prefix-map=/tmp/go-build567200773=/tmp/go-build -gno-record-gcc-switches"
CXX="g++"
CGO_ENABLED="1"
CGO_CFLAGS="-g -O2"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-g -O2"
CGO_FFLAGS="-g -O2"
CGO_LDFLAGS="-g -O2"
PKG_CONFIG="pkg-config"

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.