Gopi
Gopi

Reputation: 369

Best way to pad image based on the edge pixels (row-wise)

I want to pad an object based on edge pixel to replace the zeros.

I am not sure if padarray is applicable to this, I am showing a sample code below to replicate my need. I am able to do it but I think this is not an efficient way as I am scanning each row at a time to find and pad the zeros.

%% 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 Any suggestions to improve this code or use of existing functions to address this issue?

Thanks

Upvotes: 1

Views: 208

Answers (1)

rahnema1
rahnema1

Reputation: 15837

Here is a way without using loops:

[~,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;

Upvotes: 2

Related Questions