User:Watchduck/bin2svg

From Wikiversity
Jump to navigation Jump to search
Hadamard code
Sierpinski triangle drawn with bin2svg — The red squares form one contiguous area with only one edge, so the path contains only one M.

bin2svg is a small program that takes a binary matrix and returns the corresponding SVG path of the area covered by ones.

It was initially written in Matlab and later translated to Python. The code is shown below.

Files created with this program are marked with {{Created with bin2svg}} and sorted into the hidden category Created with bin2svg.

Example

[edit | edit source]
>>> from numpy import array
>>> from bin2svg import bin2svg
>>> mat = array([[0, 0, 0, 1], [1, 1, 1, 0], [1, 0, 1, 0], [1, 1, 1, 0]])
>>> mat
array([[0, 0, 0, 1],
       [1, 1, 1, 0],
       [1, 0, 1, 0],
       [1, 1, 1, 0]])
>>> bin2svg(mat)
'M3,0h1v1h-1M0,1h3v3h-3M1,2v1h1v-1'


If the function gets the binary matrix it will create the intermediate matrix which shows that there are three cycles of corners:
Two on the outside of an area of ones (with clockwise numbers 1...4) and one hole (with anticlockwise numbers 5...8). (The 24 is a 2 and a 4 in the same place.)
The outside cycles give the paths M3,0 h1 v1 h-1 and M0,1 h3 v3 h-3, and the hole gives M1,2 v1 h1 v-1.
So the output of the function is M3,0h1v1h-1M0,1h3v3h-3M1,2v1h1v-1.

In the following SVG code the result produces the image shown on the right:

<?xml version = "1.0" encoding = "UTF-8" ?>
<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="-.5 -.5 5 5">
    <path fill="#fff" d="m0,0h4v4H0"/> <!-- white background -->
    <path fill="#f00" d="M3,0h1v1h-1M0,1h3v3h-3M1,2v1h1v-1"/> <!-- red entries -->
    <g stroke="#000">
        <path stroke-width="4" stroke-dasharray=".05,.95" d="M0,2h5M2,0v5"/> <!-- 0.5px black lines -->
        <rect stroke-width=".1" fill="none" x="0" y="0" width="4" height="4"/> <!-- 1px black square -->
    </g>
</svg>


Python code

[edit | edit source]
See also: http://pastebin.com/y8rY5Vj4

Matlab code

[edit | edit source]

Examples

[edit | edit source]
This Inkscape file was filled with a dark gray and two red bin2svg paths. (The latter by merging matrices, e.g the four 16×16 into one 16×73 with gaps of width 3 between them.)
This file shows bin2svg paths of four matrices, which are red, green, blue and gray — the latter in the same position as the blue one. (There are also two columns and two rows scaled to be thin hints next to the matrices.)
three paths to highlight sets of entries in a matrix
simple file with four areas and corresponding grids