El Confuso
El Confuso

Reputation: 1981

Unexpected result from numpy random.shuffle

I am using numpy.random.shuffle to scramble an binary array (code below) but the output does not appear very random. I would expect a random assortment of dots but the resulting array appears to be a semi-regular pattern of dashes. What is going on here?

img = PIL.Image.open(image_path)         
array = numpy.array(img)
# threshold image etc
outim=PIL.Image.fromarray(array)
outim.show()  # generates left image (below)

numpy.random.shuffle(array)
outim=PIL.Image.fromarray(array)
outim.show()   # generates right image (below)

enter image description here

Upvotes: 1

Views: 133

Answers (1)

Daniel Renshaw
Daniel Renshaw

Reputation: 34177

You have shuffled the rows but not the columns. numpy.random.shuffle reorders its input along the first dimension only.

To shuffle the entire thing, try

shape = array.shape
array = array.flatten()
numpy.random.shuffle(array)
array = array.reshape(shape)

Upvotes: 4

Related Questions