MATLAB: Removing border pixels in a binary image

for loopimage processingImage Processing ToolboxMATLAB

Hello all, below is a binary image
i want to remove the border pixels as shown in red (i used paint to highlight ) in the below image
I cannot use imclearborder for this task as it eliminates any pixel attactched to the border too. So i was thinking we could write a loop and set the first and last white oixel in each row to zero. I am not quite sure how to write the loop. Can anyone help me with this problem?

Best Answer

B = bwskel(img); %skeletonized image
[rows,col]=size(B);
%% finding right edge and left edge
rightEdgeColumn = zeros(1,rows);
leftEdgeColumn=zeros(1,rows);
for row=1:rows
col1 = find(B(row, :), 1, 'last');
col2 = find(B(row, :), 1, 'first');
if ~isempty(col1) && ~isempty(col2)
rightEdgeColumn(row) = col1;
leftEdgeColumn(row) = col2;
end
end
%%removing the edge pixels
for i=1:length(rightEdgeColumn)
k=rightEdgeColumn(i);
if k==0 %% if the whole row has no white pixels
B(i,:)=0;
else
B(i,k)=0;
end
end