Setting pixels to a specific value

2019-08-31 02:01发布

问题:

I wrote this function in matlab that sets the value of the pixels x that have a degree of membership y = 1 to 1 as follows:

function c = core(x, y)
        tolerance = 0.01;
        pixels = [];
        index = 1;
        for i=1:length(y)
            for j=1:length(y)
                if abs(y(i,j)-1) <= tolerance
                x(i,j) = 1;
                pixels(index) = x(i,j);
                end
            end
            end
            c = pixels;
       end

Since I'm calling this function from a script, how can I return back those pixels that were set to 1? Or, will the correct way here to return the original image with the pixels that met the criterion set to 1.

Bur, before I continue, I didn't see that the pixels in the image that met the criterion were set to 1. Isn't my of setting the pixel to 1 correct?

The bottom line is that I'm assuming that core represents those pixels that had the degree of membership equal to 1. And, in the algorithm I'm trying to implement, I have the following line:

C1 = core(F)

Where F represents the image.

Based on that, what is the correct way to write this in matlab. Well, yes, in matlab this line can simply be written as:

C.('C1') = core(x,y);

But, the question is, based on the information above, what will be returned to my calling script and how?

And, yes, as an output, I'm always getting 1 in ans. Why is that?

Thanks.

回答1:

First off, all the parameters you pass on the right hand side of the function are treated as local parameters to the function and do not get updated outside. So to get the updated image, return it on the left side.

Second there are errors in your algorithm:

1- the for loops does not scan all the image.

2- the index variable never gets updated.

This function below should achieve what you want:

function [x,pixels] = core(y)
    tolerance = 0.01;
    pixels = [];
    index = 1;
    for i=1:size(y,1)
        for j=1:size(y,2)
            index = j+i*size(y,2);
            if abs(y(i,j)-1) <= tolerance
            x(i,j) = 1;
            pixels = [pixels index];
            end
        end
    end
end

EDIT:

A much easier way to do this without looping:

tolerance = 0.01;
x = zeros(size(y));
x((abs(y)-1) <= tolerance) = 1;
pixels = find(x==1);