在Matlab中随机选择像素 [英] Randomly Selecting Pixels in a Picture Matlab

查看:511
本文介绍了在Matlab中随机选择像素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a grayscale picture that I would like to manually add noise to. First I would like to randomly select a pixel , generate a random values from 0 to 1, multiple the value by 255 and replace the pixel's previous value with the newly gotten number, and repeat the process 100 times.

我相信我的代码最多

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


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

我只是无法弄清楚如何从图像中随机选择100个像素,以及如何用我创建的值替换它们.谢谢.

I just cannot figure out how to randomly select 100 pixels from the image and how to replace them with the values I have created. assistance would be great, thanks.

推荐答案

您需要找到100个随机像素的索引:

You need to find the index of 100 random pixels:

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数组是有效的,只要您使用的数字不大于数组中元素的数量即可.因此,如果

We now have a valid random index. Note that in Matlab it's valid to use 1D indexing into a 2D array, as long as you don't use a number larger than the number of elements in the array. Thus if

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之间).最后一行

Generates 100 random numbers (between 0 and 1). The final line

myimage(rPix) = 255 * rVal;

(随机地)为myimage中的100个元素建立索引,并为rVal中的值乘以255.这是Matlab中非常强大的部分: vectorization .您可以(为了速度起见,应该始终尝试使)Matlab在一次运算中就可以对许多数字进行运算.以上等同于

Indexes (randomly) 100 elements from myimage, and assigns the values from rVal multiplied by 255. This is a very powerful part of Matlab: vectorization. You can have (and, for speed, should always try to have) Matlab operate on many numbers in a single operation. The above is equivalent to

for ii = 1:100
  myimage(rPix(ii)) = 255 * rVal(ii);
end

只有更快...

这篇关于在Matlab中随机选择像素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆