2013-06-18 60 views
0

我有一個灰度圖片,我想手動添加噪音。首先,我想隨機選擇一個像素,從0到1生成一個隨機值,將該值乘以255,然後用新獲取的數字替換該像素的先前值,然後重複該過程100次。隨機選擇一個圖片中的像素Matlab

我相信我有大部分的代碼下來

clc; 
fid = fopen(str); 
myimage = fread(fid, [512 683]); 
fclose(fid); 


for i = 1:100 
A(i) = rand(1) * 255; 
end 

我只是無法弄清楚如何隨機選擇從圖像100個像素,以及如何用我所創造的價值取代它們。援助會很好,謝謝。

回答

2

你需要找到的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 

只有更快......

+0

的解釋將是巨大的,它的工作完美,但我想知道究竟是什麼,我只是做了。 – user2475404

1

爲了得到隨機像素,可以採取兩個變量Xÿ,併爲他們每個人的隨機值在極限內。生成隨機像素值並將(x,y)處的值替換爲您獲得的隨機值。它看起來像:

for i=1:100 
    x = randi([1 512]); 
    y = randi([1 683]); 
    myimage(x,y) = rand(1)*255; 
end; 
+0

好吧,randi是一個matlab函數。您不需要包含任何類型的工具箱。我正在運行matlab 2012a,它裏面有randi。您可以通過在matlab中運行** help randi **來檢查。 – diggy

+0

行 - 我正在運行一個較舊的版本。我站在更正 - 你修改後的代碼將工作。 – Floris

+0

+1不錯的答案。 –

0

使用功能randperm

image = imread('image_name.extension'); 
[row col] = size(image); 
indices = randperm(row*col); 
loc = randperm(100); 

randomly_selected_pixels = image(indices(loc)); 

% Assign the values that you have to these "randomly_selected_pixels"