Search code examples
matlabimage-processingborderimshowimread

Why is my resultant image not appearing correctly? MATLAB


I was given a paricular image and now I need to create borders for the image. I have decided that the width of both my black and white borders should be 25 pixels each. My code is below:

%% Reading the Image in
imdata = imread('image1.png');

%%Creating a new matrix for image3
e_imdata = zeros(300,356);

% First Rectangle of white 

for l = 25:331
    for m = 25:50
        e_imdata(m,l) = 255;
    end
end

%% Second Rectangle of White 

for l = 25:331
    for m = 250:275
        e_imdata(m,l) = 255;
    end
end


%% Third Rectangle of White

for l = 25:50
    for m = 50:250
        e_imdata(m,l) = 255;
    end
end

%%  Fourth Rectangle of White

for l = 306:331
    for m = 50:250
        e_imdata(m,l) = 255;
    end
end

%% Copying the Actual Image in 

for l = 51:305
    for m = 51:199
        e_imdata(m,l) = imdata(m-50,l-50);
    end
end

%% Final imsow
    imshow(e_imdata);

I am trying to add each white rectangle borderline one by one. This is certainly successful, but my final image does not come out the way I want it to.

Original Image:

enter image description here

I need to create this image:

enter image description here

And I seem to be getting this image:

enter image description here

All help and suggestions are much appreciated!


Solution

  • The problem is that imshow() is not scaling the grayscale colors to the proper range. Instead specify the minimum and maximum grayscale value:

    imshow(e_imdata, [0 255]);
    

    Or, convert the data to uint8

    imshow(uint8(e_imdata));
    

    Another issue in your code is that you aren't fully copying the image over, which is why you're still seeing some of the black background. The final loop should use the following indices:

    %% Copying the Actual Image in 
    for l = 51:306
        for m = 51:250
            e_imdata(m,l) = (imdata(m-50,l-50));
        end
    end