0

我有一张灰度图片,我想手动添加噪点。首先,我想随机选择一个像素,生成一个从 0 到 1 的随机值,将该值乘以 255,然后将像素的先前值替换为新得到的数字,然后重复该过程 100 次。

我相信我已经把大部分代码都写下来了

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


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

我只是不知道如何从图像中随机选择 100 个像素以及如何用我创建的值替换它们。帮助会很大,谢谢。

4

3 回答 3

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 中,对 2D 数组使用 1D 索引是有效的,只要您不使用大于数组中元素数的数字。因此,如果

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

只是快得多...

于 2013-06-18T19:29:49.133 回答
1

To get the random pixel, you can take two variables x and y and generate random values for each of them inside the limits. Generate the random pixel value and replace the value at (x,y) with the random value you got. It would look like:

for i=1:100
  x = randi([1 512]);
  y = randi([1 683]);
  myimage(x,y) = rand(1)*255;
end;
于 2013-06-18T19:35:40.907 回答
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"
于 2015-04-22T17:10:18.670 回答