Coder Social home page Coder Social logo

gizeh's People

Contributors

eriknw avatar festinuz avatar gouthambs avatar ivuk avatar mondeja avatar petebachant avatar zulko 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

gizeh's Issues

Input to 'radial' ColorGradient

I am trying to use the ColorGradient(type='radial', ... ) and getting confused with the meaning of xy1, xy2 and xy3. Going through cairocffi's docstrings, I see that cairocffi.RadialGradient takes (cx0, cy0, radius0, cx1, cy1, radius1) as arguments, instead of the coordinates of three points. Maybe the optional xy3 should be replaced by (r1,r2)? Or am I missing something?

In any case, thanks for this great module!

suggest: rotate text

add a new parameter: center

def text(... center=[0,0] ...)
...
return (Ele ... ).rotate(angle, center))

Can't run my code

When I ran my code I got:

Traceback (most recent call last):
File "C:/Users/Simon/PycharmProjects/Ani/Main.py", line 6, in
import gizeh
File "C:\Anaconda3\lib\site-packages\gizeh__init__.py", line 5, in
from .gizeh import *
File "C:\Anaconda3\lib\site-packages\gizeh\gizeh.py", line 4, in
import cairocffi as cairo
File "C:\Anaconda3\lib\site-packages\cairocffi__init__.py", line 41, in
cairo = dlopen(ffi, *CAIRO_NAMES)
File "C:\Anaconda3\lib\site-packages\cairocffi__init__.py", line 34, in dlopen
return ffi.dlopen(names[0]) # pragma: no cover
File "C:\Anaconda3\lib\site-packages\cffi\api.py", line 118, in dlopen
lib, function_cache = _make_ffi_library(self, name, flags)
File "C:\Anaconda3\lib\site-packages\cffi\api.py", line 411, in _make_ffi_library
backendlib = _load_backend_lib(backend, libname, flags)
File "C:\Anaconda3\lib\site-packages\cffi\api.py", line 400, in _load_backend_lib
return backend.load_library(name, flags)
OSError: cannot load library libcairo.so.2: error 0x7e

I was trying to run one of the examples:

import gizeh
import moviepy.editor as mpy

W,H = 128,128 # width, height, in pixels
duration = 2 # duration of the clip, in seconds

def make_frame(t):
surface = gizeh.Surface(W,H)
radius = W_(1+ (t_(duration-t))**2 )/6
circle = gizeh.circle(radius, xy = (W/2,H/2), fill=(1,0,0))
circle.draw(surface)
return surface.get_npimage()

clip = mpy.VideoClip(make_frame, duration=duration)
clip.write_gif("circle.gif",fps=15, opt="OptimizePlus", fuzz=10)

gizeh.ImagePattern broke using Numpy ver 10

File "animation/target_animation.py", line 161, in draw
    fill = gizeh.ImagePattern(self.bg.data, self.bg.pos, filter='best')
  File "build/bdist.linux-x86_64/egg/gizeh/gizeh.py", line 295, in __init__
  File "build/bdist.linux-x86_64/egg/gizeh/gizeh.py", line 50, in from_image
TypeError: Cannot cast ufunc add output from dtype('float64') to dtype('uint8') with casting rule 'same_kind'

I tried reporting this issue to numpy but they said the gizeh code needs to be modified:
You need to make the cast explicit using the casting argument in the np.add ufunc. That is casting='unsafe'.

Would you fix this issue please? I would like to use gizeh and the latest version of numpy.

Segmentation fault while creating a text clip

Problem

Segmentation fault.
In the logs, I see that PIL throws an error: PIL.Image - DEBUG - Error closing: Operation on closed image - 2023-06-05 20:45:11,107
Celery logs:

  | Traceback (most recent call last):   File "/Users/user1/opt/anaconda3/envs/bab/lib/python3.10/site-packages/billiard/pool.py", line 1265, in mark_as_worker_lost     raise WorkerLostError( billiard.exceptions.WorkerLostError: Worker exited prematurely: signal 11 (SIGSEGV) Job: 0.
-- | --

Code

I don't have a minimal example that replicates the error at the moment, but will add that tomorrow.
Code layout basically is as follows:

  1. API receives a request, and starts a celery task
  2. In the task, after some other sub-tasks, I render text as follows
       text_clip_mask = VideoClip(
            lambda t: make_frame_double_text(t)[:, :, 3] / 255.0,
            duration=render_duration,
            ismask=True,
        )
  1. in the make_frame_double_text function:
        text_segments = broken_text.split("\n")
        text_elements = []
        for i, t in enumerate(text_segments):
            x = 0 + TEXT_BOX_BORDER + 25 if i else 0 + TEXT_BOX_BORDER
            y = start_y + (i * LINE_BREAK_HEIGHT)
            text_elements.append(
                gizeh.text(
                    "  " + t,
                    fontfamily=FONT_FAMILY,
                    fontsize=SCALED_FONT_SIZE,
                    h_align="left",
                    v_align="top",
                    xy=[x, y],
                    fontslant="normal",
                    stroke=(0, 0, 0),
                    stroke_width=2,
                    fill=(1, 1, 1),
                )
            )
        for te in text_elements:
            te.draw(surface)

And this is where I get the segfault.
Here is a bit more of log if that is going to be helpful:

PIL.PngImagePlugin - DEBUG - STREAM b'IHDR' 16 13 - 2023-06-05 20:45:11,060
PIL.PngImagePlugin - DEBUG - STREAM b'pHYs' 41 9 - 2023-06-05 20:45:11,060
PIL.PngImagePlugin - DEBUG - STREAM b'PLTE' 62 12 - 2023-06-05 20:45:11,061
PIL.PngImagePlugin - DEBUG - STREAM b'IDAT' 86 6972 - 2023-06-05 20:45:11,061
PIL.PngImagePlugin - DEBUG - STREAM b'IHDR' 16 13 - 2023-06-05 20:45:11,062
PIL.PngImagePlugin - DEBUG - STREAM b'pHYs' 41 9 - 2023-06-05 20:45:11,062
PIL.PngImagePlugin - DEBUG - STREAM b'PLTE' 62 12 - 2023-06-05 20:45:11,062
PIL.PngImagePlugin - DEBUG - STREAM b'IDAT' 86 6972 - 2023-06-05 20:45:11,062
PIL.Image - DEBUG - Error closing: Operation on closed image - 2023-06-05 20:45:11,107

What has been tried and zeroed down:

I tried debugging by stepping inside gizeh, and error occurs on the first line of the (text's) draw function.

Environment

OS: macOS Monterey
Python version: 3.10.11
celery version: 5.2.7
moviepy: 1.0.3

Any help is appreciated.

Trouble positioning text element groups

I'm having a lot of trouble positioning grouped text element groups.

I want to be able to position a text group accurately by on of the corners of the group (top left, bottom left etc). I was having trouble accurately estimating where to translate the group to as the more lines in the group, the more inaccurately the translation seemed to work.

I've been trying to write some sample code to explain the problem, but translating the group isn't working at all.

This is the code:

import gizeh as gz

s_w, s_h = 600, 600
# Pre-calculated
text_w = 208

def get_box(side):
    return gz.rectangle(lx=side, ly=side,
                        xy=[s_w / 2, s_h / 2],
                        stroke=(0, 0, 0),
                        stroke_width=2)

def get_multiline_text(text, line_count=3):
    lines = []
    line_height = 32
    line_spacing = 5
    y = 0

    for i in range(line_count):
        line = get_text(text, xy=(0, y))
        lines.append(line)
        y += line_height + line_spacing

    text_h = y - line_spacing
    group = gz.Group(lines)

    return group, text_w, text_h

def get_text(text, xy):
    return gz.text(text,
                   fontfamily="Impact",
                   fontsize=40,
                   h_align="left",
                   v_align="center",
                   xy=xy)

# Use a text box to view positioning
box = get_box(200)
# Get a multiline group of text elements
text_group, w, h = get_multiline_text("HELLO WORLD", 3)
# Position group by top left corner of box
text_group.translate(xy=[200, 200])

surface = gz.Surface(width=s_w, height=s_h, bg_color=(1, 1, 1))
box.draw(surface)
text_group.draw(surface)

surface.write_to_png("./test.png")

What ever I do, the translation seems to have no effect. This is very strange as I've done this effectively elsewhere.

text_pos
Why isn't this translation working on the group?

error: Setup script exited with error: command 'x86_64-linux-gnu-gcc' failed with exit status 1

Hello,

I was trying to install gizeh on Ubuntu 14.04, running Python 2.7.6 using file setup.py by using the command: sudo python setup.py install

I get an error message:
error: Setup script exited with error: command 'x86_64-linux-gnu-gcc' failed with exit status 1

I will attach below the full text of the terminal output during the attempted install process. Any help or thoughts on how I can get this to install would be appreciated. Thank you.

Terminal output from install process:
running install
running bdist_egg
running egg_info
writing requirements to gizeh.egg-info/requires.txt
writing gizeh.egg-info/PKG-INFO
writing top-level names to gizeh.egg-info/top_level.txt
writing dependency_links to gizeh.egg-info/dependency_links.txt
reading manifest file 'gizeh.egg-info/SOURCES.txt'
reading manifest template 'MANIFEST.in'
warning: no files found matching '*.txt' under directory 'examples'
writing manifest file 'gizeh.egg-info/SOURCES.txt'
installing library code to build/bdist.linux-x86_64/egg
running install_lib
running build_py
creating build/bdist.linux-x86_64/egg
creating build/bdist.linux-x86_64/egg/gizeh
copying build/lib.linux-x86_64-2.7/gizeh/init.py -> build/bdist.linux-x86_64/egg/gizeh
copying build/lib.linux-x86_64-2.7/gizeh/tools.py -> build/bdist.linux-x86_64/egg/gizeh
copying build/lib.linux-x86_64-2.7/gizeh/geometry.py -> build/bdist.linux-x86_64/egg/gizeh
copying build/lib.linux-x86_64-2.7/gizeh/gizeh.py -> build/bdist.linux-x86_64/egg/gizeh
copying build/lib.linux-x86_64-2.7/gizeh/version.py -> build/bdist.linux-x86_64/egg/gizeh
byte-compiling build/bdist.linux-x86_64/egg/gizeh/init.py to init.pyc
byte-compiling build/bdist.linux-x86_64/egg/gizeh/tools.py to tools.pyc
byte-compiling build/bdist.linux-x86_64/egg/gizeh/geometry.py to geometry.pyc
byte-compiling build/bdist.linux-x86_64/egg/gizeh/gizeh.py to gizeh.pyc
byte-compiling build/bdist.linux-x86_64/egg/gizeh/version.py to version.pyc
creating build/bdist.linux-x86_64/egg/EGG-INFO
copying gizeh.egg-info/PKG-INFO -> build/bdist.linux-x86_64/egg/EGG-INFO
copying gizeh.egg-info/SOURCES.txt -> build/bdist.linux-x86_64/egg/EGG-INFO
copying gizeh.egg-info/dependency_links.txt -> build/bdist.linux-x86_64/egg/EGG-INFO
copying gizeh.egg-info/requires.txt -> build/bdist.linux-x86_64/egg/EGG-INFO
copying gizeh.egg-info/top_level.txt -> build/bdist.linux-x86_64/egg/EGG-INFO
zip_safe flag not set; analyzing archive contents...
creating 'dist/gizeh-0.1.10-py2.7.egg' and adding 'build/bdist.linux-x86_64/egg' to it
removing 'build/bdist.linux-x86_64/egg' (and everything under it)
Processing gizeh-0.1.10-py2.7.egg
Removing /usr/local/lib/python2.7/dist-packages/gizeh-0.1.10-py2.7.egg
Copying gizeh-0.1.10-py2.7.egg to /usr/local/lib/python2.7/dist-packages
gizeh 0.1.10 is already the active version in easy-install.pth

Installed /usr/local/lib/python2.7/dist-packages/gizeh-0.1.10-py2.7.egg
Processing dependencies for gizeh==0.1.10
Searching for cairocffi
Reading https://pypi.python.org/simple/cairocffi/
Best match: cairocffi 0.7.2
Downloading https://pypi.python.org/packages/ea/82/5fc10cf35ac66b42c2e91a71732ea319c68f58ba7c759f97d593a9bf6ffd/cairocffi-0.7.2.tar.gz#md5=b7b6a5908f4180deee84f07bcc14253d
Processing cairocffi-0.7.2.tar.gz
Writing /tmp/easy_install-ihogst/cairocffi-0.7.2/setup.cfg
Running cairocffi-0.7.2/setup.py -q bdist_egg --dist-dir /tmp/easy_install-ihogst/cairocffi-0.7.2/egg-dist-tmp-VUldm7
c/_cffi_backend.c:2:20: fatal error: Python.h: No such file or directory
#include <Python.h>
^
compilation terminated.
error: Setup script exited with error: command 'x86_64-linux-gnu-gcc' failed with exit status 1

Can't install in python 2.7

I'm unable to install gizeh

I'm getting this error
C:\Users\sunil>pip install gizeh
Collecting gizeh
Using cached https://files.pythonhosted.org/packages/28/e4/58a0811c60f72b6a4d69b780f1b7d718061170042eb112e86f7c5c4981af/gizeh-0.1.11.tar.gz
Collecting cairocffi (from gizeh)
Using cached https://files.pythonhosted.org/packages/62/be/ad4d422b6f38d99b09ad6d046ab725e8ccac5fefd9ca256ca35a80dbf3c6/cairocffi-0.9.0.tar.gz
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "", line 1, in
File "c:\users\sunil\appdata\local\temp\pip-build-v6ad6n\cairocffi\setup.py", line 51, in
'test': ['pytest-runner', 'pytest-cov'],
File "c:\python27\lib\distutils\core.py", line 111, in setup
setup_distribution = dist = klass(attrs)
File "c:\python27\lib\site-packages\setuptools\dist.py", line 335, in init
self.fetch_build_eggs(attrs['setup_requires'])
File "c:\python27\lib\site-packages\setuptools\dist.py", line 456, in fetch_build_eggs
replace_conflicting=True,
File "c:\python27\lib\site-packages\pkg_resources_init
.py", line 863, in resolve
replace_conflicting=replace_conflicting
File "c:\python27\lib\site-packages\pkg_resources_init_.py", line 1141, in best_match
return self.obtain(req, installer)
File "c:\python27\lib\site-packages\pkg_resources_init_.py", line 1153, in obtain
return installer(requirement)
File "c:\python27\lib\site-packages\setuptools\dist.py", line 522, in fetch_build_egg
return cmd.easy_install(req)
File "c:\python27\lib\site-packages\setuptools\command\easy_install.py", line 672, in easy_install
return self.install_item(spec, dist.location, tmpdir, deps)
File "c:\python27\lib\site-packages\setuptools\command\easy_install.py", line 698, in install_item
dists = self.install_eggs(spec, download, tmpdir)
File "c:\python27\lib\site-packages\setuptools\command\easy_install.py", line 879, in install_eggs
return self.build_and_install(setup_script, setup_base)
File "c:\python27\lib\site-packages\setuptools\command\easy_install.py", line 1118, in build_and_install
self.run_setup(setup_script, setup_base, args)
File "c:\python27\lib\site-packages\setuptools\command\easy_install.py", line 1104, in run_setup
run_setup(setup_script, args)
File "c:\python27\lib\site-packages\setuptools\sandbox.py", line 257, in run_setup
raise
File "c:\python27\lib\contextlib.py", line 35, in exit
self.gen.throw(type, value, traceback)
File "c:\python27\lib\site-packages\setuptools\sandbox.py", line 199, in setup_context
yield
File "c:\python27\lib\contextlib.py", line 35, in exit
self.gen.throw(type, value, traceback)
File "c:\python27\lib\site-packages\setuptools\sandbox.py", line 170, in save_modules
saved_exc.resume()
File "c:\python27\lib\site-packages\setuptools\sandbox.py", line 145, in resume
six.reraise(type, exc, self._tb)
File "c:\python27\lib\site-packages\setuptools\sandbox.py", line 158, in save_modules
yield saved
File "c:\python27\lib\site-packages\setuptools\sandbox.py", line 199, in setup_context
yield
File "c:\python27\lib\site-packages\setuptools\sandbox.py", line 254, in run_setup
_execfile(setup_script, ns)
File "c:\python27\lib\site-packages\setuptools\sandbox.py", line 49, in _execfile
exec(code, globals, locals)
File "c:\users\sunil\appdata\local\temp\easy_install-wrdojd\cffi-1.12.3\setup.py", line 127, in

  File "c:\users\sunil\appdata\local\temp\easy_install-wrdojd\cffi-1.12.3\setup.py", line 105, in uses_msvc

  File "c:\python27\lib\distutils\command\config.py", line 232, in try_compile
    self._compile(body, headers, include_dirs, lang)
  File "c:\python27\lib\distutils\command\config.py", line 138, in _compile
    self.compiler.compile([src], include_dirs=include_dirs)
  File "c:\python27\lib\distutils\msvc9compiler.py", line 473, in compile
    self.initialize()
  File "c:\python27\lib\distutils\msvc9compiler.py", line 383, in initialize
    vc_env = query_vcvarsall(VERSION, plat_spec)
  File "c:\python27\lib\site-packages\setuptools\msvc.py", line 147, in msvc9_query_vcvarsall
    return EnvironmentInfo(arch, ver).return_env()
  File "c:\python27\lib\site-packages\setuptools\msvc.py", line 1228, in return_env
    [self.VCIncludes,
  File "c:\python27\lib\site-packages\setuptools\msvc.py", line 877, in VCIncludes
    return [os.path.join(self.si.VCInstallDir, 'Include'),
  File "c:\python27\lib\site-packages\setuptools\msvc.py", line 556, in VCInstallDir
    raise distutils.errors.DistutilsPlatformError(msg)
distutils.errors.DistutilsPlatformError: Microsoft Visual C++ 9.0 is required. Get it from http://aka.ms/vcpython27

----------------------------------------

Command "python setup.py egg_info" failed with error code 1 in c:\users\sunil\appdata\local\temp\pip-build-v6ad6n\cairocffi\

Copying part of a surface to another surface

Hi,

Using cairocffi, one can copy part of the surface to another by doing something along the lines of:

ctx = surface.get_new_context()
ctx.set_source_surface(old_surface._cairo_surface, 0, 0)
ctx.rectangle(x, y, width, height)
ctx.fill()

I have tried to use gizeh.rectangle() in combination with gizeh.ImagePattern() using the old surface to achieve the same effect, but passing a gizeh.Surface to gizeh.ImagePattern() does not seem to work. I saw that it should be possible to use surface.get_npimage() instead, but I rather avoid the overhead of converting it to a numpy array and back to a Cairo surface.

Is there another way to achieve the same effect?

edit: I also tried using surface.get_npimage() and passing that to gizeh.ImagePattern() instead, but that also fails with:
"TypeError: Cannot cast ufunc add output from dtype('float64') to dtype('uint8') with casting rule 'same_kind'"

Yours sincerely,
Stephan.

Cannot draw an element whose fill is a Surface object

I've been trying to make instances of surfaces for drawing onto other surfaces (I want to make drawings piecewise, then assemble the whole thing in a modular fashion). However, when I fill a rectangle (for example) with a surface, then attempt to draw that rectangle, I get an error.

Here's my test script:

import gizeh as gz

w,h =256,256
surface_a = gz.Surface(width=w, height=h, bg_color=(1,0,0))
surface_b = gz.Surface(width=w, height=h, bg_color=(1,1,0))

rect = gz.rectangle(lx=2_w, ly=2_h, fill=surface_a)
rect.draw(surface_b)

surface_b.write_to_png('test1.png')

This is the resulting output:

Traceback (most recent call last):
File "D:\Data\test1.py", line 9, in
rect.draw(surface_b)
File "C:\Python34\lib\site-packages\gizeh\gizeh.py", line 137, in draw
self.draw_method(ctx)
File "C:\Python34\lib\site-packages\gizeh\gizeh.py", line 387, in new_draw
_set_source(ctx, fill)
File "C:\Python34\lib\site-packages\gizeh\gizeh.py", line 331, in _set_source
elif len(src)==4: # RGBA
TypeError: object of type 'Surface' has no len()

I wrote this in imitation of the write_to_png() method of the Surface class. This method also fails if I specify: y_origin='bottom'. Here is an example script:

import gizeh as gz

w,h =256,256
surface_a = gz.Surface(width=w, height=h, bg_color=(1,0,0))

surface_a.write_to_png('test1.png', y_origin='bottom')

And here is the output:

Traceback (most recent call last):
File "D:\Data\test2.py", line 7, in
surface_a.write_to_png('test2.png', y_origin='bottom')
File "C:\Python34\lib\site-packages\gizeh\gizeh.py", line 62, in write_to_png
rect.draw(new_surface)
File "C:\Python34\lib\site-packages\gizeh\gizeh.py", line 137, in draw
self.draw_method(ctx)
File "C:\Python34\lib\site-packages\gizeh\gizeh.py", line 387, in new_draw
_set_source(ctx, fill)
File "C:\Python34\lib\site-packages\gizeh\gizeh.py", line 326, in _set_source
ctx.set_source(src.make_cairo_pattern())
File "C:\Python34\lib\site-packages\gizeh\gizeh.py", line 293, in make_cairo_pattern
pat = cairo.SurfacePattern(self._cairo_surface)
File "C:\Python34\lib\site-packages\cairocffi\patterns.py", line 198, in init
self, cairo.cairo_pattern_create_for_surface(surface._pointer))
AttributeError: 'Surface' object has no attribute '_pointer'

Am I doing something incorrectly?

gizeh colour issue

Hi Zulko (and maintainers),

Excellent library -- many thanks for your work on it!

I think I have come across an issue where in RGB colours are not being interpreted properly, I think.

Here is a minimum working example: https://gist.github.com/bmer/86b6ce9b3f67854f6214

It is small, and meant to simply reproduce the problem.

What the script does is create an image which has two coloured strips. One colour is red. The other colour is a lighter red. You can change how light you want to make the lighter red by increasing the x value (on line 5).

Now, it seems that if you make red lighter very slightly (for instance, just make it x = 1), the lighter red strip disappears completely!

Does this issue occur on your computers as well?

By the way, I am using the latest version of gizeh available through pip.

Integration with Opencv

Halo, Zulko

I want to implement an object detection with opencv. After the object is found, rather than circle it with opencv's circle drawing function, I want to use an animated spinning circle in gizeh as the marker of the object. Is it possible to do that?

Issue while importing gizeh

I am getting the following error while trying to import gizeh/cairo on windows

import cairocffi as cairo

File "F:\kiss\python\Anaconda\Anaconda3\lib\site-packages\cairocffi_init_.py", line 50, in
('libcairo.so', 'libcairo.2.dylib', 'libcairo-2.dll'))

File "F:\kiss\python\Anaconda\Anaconda3\lib\site-packages\cairocffi_init_.py", line 45, in dlopen
raise OSError(error_message) # pragma: no cover

OSError: no library called "cairo" was found
no library called "libcairo-2" was found
cannot load library 'libcairo.so': error 0x7e
cannot load library 'libcairo.2.dylib': error 0x7e
cannot load library 'libcairo-2.dll': error 0x7e

Element current size and possition

Hello team,
I am trying to build an app where elements place itself on top each other. For that, I need to know the size of Element and position. What function or property I should use?

issue with gizeh text_clip

I'm using gizeh and moviepy to add text on videoclip. I use your code to create a text clip. There is an annoying issue with inconsistency in the space between the text lines. Where sometimes the space will be too large between two lines. It happens every now and then, and I don't understand why.

Here the code I'm using (your code):

def autocrop(np_img):
    if len(np_img.shape) == 3:
        if np_img.shape[2] == 4:
            thresholded_img = np_img[:,:,3] # use the mask
        else:
            thresholded_img = np_img.max(axis=2) # black margins
    zone_x = thresholded_img.max(axis=0).nonzero()[0]
    xmin, xmax = zone_x[0], zone_x[-1]
    zone_y = thresholded_img.max(axis=1).nonzero()[0]
    ymin, ymax = zone_y[0], zone_y[-1]
    return np_img[ymin:ymax+1, xmin:xmax+1]

def text_clip(text, font_family, align='left',
              font_weight='normal', font_slant='normal',
              font_height = 100, font_width = None,
              interline= None, fill_color=(0,0,0),
              stroke_color=(0, 0, 0), stroke_width=2,
              bg_color=None):
    stroke_color = np.array(stroke_color) / 255.0
    fill_color = np.array(fill_color) / 255.0
    if bg_color is not None:
        np.array(bg_color) / 255.0

    if font_width is None:
        font_width = font_height
    if interline is None:
        interline = 0.3 * font_height
    line_height = font_height + interline
    lines = text.splitlines()
    max_line = max(len(l) for l in lines)
    W = int(max_line * font_width + 2 * stroke_width)
    H = int(len(lines) * line_height + 2 * stroke_width)
    surface = gz.Surface(width=W, height=H, bg_color=bg_color)
    xpoint = {
        'center': W / 2,
        'left': stroke_width + 1,
        'right': W - stroke_width - 1
    }[align]
    for i, line in enumerate(lines):
        ypoint = (i + 1) * line_height
        text_element = gz.text(line, fontfamily=font_family, fontsize=font_height,
                               h_align=align, v_align='top',
                               xy=[xpoint, ypoint], fontslant=font_slant,
                               stroke=stroke_color, stroke_width=stroke_width,
                               fill=fill_color)
        text_element.draw(surface)
    cropped_img = autocrop(surface.get_npimage(transparent=True))
    return ImageClip(cropped_img)

This is how I create the text clip:

texts["text0"] = textwrap.fill(texts["text0"], 46)
clip = text_clip(texts["text0"], font_family="Verdana", align='left',
                     font_weight='normal', font_slant='normal',
                     font_height=33, font_width=None,
                     interline=None, fill_color=(255, 255, 255),
                     stroke_color=(255, 255, 255), stroke_width=0, bg_color=None)

Here is an example of the space between the textlines being to large:
image

Here is another one:
image

Here is a normal example where everything is fine, no problems:
image

another one where everything is fine, no problems:
image

The same code is used on every text clip, and there is no "section" used in any of the texts, just compound text. It looks like it happens to any text, regardless how many lines there are. Please help me out! Thanks :-)

Gizeh needs Decorator

import gizeh
Traceback (most recent call last):
File "", line 1, in
File "/usr/lib/python2.7/site-packages/gizeh/init.py", line 5, in
from .gizeh import *
File "/usr/lib/python2.7/site-packages/gizeh/gizeh.py", line 5, in
from decorator import decorator
ImportError: No module named decorator

After installing moviepy (which pulls decorator), gizeh runs. Add decorator to dependencies?

Issue when importing gizeh

When simply running:
import gizeh

I get the error:
Traceback (most recent call last):
File "C:\Users\Sam\Documents\Python\python 2.7\animations.py", line 6, in
main()
File "C:\Users\Sam\Documents\Python\python 2.7\animations.py", line 3, in main
import gizeh
File "build\bdist.win32\egg\gizeh__init__.py", line 5, in
File "build\bdist.win32\egg\gizeh\gizeh.py", line 4, in
File "build\bdist.win32\egg\cairocffi__init__.py", line 40, in
File "build\bdist.win32\egg\cairocffi__init__.py", line 34, in dlopen
File "C:\Python27\lib\site-packages\cffi\api.py", line 118, in dlopen
lib, function_cache = _make_ffi_library(self, name, flags)
File "C:\Python27\lib\site-packages\cffi\api.py", line 411, in _make_ffi_library
backendlib = _load_backend_lib(backend, libname, flags)
File "C:\Python27\lib\site-packages\cffi\api.py", line 400, in _load_backend_lib
return backend.load_library(name, flags)
OSError: cannot load library libcairo.so.2: error 0x7e
I had a lot of difficulty installing due to some pip issues and had to install cairocffi, gizeh and numpy manually

Deprecate 'ez_setup.py'

Since the README points that, if the installation fails requiring ez_setup the user must install it, the file ez_setup.py does nothing, so must be removed.

Loading from PNG and drawing on a surface

Hi there!

After some trial and error I got to load a PNG image, and use it as a fill for a rectangle.

        # load png and convert to numpy array
        image_surface = cairo.ImageSurface.create_from_png("my_img.png")
        im = 0+numpy.frombuffer(image_surface.get_data(), numpy.uint8)
        im.shape = (image_surface.get_height(), image_surface.get_width(), 4)
        im = im[:,:,[2,1,0,3]] # put RGB back in order

        #gizeh image pattern
        gizeh_pattern = gizeh.ImagePattern(im)
        r = gizeh.rectangle(lx=im.shape[0]*2, ly=im.shape[1]*2, xy=(im.shape[0], im.shape[1] ), fill=gizeh_pattern)

        surface = gizeh.Surface(WIDTH, HEIGHT, bg_color=(0, 0.0, 0.0))
        r.draw(surface)

Anyways, I was mostly posting the code for reference.
I am not sure if I should formalize this into a PNGImagePattern to be used as fill, of if I should modify gizeh's ImagePattern to include this code, as a variant. Maybe I could add something to gizeh's Surface so that a sufrface can be loaded from a png.

Any suggestions are appreciated, and I can make a pull request if some consensus arises.

Cannot install on OS X: C compiler cannot find ffi.h

Hello.

Following the directions here to install on OSX (10.11.6), I did this:

  1. Installed Cairo (using Homebrew, as brew install cairo).
  2. Installed ez_setup (using pip, as sudo pip install ez_setup).
  3. Tried to install Gizeh, and failed. Details:

I typed: sudo pip install gizeh
It did:

Collecting gizeh
  Downloading gizeh-0.1.10.tar.gz
Collecting cairocffi (from gizeh)
  Downloading cairocffi-0.8.0.tar.gz (79kB)
    100% |████████████████████████████████| 81kB 1.3MB/s
    Complete output from command python setup.py egg_info:
    c/_cffi_backend.c:15:10: fatal error: 'ffi.h' file not found
    #include <ffi.h>
             ^
    1 error generated.

(Followed by many Python errors that are just a big stacktrace pointing to this C compiler error.)

Did I follow the directions incorrectly? Is there a step missing? Any help appreciated, thanks.

Nathan

Cairocffi Error

I am working on a Win10, Python3.8, VSCode, Virtual Enviorment

Error
Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Users\smdro\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\gizeh\__init__.py", line 5, in <module> from .gizeh import * File "C:\Users\smdro\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\gizeh\gizeh.py", line 4, in <module> import cairocffi as cairo File "C:\Users\smdro\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\cairocffi\__init__.py", line 48, in <module> cairo = dlopen( File "C:\Users\smdro\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\cairocffi\__init__.py", line 45, in dlopen raise OSError(error_message) # pragma: no cover OSError: no library called "cairo" was found no library called "libcairo-2" was found cannot load library 'libcairo.so.2': error 0x7e cannot load library 'libcairo.2.dylib': error 0x7e cannot load library 'libcairo-2.dll': error 0x7e

Issue running rose.py with pip package

When running rose.py, with gizeh installed through pip

$ python gizeh/examples/roses.py 
    Traceback (most recent call last):
        File "gizeh/examples/roses.py", line 35, in <module>
            rose_nd.draw(surface)
        File "build/bdist.macosx-10.9-x86_64/egg/gizeh/gizeh.py", line 137, in draw
        File "build/bdist.macosx-10.9-x86_64/egg/gizeh/gizeh.py", line 378, in new_draw
        File "build/bdist.macosx-10.9-x86_64/egg/gizeh/gizeh.py", line 410, in draw
    TypeError: move_to() takes exactly 3 arguments (1001 given)

Running it with the repo here causes no problem. Just wanted to let you know that maybe the code on pip is out of date.

Adding ez_setup to requirements

When installing gizeh with pip

$ pip install gizeh

I am getting the following error:

ImportError: No module named ez_setup

(both for Python 2 and 3).

Manually installing

$ pip install ez_setup

solves the problem. However, could it be added to the requirements so it is installed automatically?

Proposing a PR to fix a few small typos

Issue Type

[x] Bug (Typo)

Steps to Replicate and Expected Behaviour

  • Examine examples/transparent_colors.py, tests/test_samples.py and observe tranparent, however expect to see transparent.
  • Examine gizeh/gizeh.py and observe happends, however expect to see happens.
  • Examine gizeh/geometry.py and observe coodinates, however expect to see coordinates.

Notes

Semi-automated issue generated by
https://github.com/timgates42/meticulous/blob/master/docs/NOTE.md

To avoid wasting CI processing resources a branch with the fix has been
prepared but a pull request has not yet been created. A pull request fixing
the issue can be prepared from the link below, feel free to create it or
request @timgates42 create the PR. Alternatively if the fix is undesired please
close the issue with a small comment about the reasoning.

https://github.com/timgates42/gizeh/pull/new/bugfix_typos

Thanks.

I find problem in Surface.from_image() function....

the probelm is:
when i use a image, to initial the Surface,
error was arise:
UFuncTypeError: Cannot cast ufunc 'add' output from dtype('float64') to dtype('uint8') with casting rule 'same_kind'

after look for the source code, I find the problem of source code:
np.dstack([image, 255 * np.ones((h, w))])

the input image' shape is [w, h, 3], type is np.uint8
I change the code to:
np.dstack([image, 255 * np.ones((h, w), dtype=np.uint8)])

the problem is disappear.

from .geometry import - Attempted relative import in non-package

crojav@crojav-Lenovo ~/gizeh/gizeh $ python hen.py
Traceback (most recent call last):
File "hen.py", line 2, in
import gizeh
File "/home/crojav/gizeh/gizeh/gizeh.py", line 5, in
from .geometry import (rotation_matrix,
ValueError: Attempted relative import in non-package

removed the . before geometry works
from geometry import (rotation_matrix,

Documentation problem

Hi!

There seems to be a mistake in the current documentation concerning rectangles.
The line

rect = gizeh.rectangle(lx=60.3, ly=45, xy=30, fill=(0,1,0), angle=Pi/8)

Should read

rect = gizeh.rectangle(lx=60.3, ly=45, xy=(30, 0), fill=(0,1,0), angle=Pi/8)

Same problem with the circle example.
Also, I get errors with the stroke_color argument...

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-48-d6947aacf826> in <module>()
      2 circ = gizeh.circle(r=30, xy=(30, 0), fill=(1,1,1))
      3 rect = gizeh.rectangle(lx=60.3, ly=45, xy=(30, 0), fill=(0,1,0), angle=Pi/8)
----> 4 sqr = gizeh.square(l=20, stroke_color=(1,1,1), stroke_width= 1.5)
      5 arc = gizeh.arc(r=20, a1=Pi/4, a2=3*Pi/4, fill=(1,1,1))
      6 text = gizeh.text("Hello world", fontfamily="Impact",  fontsize=40,

C:\Python27\lib\site-packages\gizeh\gizeh.pyc in square(l, **kw)
    395 
    396 def square(l, **kw):
--> 397     return rectangle(l,l, **kw)
    398 
    399 

C:\Python27\lib\site-packages\gizeh\gizeh.pyc in rectangle(lx, ly, **kw)
    391 
    392 def rectangle(lx, ly, **kw):
--> 393     return shape_element(lambda c:c.rectangle(-lx/2, -ly/2, lx, ly), **kw)
    394 
    395 

TypeError: shape_element() got an unexpected keyword argument 'stroke_color'

surface.ipython_display() fails in python 3

The following snippet produces no output in jupyter with python3.

import gizeh as gz
W, H = 500, 300
r, gray, t = 25., .3, 1.

surface = gz.Surface(W,H, bg_color=(1, 1, 1)) # white background
gradient = gz.ColorGradient(type="radial", stops_colors=[(0,(gray, gray, gray)), (1, (1, 1, 1))],
                            xy1=[0, 0], xy2=[0, 0], xy3=[0, r])
rf = gz.circle(r=r, xy=(W/2., H/2.), fill=gradient)
#rect = gz.rectangle(lx=.3*H, ly=.02*H, xy=(W*t/duration, H/2.), fill=(0,1,0), angle=np.pi/2)

rf.draw(surface)
surface.ipython_display()

The problem is in Surface._repr_png_(). Python 3 doesn't have the cStringIO module, so the line data = StringIO() fails (silently). If I instead use the io module as suggested here, the snippet above generates an error from cairo.

Fonts render 'fuzzily' running on Ubuntu

Hi!

This kind of relates to MoviePy as well, but I'm pretty sure the issue lies with Gizeh somehow. After spending a lot of time trying things out I've resorted to this.

I've got a MoviePy script which superimposes text on a pre existing video clip whilst animating the text to increase in size. I think I've posted all the relevant code, but let me know if anything else would help.

text_mask = mpy.VideoClip(make_frame=self.make_frame_text, duration=duration).to_mask()
text_mask.write_videofile(maskfilename, fps=25)
def make_frame_text(self, t):
e = self.current_element
if e.x == "center":
e.x = self.w/2
e.y = self.h/2
duration = e.end - e.start
sizeGrow = e.fontSize*0.2
sizeStart = e.fontSize-sizeGrow
currFrame = (t*100)/4
frameGrow = sizeGrow/(duration*25)
fsize = sizeStart + (currFrame * frameGrow)
bom = gizeh.text(e.text, fontfamily=e.font, fontsize=fsize,fill=(255,255,255), xy=(e.x,e.y))
surface = gizeh.Surface(self.w,self.h) # width, height
bom.draw(surface)
return surface.get_npimage() # returns a 8-bit RGB array

And e is an object like:
{ "text": "Hello", "font": "Courier", "fontSize": 100, "fontColor": "white", "start": 0.01, "end": 1.3, "x": 960, "y": 540, }

This all works very smoothly locally, however when I deploy (to Ubuntu 14.04 on AWS), the final product is jumpy, the text isn't as crisp and the animation isn't very smooth. Have you got any suggestions as to why that would be the case? I have checked everything I can think of, and the size and time variables are exactly the same for both versions for each frame, so essentially exactly the same thing is happening, just for some reason the local one produces a far smooth animation.

To my eye it appears that in some frames the text grows more than in others, however when I increased the sizeGrow it became clear the font size was increasing in every frame.

Any help would be really appreciated, it's driving me crazy!

Thanks!

tools.py syntax error

pip install gizeh reports a SyntaxError in tools.py (gizeh-0.1.09, on a virtualenv, Python 3.4.0, linux).

      File "/space/moviepy/env/lib/python3.4/site-packages/gizeh/tools.py", line 8
        return [1.0*int(n,16)/255 for n in string[:2], string[2:4], string[4:]]
                                                     ^
    SyntaxError: invalid syntax

Tiny imprecision in README.rst ?

Hi @Zulko ,
Been practicing on your great libraries, thanks again.
I was just wondering : the "Elements" part of your README.rst says :

text = gizeh.text("Hello world", fontfamily="Impact",  fontsize=40,
                  fontcolor=(1,1,1), xy=(100,100), angle=Pi/12)

Isn't fontcolor just supposed to be fill ? Or is there something I've missed ?

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.