我有一个图像和一个由regionprops定义的图像中的几个大对象的像素。现在我想生成一个只包含一个对象的新图像,该对象的大小调整为对象的大小。所以我所做的就是
rawimage = imread('testfile.tif');
processimage = squeeze((sum(rawimage,3))');
IMAGE_labeled = bwlabel(processimage,8);
shapedata=regionprops (IMAGE_labeled,'Area','PixelList');
index = find ([shapedata.Area]>5000);
for i = 1:length(index)
ix = shapedata(index(i)).PixelList(:,1);
iy = shapedata(index(i)).PixelList(:,2);
newimage = zeros(max(ix)-min(ix)+1,max(iy)-min(iy)+1,3);
for im = 1:length(ix)
newimage(ix(im)-min(ix)+1,iy(im)-min(iy)+1,:) = rawimage(ix(im),iy(im),:);
end
newimage = uint8(newimage);
imwrite(newimage,'myimage.tif','tif')
end
有没有人知道如何对第二个for循环进行矢量化以加快整个代码的速度?最后,问题是如何在矩阵中使用两个向量作为索引。
我找到了
Vc = num2cell([ix,iy])
rawimage(sub2ind(size(rawimage),Vc{i,:}))
但这又要求for循环遍历Vc的所有索引,因为我无法使用
rawimage(sub2ind(size(rawimage),Vc))
感谢您的建议
答案 0 :(得分:2)
由于您的图片具有第三维,因此您需要首先将其重塑为[M*N x 3]
数组。然后,您可以使用已显示的sub2ind
。
for k = 1:numel(shapedata)
% Flip the PixelList so it's row/column rather than x/y
list = fliplr(shapedata(k).PixelList);
% Figure out the extents of the PixelList values
minima = min(list, [], 1);
maxima = max(list, [], 1);
% Grab a square of the image containing the object of interest
subimage = rawimage(minima(1):maxima(1), minima(2):maxima(2),:);
% Store the size
sz = size(subimage);
% Convert the PixelList values to linear indices within this sub-image
inds = sub2ind(sz(1:2), bsxfun(@minus, list, minima - 1));
% Reshape so that we can index into the first two dimensions at the same time
subimage = reshape(subimage, [], size(subimage, 3));
% Now create the output which is all zeros, but then we grab the values that are
% in PixelList and set them within the new matrix.
newimage = zeros(size(subimage));
newimage(inds,:) = subimage(inds,:);
% Reshape the result to be the expected dimension
newimage = reshape(newimage, sz);
end