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>dtype=uint8</code> is not an element of the array. It is just a thing that gets printed to let you know that the array is of type <code>np.uint8</code>.</p>

<p>The default types <code>np.float_</code> and <code>np.int_</code> do not get a printout like that, which is what you are seeing in the second case. The way you can tell float and int arrays apart is that float arrays will always have decimal points in the numbers.</p>

<p>The reason that this is happening is that you are adding <code>2</code> to each element of your array. Since <code>2</code> is an integer, the output array gets promoted to <code>np.int_</code> type and you do not get an explicit <code>dtype</code> printout.</p>

<p>You can try the following experiment: redefine <code>myfunc</code> to add a <code>np.uint8</code> instead of an integer to the array elements and try to print the result:</p>

<pre><code>def myfunc(a, b):
    return a + np.uint8(2)
</code></pre>

<p>Finally, keep in mind that vectorizing Python code is usually not the best way to get things done. The function itself will be a Python function, and therefore slow. It is generally better to find a way of performing whatever operations you want with numpy functions.</p>

python numpy