我需要并行化一个 MATLAB 循环。我的代码本质上所做的是将每个提取的二进制对象(已经存储在二进制掩码中bw
)按顺序分水岭,这些对象的大小超过某个阈值,分成更小的部分。分段后,我想用分段的片段替换每个二进制块,但代码给了我错误:
- “PARFOR 循环无法运行,因为变量 'watershed_temp' 的使用方式”
- “由于使用了变量‘img_seg’的方式,PARFOR 循环无法运行”
- “'watershed_temp' 的有效索引在 PARFOR 循环中受到限制”
- “'img_seg' 的有效索引在 PARFOR 循环中受到限制”
我应该如何索引这些图像以使代码正常工作?请帮忙。
感谢您提前输入!
试图
function [bw_seg] = watershedImage(img, bw, param)
%% Parameters extraction
stats = regionprops(bw, img, 'Area', 'Image', 'PixelIdxList', 'BoundingBox');
param.medianarea = median([stats.Area]);
% Select only the BLOBs with sufficient area for watershed segmentation
thresh = 0.6*param.medianarea; % lower area threshold
BLOBind = find([stats.Area] > thresh); % BLOB indices
boundingboxbuffer = 5; % in pixels
watershed_temp = false(size(img));
bw_seg = logical(bw);
%% Watershed on each individual binary section of the mask
parfor i = 1:length(BLOBind)
% Extract each BLOB by cropping (with a buffer 'safety' border) the
% bounding box of each BLOB
r = round(stats(BLOBind(i)).BoundingBox);
boundingboxBLOB = [max(r(1)-boundingboxbuffer,1) max(r(2)-boundingboxbuffer,1) ...
r(3)+2*boundingboxbuffer-1 r(4)+2*boundingboxbuffer-1];
img_BLOB = imcrop(img, boundingboxBLOB);
% Crop the same region accordingly from the binary mask
bw_BLOB = false(size(bw));
bw_BLOB(stats(BLOBind(i)).PixelIdxList) = 1;
bw_BLOB = imcrop(bw_BLOB, boundingboxBLOB);
% Watershed segmentation (a written watershed segmentation algorithm)
L = watershedBLOB(img_BLOB, bw_BLOB, param);
%%%%%% I'm getting errors here for 'watershed_temp' and 'img_seg'!!! %%%%%%%
if max(max(bwlabel(L))) > 0 && sum(sum(L)) >= 0.6*sum(sum(bw_BLOB))
[f1, f2] = find(L > 0);
fr = f1 + boundingboxBLOB(2) - 1;
fc = f2 + boundingboxBLOB(1) - 1;
watershed_temp(sub2ind(size(img), fr, fc)) = L(sub2ind(size(L), f1, f2));
bw_seg(stats(BLOBind(i)).PixelIdxList) = 0;
end
end
bw_seg = imfill(logical(bw_seg) | watershed_temp, 'holes');
end