Numpy: how to apply vectorized functions to array with dtype
<p>I'm following <a href="http://www.scipy-lectures.org/advanced/image_processing/" rel="nofollow">this tutorial</a> on how to use numpy to manipulate images. When I load the sample image using scipy, I get a 2D array of RGB tuples, with a dtype value appended on the end.</p>

<pre><code>array([[7, 8, 5],
   [3, 5, 7]], dtype=uint8)
</code></pre>

<p>I wrote a function and vectorized it</p>

<pre><code>def myfunc(a, b):
    return a + 2

vfunc = np.vectorize(myfunc)
</code></pre>

<p>but when I apply it to my array, the result doesn't have the dtype</p>

<pre><code>array([[9, 10, 7],
   [5, 7, 9]])
</code></pre>

<p>My guess is that because "dtype + 2" isn't defined, it's just losing that element of the array.</p>

<p>How can I write a function that will not strip the dtype when I vectorize it and apply it to a numpy array?</p>

<p><code>np.vectorize</code> takes an <code>otypes</code> parameter.  You can use that to specify the dtype of the return.  Without that <code>vectorize</code> does a trial calculation on the 1st element of your array, and uses that return dtype to determine the dtype of the whole reply.</p>

<p>Look at the 3rd example in its docs.</p>

<p>Usually users encounter this when the first value produces an integer value (e.g. <code>0</code>) and they expect the whole thing to be float.</p>

<p>So try:</p>

<pre><code> vfunc = np.vectorize(myfunc, otypes=[np.uint8])
</code></pre>

python numpy