Skip to content Skip to sidebar Skip to footer

How To Randomize Image Pixels In Python

I am new to computational vision and python and I could not really figure out what went wrong. I have tried to randomize all the image pixels in a RGB image, but my image turned ou

Solution 1:

You are not shuffling the pixels, you are shuffling everything when you use np.ravel() and np.shuffle() afterwards.

When you shuffle the pixels, you have to make sure that the color, the RGB tuples, stay the same.

from scipy import misc

import numpy as np
import matplotlib.pyplot as plt

#Loads an arbitrary RGB image from the misc library
rgbImg = misc.face()

#Display out the original RGB image
plt.figure(1,figsize = (6, 4))
plt.imshow(rgbImg)
plt.show()

# doc on shuffle: multi-dimensional arrays are only shuffled along the first axis# so let's make the image an array of (N,3) instead of (m,n,3)

rndImg2 = np.reshape(rgbImg, (rgbImg.shape[0] * rgbImg.shape[1], rgbImg.shape[2]))
# this like could also be written using -1 in the shape tuple# this will calculate one dimension automatically# rndImg2 = np.reshape(rgbImg, (-1, rgbImg.shape[2]))#now shuffle
np.random.shuffle(rndImg2)

#and reshape to original shape
rdmImg = np.reshape(rndImg2, rgbImg.shape)

plt.imshow(rdmImg)
plt.show()

This is the random racoon, notice the colors. There is not red or blue there. Just the original ones, white, grey, green, black.

enter image description here

There are some other issues with your code I removed:

  • Do not use the nested for loops, slow.

  • The preallocation with np.zeros is not needed (if you ever need it, just pass rgbImg.shape as argument, no need to unpack the separate values)

Solution 2:

Change plt.imshow(rdmImg) into plt.imshow(rdmImg.astype(np.uint8)) This may related to this issue https://github.com/matplotlib/matplotlib/issues/9391/

Post a Comment for "How To Randomize Image Pixels In Python"