如何生成像素值为1-12的随机位置?

时间:2014-02-06 16:38:24

标签: arrays image matlab random

附带的Matlab脚本在300 x 400的数组中创建随机数。下图中的“白色”位置的值为255.所有其他值均为0.如何更改此代码,使随机位置为1到12的整数,而不是等于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

1 个答案:

答案 0 :(得分:2)

如果要用1到12之间的随机值替换 255,请更改行

m(linearIndices) = 255;

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