Issue
I have a 2D numpy array with only 0
and 255
values (created from a black and white image) that i'd like to XOR with another similar 2D array.
The dtype
of these arrays is uint8
and their shapes are identical.
The only information and examples i've been able to find, so far, deal with 1D arrays.
Do I need to 'flatten' these 2D arrays before XOR'ing? If so, how is that done?
Solution
numpy.logical_xor
and numpy.bitwise_xor
will work for 2-D arrays, as will the operators !=
and ^
(essentially logical and bitwise XOR, respectively).
edit: I just noticed in your title you are looking for logical XOR, but I will leave the bitwise info there for reference in case it's helpful.
Setup:
a = np.random.choice([0,255], (5,5))
b = np.random.choice([0,255], (5,5))
>>> a
array([[255, 255, 0, 255, 255],
[255, 255, 0, 255, 0],
[255, 0, 0, 0, 0],
[ 0, 255, 255, 255, 255],
[ 0, 0, 255, 0, 0]])
>>> b
array([[ 0, 255, 255, 255, 255],
[255, 0, 0, 255, 0],
[255, 0, 255, 0, 255],
[ 0, 0, 0, 0, 0],
[255, 0, 0, 0, 255]])
Logical XOR:
>>> np.logical_xor(a,b)
array([[ True, False, True, False, False],
[False, True, False, False, False],
[False, False, True, False, True],
[False, True, True, True, True],
[ True, False, True, False, True]])
# equivalently:
>>> a!=b
array([[ True, False, True, False, False],
[False, True, False, False, False],
[False, False, True, False, True],
[False, True, True, True, True],
[ True, False, True, False, True]])
Bitwise XOR:
>>> np.bitwise_xor(a,b)
array([[255, 0, 255, 0, 0],
[ 0, 255, 0, 0, 0],
[ 0, 0, 255, 0, 255],
[ 0, 255, 255, 255, 255],
[255, 0, 255, 0, 255]])
# equivalently:
>>> a^b
array([[255, 0, 255, 0, 0],
[ 0, 255, 0, 0, 0],
[ 0, 0, 255, 0, 255],
[ 0, 255, 255, 255, 255],
[255, 0, 255, 0, 255]])
Answered By - sacuL
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.