I have a numpy ndarray variable:
>>> type(data)
<class 'numpy.ndarray'>
>> data.shape
(250, 250, 3)
It corresponds to a 250*250 image containing black or white pixels.
I would like to convert r,g,b information to boolean value (black or white), hence obtaining a (250, 250) array containing boolean or 0/1 values.
I tied something like the following without success:
iswhite = lambda t: t[0] == 255
vfunc = np.vectorize(iswhite)
vfunc(data)
I believe I have to somehow use the parameter signature
of the vectorize
function but I could not figure out how to do that despite looking at Numpy documentation.
For info, I know I can achieve what I want with other ways like:
np.alltrue(data == [255, 255, 255], axis = 2)
But here I want to learn how to use vectorized functions.
Thank you in advance for your help
CodePudding user response:
As commented, you should not see np.vectorize
as a means to accelerate runtime. Per the document it is just a fancy for
loop.
Back to the question of how to use np.vectorize
in this case, you need to pass signature
so that vectorize
knows it needs to work on an array:
iswhite = lambda t: (t == 255).all()
vfunc = np.vectorize(iswhite, signature='(n)->()')
vfunc(data).shape
# (250,250)
CodePudding user response:
Your lambda function is wrong for what you're trying to achieve (I don't even want to discuss if it makes sense or not). You lambda function should be this:
iswhite = lambda t: 255