基于边缘像素(行方向)填充图像的最佳方法

时间:2019-01-30 17:10:35

标签: image matlab image-processing

我想基于边缘像素填充对象以替换零。

我不确定padarray是否适用于此,我在下面显示了一个示例代码来重复我的需求。我可以做到,但是我认为这不是一种有效的方法,因为我一次扫描每一行以查找并填充零。

%% Example code to recreate my need
image = imread('moon.tif');
[~, ncols] = size(image);
image(image <50) = 0;
image = fliplr(image(:,1:round(ncols/2)));
% figure, imshow(image,[])
BW = bwareafilt(logical(image),1);
% create bounding box
boxProps=regionprops(BW,'BoundingBox'); 
cords_BoundingBox = boxProps(1).BoundingBox;
% Extract sub_Image
sub_Image = imcrop(image, cords_BoundingBox);
% figure, imshow(sub_Image,[])
%% This is the part I want to use better or existing function for padding
duplicate_sub_Image = sub_Image;
[nrows, ~] = size(duplicate_sub_Image);
for nrow = 1:nrows
    % current_row_inverted = fliplr(sub_Image(nrow,:));
    [~,col,pad_value] = find(duplicate_sub_Image(nrow,:),1,'last');
    duplicate_sub_Image(nrow,col+1:end) = pad_value;
end
figure, 
subplot(131),imshow(image,[]), title('original image');
subplot(132),imshow(sub_Image,[]), title('bounding box image');
subplot(133),imshow(duplicate_sub_Image,[]), title('row padded image');

enter image description here 对改进此代码或使用现有功能解决此问题有任何建议吗?

谢谢

1 个答案:

答案 0 :(得分:2)

这是不使用循环的一种方法:

[~,imin] = min(sub_Image, [], 2);
col = max(1, imin-1);
ind = sub2ind(size(sub_Image), (1:numel(col)).', col);

duplicate_sub_Image = sub_Image(ind) .* ~sub_Image + sub_Image;