Numpy: TypeError: Cannot cast ufunc add output from dtype('float64') to dtype('uint8') with casting rule 'same_kind'

Created on 10 Feb 2016  ·  10Comments  ·  Source: numpy/numpy

I'm using Gizeh library and I get the above error upon installing the latest version of Numpy. There was no error with Numpy version 1.08.

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'

Is there a workaround or would you fix this issue please?

Most helpful comment

Typically this is code such as a += b and you need to make it np.add(a, b, out=a, casting="unsafe") (if you are sure you want the unsafe cast behaviour. Or, unless b is huge and it is safe, maybe just cast b first.

All 10 comments

You need to make the cast explicit using the casting argument in the np.add ufunc. The behavior Gizeh depends on has been deprecated since 1.7.

That is casting='unsafe'.

where should i change this @charris ?

Typically this is code such as a += b and you need to make it np.add(a, b, out=a, casting="unsafe") (if you are sure you want the unsafe cast behaviour. Or, unless b is huge and it is safe, maybe just cast b first.

I get that I was talking specifically for the changes to be made to gizeh/moviepy .

In my case, I had a similar issue. It was solved as suggested by seberg. I replaced line 40 in gizeh.py:

arr += image.flatten()

with line:

arr = np.add(arr, image.flatten(), out=arr, casting="unsafe")

I hope this helps somebody else.

I had this issue when _subtracting_ like this:
yn -= self.y_mean

My error went away when I did the subtraction via numpy.subtract, like so:
yn = np.subtract(yn, self.y_mean, out=yn, casting="unsafe")

Thanks a lot @seberg :+1:

@FilipSavic95: Could also do yn -= self.y_mean.astype(yn.dtype)

@eric-wieser Yeah, I've just tried your solution and it works. Thanks for posting it. :+1:

The question is which precision you want to use for the operation itself. the unsafe casting will do the operation in the larger (rhs) precision (or the combined safe dtype) the other option will do the cast and thus the operation in the lower precision.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

dmvianna picture dmvianna  ·  4Comments

dcsaba89 picture dcsaba89  ·  3Comments

toddrjen picture toddrjen  ·  4Comments

kevinzhai80 picture kevinzhai80  ·  4Comments

keithbriggs picture keithbriggs  ·  3Comments