开发者

How to mask part of an image in matlab?

I would like to know how to mask part of an image that is in BLACK & WHITE ?

I got an object that needs to be edge detected, but I have other white interfering objects in the background that are below the target objet ... I would like to mask the entire lower part of an image to black, how can I do that ?

Thanks !!

EDIT

I also want to mask some other parts (top part) ... how can I do that ?

Please explain the code because I really wnat to learn how it works and implement it in my own understanding.

EDIT2

My image is 开发者_如何学Python480x640 ... Is there a way to mask specific pixels ? for example 180x440 from the image ...


If you have a 2-D grayscale intensity image stored in matrix A, you can set the lower half to black by doing the following:

centerIndex = round(size(A,1)/2);         %# Get the center index for the rows
A(centerIndex:end,:) = cast(0,class(A));  %# Set the lower half to the value
                                          %#   0 (of the same type as A)

This works by first getting the number of rows in A using the function SIZE, dividing that by 2, and rounding it off to get an integer index near the center of the image height. Then, the vector centerIndex:end indexes all the rows from the center index to the end, and : indexes all the columns. All of these indexed elements are set to 0 to represent the color black.

The function CLASS is used to get the data type of A so that 0 can be cast to that type using the function CAST. This may not be necessary, though, as 0 will probably be automatically converted to the type of A without them.

If you want to create a logical index to use as a mask, you can do the following:

mask = true(size(A));  %# Create a matrix of true values the same size as A
centerIndex = round(size(A,1)/2);  %# Get the center index for the rows
mask(centerIndex:end,:) = false;   %# Set the lower half to false

Now, mask is a logical matrix with true (i.e. "1") for pixels you want to keep and false (i.e. "0") for pixels you want to set to 0. You can set more elements of mask to false as you wish. Then, when you want to apply the mask, you can do the following:

A(~mask) = 0;  %# Set all elements in A corresponding
               %#   to false values in mask to 0


function masked = maskout(src,mask)
    % mask: binary, same size as src, but does not have to be same data type (int vs logical)
    % src: rgb or gray image
    masked = bsxfun(@times, src, cast(mask,class(src)));
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜