我有一个二值图像,我需要从中随机选择一个值为 1 的像素(一个白色像素)。我写了一个while/if循环来完成这项工作,这是我的代码:
Clear all
clc
% I have defined matrix A as an example of a given bw image
A=[0 0 1 0 0;0 0 0 1 0;0 1 0 0 0;0 0 0 1 0;1 0 0 0 0];
bwImage=mat2gray(A);
Number_Of_Pixls = numel(bwImage)
Number_Of_Interest_Points=numel(find(bwImage))
% randomly select a pixel
condition=0;
while ~(condition)
RandomPixel = randi(Number_Of_Pixls)
bwImage(RandomPixel) % to show the value of the selected pixel
if bwImage(RandomPixel) == 1
condition = 1; break
else
continue
end
end
SelectedPixel =RandomPixel % show which pixel had been selected
这段代码有效,但是当涉及到具有大量像素的真实图像时,这个搜索过程变得非常详尽,计算量也很大,这使得它实际上毫无用处。有什么方法可以更快地完成这项工作吗?