User:Watchduck/bin2svg

From Wikiversity
Jump to navigation Jump to search
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]

>>> 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.

Bin2svg example.svg

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]

See also: http://pastebin.com/y8rY5Vj4

Matlab code[edit]

Derived functions for integer matrices[edit]

Binary strings created with mat2svg(Matrix,4,5,2)
Binary matrices below are created with mat2svg_dual(Matrix,4,3)
Binary strings created with mat2svg(Matrix,16,8,2)
Binary matrices below are created with mat2svg_dual(Matrix,16,2)