你需要找到的100個隨機像素索引:
rPix = floor(rand(1,100) * numel(myimage)) + 1;
rVal = rand(1,100);
myimage(rPix) = 255 * rVal;
解釋
rand(1,100) : an array of 1 x 100 random numbers
numel(myimage) : number of pixels
product of the two : a random number between 0 and n
floor() : the next smallest integer. This "almost" points to 100 random pixels; we're off by 1, so
+ 1 : we add one to get a valid index.
我們現在有一個有效的隨機指數。請注意,只要不使用大於數組中元素數的數字,在Matlab中使用1D索引到2D數組是有效的。因此,如果
A = rand(3,3);
b = A(5);
相同
b = A(2,2); % because the order is A(1,1), A(2,1), A(3,1), A(1,2), A(2,2), ...
下一行:
rVal = rand(1, 100);
100張生成的隨機數(0和1之間)。最後一行
myimage(rPix) = 255 * rVal;
指標(隨機地)100個從myimage
元件,並且分配從rVal
乘以255的值這是Matlab的一個非常強大的部分:矢量。 Matlab可以在一次操作中對許多數字進行操作(並且爲了速度,應該始終嘗試)。以上是相當於
for ii = 1:100
myimage(rPix(ii)) = 255 * rVal(ii);
end
只有更快......
的解釋將是巨大的,它的工作完美,但我想知道究竟是什麼,我只是做了。 – user2475404