如何在下面的代码中避免使用fliplr?

时间:2018-05-13 01:49:49

标签: matlab image-processing

我试图将图像中的区域分成左右两边。但我从两边避开了一定比例的中心柱子。

所以, 我必须得到左右两个的保持索引。

我使用fliplr来反转右侧的数组索引

get(1:n_indices),

然后再次fliplr恢复正常。

我可以在以下代码中避免使用fliplr

img1 = imread('sample4.png');
keepPercent = 0.9; %90 on both sides
columnsWithAllZeros = all(img1 == 0);

left_idx = find(~columnsWithAllZeros,1,'first');
right_idx = find(~columnsWithAllZeros,1,'last');

cent_idx = floor(mean([left_idx,right_idx]));
left_to_cent_idxs = left_idx:cent_idx;
cent_to_right_idxs = cent_idx+1:right_idx;
cent_to_right_idxs = fliplr(cent_to_right_idxs); % flip

num_leftKeep_idxs = floor(keepPercent *length(left_to_cent_idxs));
num_rightKeep_idxs = floor(keepPercent *length(cent_to_right_idxs));

right_keepImg_idxs = left_to_cent_idxs(1:num_leftKeep_idxs);
left_keepImg_idxs = cent_to_right_idxs(1:num_rightKeep_idxs);
left_keepImg_idxs = fliplr(left_keepImg_idxs); %flip back This is not needed I Know

[leftBrain_img, rightBrain_img]  = deal(zeros(nrow, ncol, 'logical'));
leftBrain_img(:,left_keepImg_idxs) = img1(:,left_keepImg_idxs);
rightBrain_img(:,right_keepImg_idxs) = img1(:,right_keepImg_idxs);

rightBrain_img = cast(rightBrain_img,'uint16') .*img1;
leftBrain_img = cast(leftBrain_img,'uint16') .*img1;
figure,
subplot(131), imshow(img1,[])
subplot(132), imshow(rightBrain_img,[])
subplot(133), imshow(leftBrain_img,[])

示例图片可用here

谢谢,

戈皮

1 个答案:

答案 0 :(得分:0)

可以这样做,就像@ rahnema1所说的那样。但问题是为什么即使这样做也可以在更快的速度下完成。更简单的方法! 看看这段代码 -

img1 = imread('sample4.png');
keepPercent = 0.9; %90 on both sides
columnsWithAllZeros = all(img1 == 0);
leavepercent=1-keepPercent;
idx=minmax(find(columnsWithAllZeros==0));

cent_idx = floor(mean(idx));
left_keepImg_idxs1=idx(1):cent_idx-floor(leavepercent*(cent_idx-idx(1)+1));
right_keepImg_idxs1=cent_idx+1+floor(leavepercent*(idx(2)-cent_idx+1)):idx(2);

[leftBrain_img, rightBrain_img]  =deal(zeros(512, 512, 'logical'));
leftBrain_img(:,left_keepImg_idxs1) = img1(:,left_keepImg_idxs1);
rightBrain_img(:,right_keepImg_idxs1) = img1(:,right_keepImg_idxs1);

rightBrain_img = cast(rightBrain_img,'uint16') .*img1;
leftBrain_img = cast(leftBrain_img,'uint16') .*img1;
figure,
subplot(131), imshow(img1,[])
subplot(132), imshow(rightBrain_img,[])
subplot(133), imshow(leftBrain_img,[])