Borealis
Borealis

Reputation: 8470

How to generate random locations with a pixel value of 1–12?

The attached Matlab script creates random numbers in a 300-by-400 array. The "white" locations in the image below have a value of 255. All other values are 0. How can I alter this code so that the random locations are integers from 1 to 12 rather than all equal to 255?

% Generate a totally black image to start with.
m = zeros(300, 400, 'uint8');

% Generate 1000 random locations.
numRandom = 1000;
linearIndices = randi(numel(m), 1, numRandom);

% Set those locations to be "white".
m(linearIndices) = 255;

% Display it.  Random locations will appear white.
image(m);
colormap(gray); 

enter image description here

Upvotes: 0

Views: 100

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112699

If you want to replace the value 255 by random values between 1 and 12, change line

m(linearIndices) = 255;

to

m(linearIndices) = randi(12, [numel(linearIndices) 1]);

Upvotes: 2

Related Questions