[Numpy-discussion] SWIGed function does not like my boolean array

Timothy Hochberg tim.hochberg@ieee....
Wed Nov 7 11:46:21 CST 2007


On Nov 7, 2007 10:35 AM, Sebastian Haase <haase@msg.ucsf.edu> wrote:

> On Nov 7, 2007 5:23 PM, Matthieu Brucher <matthieu.brucher@gmail.com>
> wrote:
> >
> > > I don't understand.  I'm thinking of most math functions in the
> > > C-library. In C a boolean is just an integer of 0 or 1 (quasi, by
> > > definition).
> > >
> > > Could you explain what you mean ?
> > >
> >
> > In C++, bool is a new type that has two values, true and false. If you
> add
> > true and true, it is still true, and not 2. In C, everything that is not
> 0
> > is true, not in C++.
>
> Yes, I know this. But my situation is "the other way around". Lets say
> I want to count "foreground pixels" in an image: I would want to "sum"
> all the true values, i.e. a true *is* a 1 and a false *is* a 0.
>
> In other words, I'm really thinking of (older kind of) C, where there
> *was* no bool.
> I assume this thinking still applies to the internal arithmetic of CPUs
> today.
> Also the "bit-values" of a boolean array (in memory) are set this way
> already anyway !
>
> How can I simply call my functions looking at these bit values ?
> (essentially interpreting a boolean true as 1 and false as 0)


I'm not sure how well this would work, but could you change the dtype before
passing the array to your function? If you wanted a copy, you could just to
the equivalent of a.astype(unit8). However, if you didn't want a copy, you
could set the dtype to unit8, operate on the array and then reset it to
bool:
>>> a = np.array([True, True, False, True])
>>> a
array([ True,  True, False,  True], dtype=bool)
>>> a.dtype = np.uint8
>>> a
array([1, 1, 0, 1], dtype=uint8)
>>> # do something with 'a' here
>>> a.dtype = bool
>>> a
array([ True,  True, False,  True], dtype=bool)
This assumes everything is single threaded. If you have multiple threads
accessing 'a', this could be a problem... And, you probably want to do this
in C, so translate as appropriate.

-tim





>
>
> -Sebastian
> _______________________________________________
> Numpy-discussion mailing list
> Numpy-discussion@scipy.org
> http://projects.scipy.org/mailman/listinfo/numpy-discussion
>



-- 
.  __
.   |-\
.
.  tim.hochberg@ieee.org
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://projects.scipy.org/pipermail/numpy-discussion/attachments/20071107/ca53f729/attachment.html 


More information about the Numpy-discussion mailing list