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

时间:2022-12-01 16:50:43

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?

附带的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); 

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

1 个解决方案

#1


2  

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

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

m(linearIndices) = 255;

to

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

#1


2  

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

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

m(linearIndices) = 255;

to

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