numpngw


Namenumpngw JSON
Version 0.1.3 PyPI version JSON
download
home_pagehttps://github.com/WarrenWeckesser/numpngw
SummaryWrite numpy array(s) to a PNG or animated PNG file.
upload_time2023-10-07 17:31:53
maintainer
docs_urlNone
authorWarren Weckesser
requires_python
licenseBSD
keywords numpy png matplotlib animation
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            numpngw
=======

This python package (availabe on PyPI at https://pypi.org/project/numpngw/)
defines the function ``write_png`` that writes a numpy array to a PNG file,
and the function ``write_apng`` that writes a sequence of arrays to an
animated PNG (APNG) file.  Also included is the class ``AnimatedPNGWriter``
that can be used to save a Matplotlib animation as an animated PNG file;
see Example 8 for an example.

Capabilities of ``write_png`` include:

* creation of 8-bit and 16-bit RGB files;
* creation of 1-bit, 2-bit, 4-bit, 8-bit and 16-bit grayscale files;
* creation of RGB and grayscale images with an alpha channel;
* setting a transparent color;
* automatic creation of a palette for an indexed PNG file;
* inclusion of ``tEXt``, ``tIME``, ``bKGD``, ``pHYs``, ``gAMA``, ``cHRM``
  and ``iCCP`` chunks.

The package is written in pure python.  The only external dependencies
are numpy and setuptools.

The package has a suite of unit tests, but it should still be considered
prototype-quality software.  There may be backwards-incompatible API changes
between releases.

This software is released under the BSD 2-clause license.

For packages with more features (including functions for *reading* PNG files),
take a look at:

* pypng (https://pypi.python.org/pypi/pypng) or
* imageio (https://pypi.python.org/pypi/imageio).

The following examples show some PNG and animated PNG files created with
numpy and numpngw.  To see the animations in Examples 5 - 8, you must view
this file with a browser that supports animated PNG files.  Most web browsers
support animated PNG; see https://caniuse.com/apng for support status.

Example 1
---------

The following script creates this PNG file, an 8-bit RGB image.

.. image:: https://raw.githubusercontent.com/WarrenWeckesser/numpngw/master/examples/example1.png
   :alt: Example 1
   :align: center

The script::

    import numpy as np
    from numpngw import write_png


    # Example 1
    #
    # Create an 8-bit RGB image.

    img = np.zeros((80, 128, 3), dtype=np.uint8)

    grad = np.linspace(0, 255, img.shape[1])

    img[:16, :, :] = 127
    img[16:32, :, 0] = grad
    img[32:48, :, 1] = grad[::-1]
    img[48:64, :, 2] = grad
    img[64:, :, :] = 127

    write_png('example1.png', img)


Example 2
---------

The following script creates this PNG file, a 1-bit grayscale image.

.. image:: https://raw.githubusercontent.com/WarrenWeckesser/numpngw/master/examples/example2.png
   :alt: Example 2
   :align: center

The script::

    import numpy as np
    from numpngw import write_png

    # Example 2
    #
    # Create a 1-bit grayscale image.

    mask = np.zeros((48, 48), dtype=np.uint8)
    mask[:2, :] = 1
    mask[:, -2:] = 1
    mask[4:6, :-4] = 1
    mask[4:, -6:-4] = 1
    mask[-16:, :16] = 1
    mask[-32:-16, 16:32] = 1

    write_png('example2.png', mask, bitdepth=1)


Example 3
---------

The following script creates this PNG file, a 16-bit RGB file in which
the value (0, 0, 0) is transparent.  It might not be obvious, but the
two squares are transparent.

.. image:: https://raw.githubusercontent.com/WarrenWeckesser/numpngw/master/examples/example3.png
   :alt: Example 3
   :align: center

The script::

    import numpy as np
    from numpngw import write_png

    # Example 3
    #
    # Create a 16-bit RGB image, with (0, 0, 0) indicating a transparent pixel.

    # Create some interesting data.
    w = 32
    nrows = 3*w
    ncols = 5*w
    kernel = np.exp(-np.linspace(-2, 2, 35)**2)
    kernel = kernel/kernel.sum()
    np.random.seed(123)
    x = np.random.randn(nrows, ncols, 3)
    x = np.apply_along_axis(lambda z: np.convolve(z, kernel, mode='same'), 0, x)
    x = np.apply_along_axis(lambda z: np.convolve(z, kernel, mode='same'), 1, x)

    # Convert to 16 bit unsigned integers.
    z = (65535*((x - x.min())/x.ptp())).astype(np.uint16)

    # Create two squares containing (0, 0, 0).
    z[w:2*w, w:2*w] = 0
    z[w:2*w, -2*w:-w] = 0

    # Write the PNG file, and indicate that (0, 0, 0) should be transparent.
    write_png('example3.png', z, transparent=(0, 0, 0))


Example 4
---------

The following script uses the option ``use_palette=True`` to create this 8-bit
indexed RGB file.

.. image:: https://raw.githubusercontent.com/WarrenWeckesser/numpngw/master/examples/example4.png
   :alt: Example 4
   :align: center

The script::

    import numpy as np
    from numpngw import write_png


    # Example 4
    #
    # Create an 8-bit indexed RGB image that uses a palette.

    img_width = 300
    img_height = 200
    img = np.zeros((img_height, img_width, 3), dtype=np.uint8)

    np.random.seed(222)
    for _ in range(40):
        width = np.random.randint(5, img_width // 5)
        height = np.random.randint(5, img_height // 5)
        row = np.random.randint(5, img_height - height - 5)
        col = np.random.randint(5, img_width - width - 5)
        color = np.random.randint(80, 256, size=2)
        img[row:row+height, col:col+width, 1:] = color

    write_png('example4.png', img, use_palette=True)


Example 5
---------

This animated PNG

.. image:: https://raw.githubusercontent.com/WarrenWeckesser/numpngw/master/examples/example5.png
   :alt: Example 5
   :align: center

is created by the following script.  As in the other examples, most of the
script is code that generates the data to be saved.  The line that creates
the PNG file is simply::

    write_apng("example5.png", seq, delay=50, use_palette=True)

The script::

    import numpy as np
    from numpngw import write_apng

    # Example 5
    #
    # Create an 8-bit RGB animated PNG file.

    height = 20
    width = 200
    t = np.linspace(0, 10*np.pi, width)
    seq = []
    for phase in np.linspace(0, 2*np.pi, 25, endpoint=False):
        y = 150*0.5*(1 + np.sin(t - phase))
        a = np.zeros((height, width, 3), dtype=np.uint8)
        a[:, :, 0] = y
        a[:, :, 2] = y
        seq.append(a)

    write_apng("example5.png", seq, delay=50, use_palette=True)


Example 6
---------

Another animated RGB PNG. In this example, the argument ``seq``
that is passed to ``write_apng`` is a numpy array with shape
``(num_frames, height, width, 3)``.

.. image:: https://raw.githubusercontent.com/WarrenWeckesser/numpngw/master/examples/example6.png
   :alt: Example 6
   :align: center

The script::

    import numpy as np
    from numpngw import write_apng

    # Example 6
    #
    # Create an 8-bit RGB animated PNG file.

    def smoother(w):
        # Return the periodic convolution of w with a 3-d Gaussian kernel.
        r = np.linspace(-3, 3, 21)
        X, Y, Z = np.meshgrid(r, r, r)
        kernel = np.exp(-0.25*(X*X + Y*Y + Z*Z)**2)
        fw = np.fft.fftn(w)
        fkernel = np.fft.fftn(kernel, w.shape)
        v = np.fft.ifftn(fw*fkernel).real
        return v

    height = 40
    width = 250
    num_frames = 30
    np.random.seed(12345)
    w = np.random.randn(num_frames, height, width, 3)
    for k in range(3):
        w[..., k] = smoother(w[..., k])

    seq = (255*(w - w.min())/w.ptp()).astype(np.uint8)

    write_apng("example6.png", seq, delay=40)


Example 7
---------

Create an animated PNG with different display times for each frame.

.. image:: https://raw.githubusercontent.com/WarrenWeckesser/numpngw/master/examples/example7.png
   :alt: Example 7
   :align: center

The script::

    import numpy as np
    from numpngw import write_apng

    # Example 7
    #
    # Create an animated PNG file with nonuniform display times
    # of the frames.

    bits1 = np.array([
        [0,0,1,0,0],
        [0,1,1,0,0],
        [0,0,1,0,0],
        [0,0,1,0,0],
        [0,0,1,0,0],
        [0,0,1,0,0],
        [0,1,1,1,0],
        ])

    bits2 = np.array([
        [0,1,1,1,0],
        [1,0,0,0,1],
        [0,0,0,0,1],
        [0,1,1,1,0],
        [1,0,0,0,0],
        [1,0,0,0,0],
        [1,1,1,1,1],
        ])

    bits3 = np.array([
        [0,1,1,1,0],
        [1,0,0,0,1],
        [0,0,0,0,1],
        [0,0,1,1,0],
        [0,0,0,0,1],
        [1,0,0,0,1],
        [0,1,1,1,0],
        ])

    bits_box1 = np.array([
        [0,0,0,0,0],
        [1,1,1,1,1],
        [1,0,0,0,1],
        [1,0,0,0,1],
        [1,0,0,0,1],
        [1,1,1,1,1],
        [0,0,0,0,0],
        ])

    bits_box2 = np.array([
        [0,0,0,0,0],
        [0,0,0,0,0],
        [0,1,1,1,0],
        [0,1,0,1,0],
        [0,1,1,1,0],
        [0,0,0,0,0],
        [0,0,0,0,0],
        ])

    bits_dot = np.array([
        [0,0,0,0,0],
        [0,0,0,0,0],
        [0,0,0,0,0],
        [0,0,1,0,0],
        [0,0,0,0,0],
        [0,0,0,0,0],
        [0,0,0,0,0],
        ])

    bits_zeros = np.zeros((7, 5), dtype=bool)
    bits_ones = np.ones((7, 5), dtype=bool)


    def bits_to_image(bits, blocksize=32, color=None):
        bits = np.asarray(bits, dtype=bool)
        if color is None:
            color = np.array([255, 0, 0], dtype=np.uint8)
        else:
            color = np.asarray(color, dtype=np.uint8)

        x = np.linspace(-1, 1, blocksize)
        X, Y = np.meshgrid(x, x)
        Z = np.sqrt(np.maximum(1 - (X**2 + Y**2), 0))
        # The "on" image:
        img1 = (Z.reshape(blocksize, blocksize, 1)*color)
        # The "off" image:
        img0 = 0.2*img1

        data = np.where(bits[:, None, :, None, None],
                        img1[:, None, :], img0[:, None, :])
        img = data.reshape(bits.shape[0]*blocksize, bits.shape[1]*blocksize, 3)
        return img.astype(np.uint8)

    # Create `seq` and `delay`, the sequence of images and the
    # corresponding display times.

    color = np.array([32, 48, 255])
    blocksize = 24
    # Images...
    im3 = bits_to_image(bits3, blocksize=blocksize, color=color)
    im2 = bits_to_image(bits2, blocksize=blocksize, color=color)
    im1 = bits_to_image(bits1, blocksize=blocksize, color=color)
    im_all = bits_to_image(bits_ones, blocksize=blocksize, color=color)
    im_none = bits_to_image(bits_zeros, blocksize=blocksize, color=color)
    im_box1 = bits_to_image(bits_box1, blocksize=blocksize, color=color)
    im_box2 = bits_to_image(bits_box2, blocksize=blocksize, color=color)
    im_dot = bits_to_image(bits_dot, blocksize=blocksize, color=color)

    # The sequence of images:
    seq = [im3, im2, im1, im_all, im_none, im_all, im_none, im_all, im_none,
           im_box1, im_box2, im_dot, im_none]
    # The time duration to display each image, in milliseconds:
    delay = [1000, 1000, 1000, 333, 250, 333, 250, 333, 500,
             167, 167, 167, 1000]

    # Create the animated PNG file.
    write_apng("example7.png", seq, delay=delay, default_image=im_all,
               use_palette=True)


Example 8
---------

This example shows how a Matplotlib animation can be saved as
an animated PNG file with `numpngw.AnimatedPNGWriter`.  (Be careful
with this class--it can easily create very large PNG files.)

.. image:: https://raw.githubusercontent.com/WarrenWeckesser/numpngw/master/examples/example8.png
   :alt: Example 8
   :align: center

The script::

    import numpy as np
    from scipy.integrate import odeint
    from scipy.fftpack import diff as psdiff

    import matplotlib.pyplot as plt
    from matplotlib import animation
    from numpngw import AnimatedPNGWriter


    def kdv_exact(x, c):
        """
        Profile of the exact solution to the KdV for a single soliton
        on the real line.
        """
        u = 0.5*c*np.cosh(0.5*np.sqrt(c)*x)**(-2)
        return u


    def kdv(u, t, L):
        """
        Differential equations for the KdV equation, discretized in x.
        """
        # Compute the x derivatives using the pseudo-spectral method.
        ux = psdiff(u, period=L)
        uxxx = psdiff(u, period=L, order=3)

        # Compute du/dt.
        dudt = -6*u*ux - uxxx

        return dudt


    def kdv_solution(u0, t, L):
        """
        Use odeint to solve the KdV equation on a periodic domain.

        `u0` is initial condition, `t` is the array of time values at which
        the solution is to be computed, and `L` is the length of the periodic
        domain.
        """
        sol = odeint(kdv, u0, t, args=(L,), mxstep=5000)
        return sol


    def update_line(num, x, data, line):
        """
        Animation "call back" function for each frame.
        """
        line.set_data(x, data[num, :])
        return line,


    # Set the size of the domain, and create the discretized grid.
    L = 80.0
    N = 256
    dx = L / (N - 1.0)
    x = np.linspace(0, (1-1.0/N)*L, N)

    # Set the initial conditions.
    # Not exact for two solitons on a periodic domain, but close enough...
    u0 = kdv_exact(x-0.15*L, 0.8) + kdv_exact(x-0.4*L, 0.4)

    # Set the time sample grid.
    T = 260
    t = np.linspace(0, T, 225)

    print("Computing the solution.")
    sol = kdv_solution(u0, t, L)

    print("Generating the animated PNG file.")

    fig = plt.figure(figsize=(7.5, 1.5))
    ax = fig.gca()
    ax.set_title("Korteweg de Vries interacting solitons in a periodic domain "
                "(L = 80)")

    # Plot the initial condition. lineplot is reused in the animation.
    lineplot, = ax.plot(x, u0, 'c-', linewidth=3)
    plt.tight_layout()

    ani = animation.FuncAnimation(fig, update_line, frames=len(t),
                                  init_func=lambda : None,
                                  fargs=(x, sol, lineplot))
    writer = AnimatedPNGWriter(fps=12)
    ani.save('kdv.png', dpi=60, writer=writer)

    plt.close(fig)

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/WarrenWeckesser/numpngw",
    "name": "numpngw",
    "maintainer": "",
    "docs_url": null,
    "requires_python": "",
    "maintainer_email": "",
    "keywords": "numpy png matplotlib animation",
    "author": "Warren Weckesser",
    "author_email": "",
    "download_url": "https://files.pythonhosted.org/packages/56/cb/f9d11096476a6be47305f14f9e9354549fd5af04c57d0346693789745270/numpngw-0.1.3.tar.gz",
    "platform": null,
    "description": "numpngw\n=======\n\nThis python package (availabe on PyPI at https://pypi.org/project/numpngw/)\ndefines the function ``write_png`` that writes a numpy array to a PNG file,\nand the function ``write_apng`` that writes a sequence of arrays to an\nanimated PNG (APNG) file.  Also included is the class ``AnimatedPNGWriter``\nthat can be used to save a Matplotlib animation as an animated PNG file;\nsee Example 8 for an example.\n\nCapabilities of ``write_png`` include:\n\n* creation of 8-bit and 16-bit RGB files;\n* creation of 1-bit, 2-bit, 4-bit, 8-bit and 16-bit grayscale files;\n* creation of RGB and grayscale images with an alpha channel;\n* setting a transparent color;\n* automatic creation of a palette for an indexed PNG file;\n* inclusion of ``tEXt``, ``tIME``, ``bKGD``, ``pHYs``, ``gAMA``, ``cHRM``\n  and ``iCCP`` chunks.\n\nThe package is written in pure python.  The only external dependencies\nare numpy and setuptools.\n\nThe package has a suite of unit tests, but it should still be considered\nprototype-quality software.  There may be backwards-incompatible API changes\nbetween releases.\n\nThis software is released under the BSD 2-clause license.\n\nFor packages with more features (including functions for *reading* PNG files),\ntake a look at:\n\n* pypng (https://pypi.python.org/pypi/pypng) or\n* imageio (https://pypi.python.org/pypi/imageio).\n\nThe following examples show some PNG and animated PNG files created with\nnumpy and numpngw.  To see the animations in Examples 5 - 8, you must view\nthis file with a browser that supports animated PNG files.  Most web browsers\nsupport animated PNG; see https://caniuse.com/apng for support status.\n\nExample 1\n---------\n\nThe following script creates this PNG file, an 8-bit RGB image.\n\n.. image:: https://raw.githubusercontent.com/WarrenWeckesser/numpngw/master/examples/example1.png\n   :alt: Example 1\n   :align: center\n\nThe script::\n\n    import numpy as np\n    from numpngw import write_png\n\n\n    # Example 1\n    #\n    # Create an 8-bit RGB image.\n\n    img = np.zeros((80, 128, 3), dtype=np.uint8)\n\n    grad = np.linspace(0, 255, img.shape[1])\n\n    img[:16, :, :] = 127\n    img[16:32, :, 0] = grad\n    img[32:48, :, 1] = grad[::-1]\n    img[48:64, :, 2] = grad\n    img[64:, :, :] = 127\n\n    write_png('example1.png', img)\n\n\nExample 2\n---------\n\nThe following script creates this PNG file, a 1-bit grayscale image.\n\n.. image:: https://raw.githubusercontent.com/WarrenWeckesser/numpngw/master/examples/example2.png\n   :alt: Example 2\n   :align: center\n\nThe script::\n\n    import numpy as np\n    from numpngw import write_png\n\n    # Example 2\n    #\n    # Create a 1-bit grayscale image.\n\n    mask = np.zeros((48, 48), dtype=np.uint8)\n    mask[:2, :] = 1\n    mask[:, -2:] = 1\n    mask[4:6, :-4] = 1\n    mask[4:, -6:-4] = 1\n    mask[-16:, :16] = 1\n    mask[-32:-16, 16:32] = 1\n\n    write_png('example2.png', mask, bitdepth=1)\n\n\nExample 3\n---------\n\nThe following script creates this PNG file, a 16-bit RGB file in which\nthe value (0, 0, 0) is transparent.  It might not be obvious, but the\ntwo squares are transparent.\n\n.. image:: https://raw.githubusercontent.com/WarrenWeckesser/numpngw/master/examples/example3.png\n   :alt: Example 3\n   :align: center\n\nThe script::\n\n    import numpy as np\n    from numpngw import write_png\n\n    # Example 3\n    #\n    # Create a 16-bit RGB image, with (0, 0, 0) indicating a transparent pixel.\n\n    # Create some interesting data.\n    w = 32\n    nrows = 3*w\n    ncols = 5*w\n    kernel = np.exp(-np.linspace(-2, 2, 35)**2)\n    kernel = kernel/kernel.sum()\n    np.random.seed(123)\n    x = np.random.randn(nrows, ncols, 3)\n    x = np.apply_along_axis(lambda z: np.convolve(z, kernel, mode='same'), 0, x)\n    x = np.apply_along_axis(lambda z: np.convolve(z, kernel, mode='same'), 1, x)\n\n    # Convert to 16 bit unsigned integers.\n    z = (65535*((x - x.min())/x.ptp())).astype(np.uint16)\n\n    # Create two squares containing (0, 0, 0).\n    z[w:2*w, w:2*w] = 0\n    z[w:2*w, -2*w:-w] = 0\n\n    # Write the PNG file, and indicate that (0, 0, 0) should be transparent.\n    write_png('example3.png', z, transparent=(0, 0, 0))\n\n\nExample 4\n---------\n\nThe following script uses the option ``use_palette=True`` to create this 8-bit\nindexed RGB file.\n\n.. image:: https://raw.githubusercontent.com/WarrenWeckesser/numpngw/master/examples/example4.png\n   :alt: Example 4\n   :align: center\n\nThe script::\n\n    import numpy as np\n    from numpngw import write_png\n\n\n    # Example 4\n    #\n    # Create an 8-bit indexed RGB image that uses a palette.\n\n    img_width = 300\n    img_height = 200\n    img = np.zeros((img_height, img_width, 3), dtype=np.uint8)\n\n    np.random.seed(222)\n    for _ in range(40):\n        width = np.random.randint(5, img_width // 5)\n        height = np.random.randint(5, img_height // 5)\n        row = np.random.randint(5, img_height - height - 5)\n        col = np.random.randint(5, img_width - width - 5)\n        color = np.random.randint(80, 256, size=2)\n        img[row:row+height, col:col+width, 1:] = color\n\n    write_png('example4.png', img, use_palette=True)\n\n\nExample 5\n---------\n\nThis animated PNG\n\n.. image:: https://raw.githubusercontent.com/WarrenWeckesser/numpngw/master/examples/example5.png\n   :alt: Example 5\n   :align: center\n\nis created by the following script.  As in the other examples, most of the\nscript is code that generates the data to be saved.  The line that creates\nthe PNG file is simply::\n\n    write_apng(\"example5.png\", seq, delay=50, use_palette=True)\n\nThe script::\n\n    import numpy as np\n    from numpngw import write_apng\n\n    # Example 5\n    #\n    # Create an 8-bit RGB animated PNG file.\n\n    height = 20\n    width = 200\n    t = np.linspace(0, 10*np.pi, width)\n    seq = []\n    for phase in np.linspace(0, 2*np.pi, 25, endpoint=False):\n        y = 150*0.5*(1 + np.sin(t - phase))\n        a = np.zeros((height, width, 3), dtype=np.uint8)\n        a[:, :, 0] = y\n        a[:, :, 2] = y\n        seq.append(a)\n\n    write_apng(\"example5.png\", seq, delay=50, use_palette=True)\n\n\nExample 6\n---------\n\nAnother animated RGB PNG. In this example, the argument ``seq``\nthat is passed to ``write_apng`` is a numpy array with shape\n``(num_frames, height, width, 3)``.\n\n.. image:: https://raw.githubusercontent.com/WarrenWeckesser/numpngw/master/examples/example6.png\n   :alt: Example 6\n   :align: center\n\nThe script::\n\n    import numpy as np\n    from numpngw import write_apng\n\n    # Example 6\n    #\n    # Create an 8-bit RGB animated PNG file.\n\n    def smoother(w):\n        # Return the periodic convolution of w with a 3-d Gaussian kernel.\n        r = np.linspace(-3, 3, 21)\n        X, Y, Z = np.meshgrid(r, r, r)\n        kernel = np.exp(-0.25*(X*X + Y*Y + Z*Z)**2)\n        fw = np.fft.fftn(w)\n        fkernel = np.fft.fftn(kernel, w.shape)\n        v = np.fft.ifftn(fw*fkernel).real\n        return v\n\n    height = 40\n    width = 250\n    num_frames = 30\n    np.random.seed(12345)\n    w = np.random.randn(num_frames, height, width, 3)\n    for k in range(3):\n        w[..., k] = smoother(w[..., k])\n\n    seq = (255*(w - w.min())/w.ptp()).astype(np.uint8)\n\n    write_apng(\"example6.png\", seq, delay=40)\n\n\nExample 7\n---------\n\nCreate an animated PNG with different display times for each frame.\n\n.. image:: https://raw.githubusercontent.com/WarrenWeckesser/numpngw/master/examples/example7.png\n   :alt: Example 7\n   :align: center\n\nThe script::\n\n    import numpy as np\n    from numpngw import write_apng\n\n    # Example 7\n    #\n    # Create an animated PNG file with nonuniform display times\n    # of the frames.\n\n    bits1 = np.array([\n        [0,0,1,0,0],\n        [0,1,1,0,0],\n        [0,0,1,0,0],\n        [0,0,1,0,0],\n        [0,0,1,0,0],\n        [0,0,1,0,0],\n        [0,1,1,1,0],\n        ])\n\n    bits2 = np.array([\n        [0,1,1,1,0],\n        [1,0,0,0,1],\n        [0,0,0,0,1],\n        [0,1,1,1,0],\n        [1,0,0,0,0],\n        [1,0,0,0,0],\n        [1,1,1,1,1],\n        ])\n\n    bits3 = np.array([\n        [0,1,1,1,0],\n        [1,0,0,0,1],\n        [0,0,0,0,1],\n        [0,0,1,1,0],\n        [0,0,0,0,1],\n        [1,0,0,0,1],\n        [0,1,1,1,0],\n        ])\n\n    bits_box1 = np.array([\n        [0,0,0,0,0],\n        [1,1,1,1,1],\n        [1,0,0,0,1],\n        [1,0,0,0,1],\n        [1,0,0,0,1],\n        [1,1,1,1,1],\n        [0,0,0,0,0],\n        ])\n\n    bits_box2 = np.array([\n        [0,0,0,0,0],\n        [0,0,0,0,0],\n        [0,1,1,1,0],\n        [0,1,0,1,0],\n        [0,1,1,1,0],\n        [0,0,0,0,0],\n        [0,0,0,0,0],\n        ])\n\n    bits_dot = np.array([\n        [0,0,0,0,0],\n        [0,0,0,0,0],\n        [0,0,0,0,0],\n        [0,0,1,0,0],\n        [0,0,0,0,0],\n        [0,0,0,0,0],\n        [0,0,0,0,0],\n        ])\n\n    bits_zeros = np.zeros((7, 5), dtype=bool)\n    bits_ones = np.ones((7, 5), dtype=bool)\n\n\n    def bits_to_image(bits, blocksize=32, color=None):\n        bits = np.asarray(bits, dtype=bool)\n        if color is None:\n            color = np.array([255, 0, 0], dtype=np.uint8)\n        else:\n            color = np.asarray(color, dtype=np.uint8)\n\n        x = np.linspace(-1, 1, blocksize)\n        X, Y = np.meshgrid(x, x)\n        Z = np.sqrt(np.maximum(1 - (X**2 + Y**2), 0))\n        # The \"on\" image:\n        img1 = (Z.reshape(blocksize, blocksize, 1)*color)\n        # The \"off\" image:\n        img0 = 0.2*img1\n\n        data = np.where(bits[:, None, :, None, None],\n                        img1[:, None, :], img0[:, None, :])\n        img = data.reshape(bits.shape[0]*blocksize, bits.shape[1]*blocksize, 3)\n        return img.astype(np.uint8)\n\n    # Create `seq` and `delay`, the sequence of images and the\n    # corresponding display times.\n\n    color = np.array([32, 48, 255])\n    blocksize = 24\n    # Images...\n    im3 = bits_to_image(bits3, blocksize=blocksize, color=color)\n    im2 = bits_to_image(bits2, blocksize=blocksize, color=color)\n    im1 = bits_to_image(bits1, blocksize=blocksize, color=color)\n    im_all = bits_to_image(bits_ones, blocksize=blocksize, color=color)\n    im_none = bits_to_image(bits_zeros, blocksize=blocksize, color=color)\n    im_box1 = bits_to_image(bits_box1, blocksize=blocksize, color=color)\n    im_box2 = bits_to_image(bits_box2, blocksize=blocksize, color=color)\n    im_dot = bits_to_image(bits_dot, blocksize=blocksize, color=color)\n\n    # The sequence of images:\n    seq = [im3, im2, im1, im_all, im_none, im_all, im_none, im_all, im_none,\n           im_box1, im_box2, im_dot, im_none]\n    # The time duration to display each image, in milliseconds:\n    delay = [1000, 1000, 1000, 333, 250, 333, 250, 333, 500,\n             167, 167, 167, 1000]\n\n    # Create the animated PNG file.\n    write_apng(\"example7.png\", seq, delay=delay, default_image=im_all,\n               use_palette=True)\n\n\nExample 8\n---------\n\nThis example shows how a Matplotlib animation can be saved as\nan animated PNG file with `numpngw.AnimatedPNGWriter`.  (Be careful\nwith this class--it can easily create very large PNG files.)\n\n.. image:: https://raw.githubusercontent.com/WarrenWeckesser/numpngw/master/examples/example8.png\n   :alt: Example 8\n   :align: center\n\nThe script::\n\n    import numpy as np\n    from scipy.integrate import odeint\n    from scipy.fftpack import diff as psdiff\n\n    import matplotlib.pyplot as plt\n    from matplotlib import animation\n    from numpngw import AnimatedPNGWriter\n\n\n    def kdv_exact(x, c):\n        \"\"\"\n        Profile of the exact solution to the KdV for a single soliton\n        on the real line.\n        \"\"\"\n        u = 0.5*c*np.cosh(0.5*np.sqrt(c)*x)**(-2)\n        return u\n\n\n    def kdv(u, t, L):\n        \"\"\"\n        Differential equations for the KdV equation, discretized in x.\n        \"\"\"\n        # Compute the x derivatives using the pseudo-spectral method.\n        ux = psdiff(u, period=L)\n        uxxx = psdiff(u, period=L, order=3)\n\n        # Compute du/dt.\n        dudt = -6*u*ux - uxxx\n\n        return dudt\n\n\n    def kdv_solution(u0, t, L):\n        \"\"\"\n        Use odeint to solve the KdV equation on a periodic domain.\n\n        `u0` is initial condition, `t` is the array of time values at which\n        the solution is to be computed, and `L` is the length of the periodic\n        domain.\n        \"\"\"\n        sol = odeint(kdv, u0, t, args=(L,), mxstep=5000)\n        return sol\n\n\n    def update_line(num, x, data, line):\n        \"\"\"\n        Animation \"call back\" function for each frame.\n        \"\"\"\n        line.set_data(x, data[num, :])\n        return line,\n\n\n    # Set the size of the domain, and create the discretized grid.\n    L = 80.0\n    N = 256\n    dx = L / (N - 1.0)\n    x = np.linspace(0, (1-1.0/N)*L, N)\n\n    # Set the initial conditions.\n    # Not exact for two solitons on a periodic domain, but close enough...\n    u0 = kdv_exact(x-0.15*L, 0.8) + kdv_exact(x-0.4*L, 0.4)\n\n    # Set the time sample grid.\n    T = 260\n    t = np.linspace(0, T, 225)\n\n    print(\"Computing the solution.\")\n    sol = kdv_solution(u0, t, L)\n\n    print(\"Generating the animated PNG file.\")\n\n    fig = plt.figure(figsize=(7.5, 1.5))\n    ax = fig.gca()\n    ax.set_title(\"Korteweg de Vries interacting solitons in a periodic domain \"\n                \"(L = 80)\")\n\n    # Plot the initial condition. lineplot is reused in the animation.\n    lineplot, = ax.plot(x, u0, 'c-', linewidth=3)\n    plt.tight_layout()\n\n    ani = animation.FuncAnimation(fig, update_line, frames=len(t),\n                                  init_func=lambda : None,\n                                  fargs=(x, sol, lineplot))\n    writer = AnimatedPNGWriter(fps=12)\n    ani.save('kdv.png', dpi=60, writer=writer)\n\n    plt.close(fig)\n",
    "bugtrack_url": null,
    "license": "BSD",
    "summary": "Write numpy array(s) to a PNG or animated PNG file.",
    "version": "0.1.3",
    "project_urls": {
        "Homepage": "https://github.com/WarrenWeckesser/numpngw"
    },
    "split_keywords": [
        "numpy",
        "png",
        "matplotlib",
        "animation"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "5f05218a78d1b96e039cceedb61c0bc32f25d6a5781d87819fc64fd28db66dd5",
                "md5": "19be60862f2e4f90486ccca9cb2988c9",
                "sha256": "7a7eac24d7f509d174fbf2f66de0fbb45922ac6ff6cc395befed1ee5155e281d"
            },
            "downloads": -1,
            "filename": "numpngw-0.1.3-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "19be60862f2e4f90486ccca9cb2988c9",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": null,
            "size": 21394,
            "upload_time": "2023-10-07T17:31:51",
            "upload_time_iso_8601": "2023-10-07T17:31:51.494376Z",
            "url": "https://files.pythonhosted.org/packages/5f/05/218a78d1b96e039cceedb61c0bc32f25d6a5781d87819fc64fd28db66dd5/numpngw-0.1.3-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "56cbf9d11096476a6be47305f14f9e9354549fd5af04c57d0346693789745270",
                "md5": "06cbb8b1338f0be2aad0846eeca6059d",
                "sha256": "a757a17d3a497d63feee44c15a7a5be2476a1bf61de6aad4c5bd58e3d3153d62"
            },
            "downloads": -1,
            "filename": "numpngw-0.1.3.tar.gz",
            "has_sig": false,
            "md5_digest": "06cbb8b1338f0be2aad0846eeca6059d",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 29178,
            "upload_time": "2023-10-07T17:31:53",
            "upload_time_iso_8601": "2023-10-07T17:31:53.062701Z",
            "url": "https://files.pythonhosted.org/packages/56/cb/f9d11096476a6be47305f14f9e9354549fd5af04c57d0346693789745270/numpngw-0.1.3.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-10-07 17:31:53",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "WarrenWeckesser",
    "github_project": "numpngw",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "numpngw"
}
        
Elapsed time: 0.11935s