matlabimage-processingdensity-independent-pixel

How to assign values to image array in Matlab?


I am trying to write a matlab code which copies one segment of an image into another with a particular range matrices. My code works as required. The only problem I am having is that I want to assign 255 value to copied part of image so that the image appears on white background rather than black background

a=imread('/Applications/MATLAB_R2015a.app/toolbox/images/imdata/cameraman.tif');
    a=double(a);
    b=zeros(256,256);
    for i =0:1:255
        for j=0:1:255
        if((i>=97 && i<=150)&&(j>=34 && j<=81))
        b(j,i)=a(j,i);
    %    else
    %         b(j,i)=255;
        end
        end
    end
    imshow(a,[]);
    figure,imshow(b,[]);
    imageSegmenter(b);

Solution

  • Instead of initializing your matrix to zeros simply initialize it to 255.

    b = 255 + zeros(256, 256);
    

    As a side-note, MATLAB uses 1-based indexing so you should change your for loop indices to reflect that:

    for i = 1:size(b,2)
        for j = 1:size(b, 1)
            % Do stuff
        end
    end
    

    Better yet, you can completely remove the for loop.

    b = 255 + zeros(256, 256);
    b(34:81, 97:150) = a;