【问题标题】:Sample 1D vectors from 3D array using a vector of points使用点向量从 3D 数组中采样 1D 向量
【发布时间】:2016-03-14 21:47:58
【问题描述】:

我有一个 n 通道图像,我有一个 100x2 的点矩阵(在我的例子中,n 是 20,但将其视为 3 通道图像可能更清楚)。我需要在每个点对图像进行采样并获得这些图像点的 nx100 数组。 我知道如何使用 for 循环来做到这一点:

for j = 1:100
        samples(j,:) = image(points(j,1),points(j,2),:);
end

我将如何对其进行矢量化?我试过了

samples = image(points);

但这给出了 20 个通道的 200 个样本。如果我尝试

samples = image(points,:);

这给了我 4800 个通道的 200 个样本。甚至

samples = image(points(:,1),points(:,2));

给我 100 x 100 个 20 个样本(X 中的 x 和 Y 中的 y 的每种可能组合一个)

【问题讨论】:

  • 关于重复投票:我不明白this question 是如何处理拖尾: 的。
  • @Daniel 是的,我同意。一旦我注意到这个小细节,我就撤销了投票。

标签: matlab indexing


【解决方案1】:

执行此操作的一种简洁方法是重塑您的图像,以便您强制将[nRows, nCols, nChannels] 的图像变为[nRows*nCols, nChannels]。然后您可以将您的points 数组转换为一个线性索引(使用sub2ind),它将对应于新的“组合”行索引。然后要获取所有频道,您可以简单地使用冒号运算符 (:) 作为第二个维度,现在代表频道。

% Determine the new row index that will correspond to each point after we reshape it
sz = size(image);
inds = sub2ind(sz([1, 2]), points(:,2), points(:,1));

% Do the reshaping (i.e. flatten the first two dimensions)
reshaped_image = reshape(image, [], size(image, 3));

% Grab the pixels (rows) that we care about for all channels
newimage = reshaped_image(inds, :);

size(newimage)

    100    20

现在您已在 所有 个通道的所需点处对图像进行了采样。

【讨论】:

  • 最后一句不成立,reshape 是一个“零成本”的操作,它不会创建额外的数据副本。
  • @Daniel 哦,真的吗?只要不改就零成本?小崽子今天学到了一些东西!
  • 是的,内存中的(线性化)数据是一样的。
  • @Daniel 太棒了!谢谢(你的)信息。也许这种方法比我想象的还要好。
  • 可能替换size(image(:,:,1)),索引不是零成本操作。在这里,您从数据中复制一个切片只是为了获取大小。更好地使用s=size(image);inds = sub2ind(s([1,2]), points(:,2), points(:,1));
猜你喜欢
  • 2016-11-21
  • 1970-01-01
  • 2014-06-02
  • 2021-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-19
  • 1970-01-01
相关资源
最近更新 更多