【问题标题】:Randomly selecting n pixels in an image mask在图像掩码中随机选择 n 个像素
【发布时间】:2013-11-02 13:49:40
【问题描述】:

具有大小为MxN 的掩码,包含0 和1。

如何随机选择(均匀分布)选择n这个掩码的1个像素?

编辑: 我想选择此掩码的n 像素,其中掩码为1。那些n 像素应随机分布在整个图像/掩码上。

【问题讨论】:

  • "选择 n 1 像素" - 嗯?请让问题更清楚。

标签: matlab


【解决方案1】:

在矩阵中找到“1”的索引,然后使用randperm 选择其中的一个随机子集:

idx = find(mask==1);
y = randperm(length(idx),n); %take n values from 1 to the number of values in idx
rand_idx = idx(y); %select only those values out of your indexes

【讨论】:

    【解决方案2】:

    另一个简洁的解决方案是randi 允许重复采样(替换采样):

    nonZeroSampleInds = randi(nnz(mask),1,n);
    maskInds = find(mask);
    maskSampleInds = maskInds(nonZeroSampleInds);
    

    对于非重复样本,randperm 的工作方式与 nkjt 的答案相同,或者只是为了好玩,您可以从以下内容开始,

    [~,nonZeroSampleInds]=sort(rand(1,nnz(mask)));
    

    我认为 MATLAB 的 randperm 非常适合这项工作,但这条 sort 行实际上是 how MATLAB used to implement randperm.m 在它成为 MEX 文件之前,所以我想我会提供它,因为我喜欢 MATLAB 小知识。

    如果您希望按顺序排列位置,请sort nonZeroSampleIndsmaskSampleInds

    【讨论】:

      【解决方案3】:

      你可以这样做:

      idx = find( mask == 1); % This found all 1s in your mask
      
      idx2Take = 1:5:size(idx,1); % This take 1s on every 5 (uniform distributed)
      
      uniformPts = idx(idx2Take); % Finally, obtain the mask position from the uniform distribution
      

      所以之后,你只需要得到所有的 uniformPts。

      【讨论】:

        猜你喜欢
        • 2020-07-03
        • 2014-01-28
        • 2022-01-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多