I'm trying to apply an algorithm only to a specific region of an image. I tried imfreehand
, but not able, at least for me, to do that using this function.
So, is there some way when running my code for the operations to be applied only to some specific region of an image in MATLAB
?
Thanks.
Using a mask defined by any of the "imroi" functions - imfreehand and imellipse included, you can use roifilt2 to filter just the roi using a given filter or function.
First, define the area:
Then, use roifilt2 in one of the following ways -
Define a filter and apply it:
Apply a given function to the roi:
I2 = roifilt2(I, BW, 'histeq');
Apply a given function to the roi, specifying parameters:
The last is equivalent to calling I2 = hist(I,5); but only works on the defined roi.
ETA:
If you want to call multiple functions on the roi, it may be easiest to define your own function, which takes an image input (and optionally, other parameters), applies the appropriate filters/functions to the image, and outputs a final image - you would then call "myfunc" in the same way as "histeq" above.
You can try roipoly.
There is an example on SO here.
Here's an example:
Edit
On erode: as the matlab doc explains,
imerode
picks the lowest value from the surrounding pixels (imdilate
does the opposite). This means that the original treatment in my answer is inadequate forimerode
, it would be better to set pixels outside the selection to max on the colorscale, and I provide an example here on how to do this "manually":As other answers show, matlab has routines that handle these operations implicitly and are more efficient not least in terms of memory management, however this example provides you with more control so you can see what is happening.