Replace multiple pixels value in an image with a certain value Matlab -


i have image 640x480 img, , want replace pixels having values not in list or array x=[1, 2, 3, 4, 5] value 10, pixel in img doesn't have of values in x replaced 10. know how replace 1 value using img(img~=1)=10 or multiple values using img(img~=1 & img~=2 & img~=3 & img~=4 & img~=5)=10 when tried img(img~=x)=10 gave error saying matrix dimensions must agree. if please advise.

you can achieve combination of permute , bsxfun. can create 3d column vector consists of elements of [1,2,3,4,5], use bsxfun not equals method (@ne) on image (assuming grayscale) create 3d matrix of 5 slices. each slice tell whether locations in image do not match element in x. first slice give locations don't match x = 1, second slice give locations don't match x = 2, , on.

once finish this, can use all call operating on third dimension consolidate pixel locations not equal of 1, 2, 3, 4 or 5. last step take logical map, tells locations none of 1, 2, 3, 4, or 5 , we'd set locations 10.

one thing need consider image type , vector x must same type. can ensure casting vector same class img.

as such, this:

x = permute([1 2 3 4 5], [3 1 2]); vals = bsxfun(@ne, img, cast(x, class(img))); ind = all(vals, 3); img(ind) = 10; 

the advantage of above method list want use check elements can whatever want. prevents having messy logical indexing syntax, img(img ~= 1 & img ~= 2 & ....). have change input list @ beginning line of code, , bsxfun, permute , any should work you.

here's example 5 x 5 image:

>> rng(123123); >> img = randi(7, 5, 5)  img =       3     4     3     6     5      7     2     6     5     1      3     1     6     1     7      6     4     4     3     3      6     2     4     1     3 

by using code above, output is:

img =       3     4     3    10     5     10     2    10     5     1      3     1    10     1    10     10     4     4     3     3     10     2     4     1     3 

you can see elements neither 1, 2, 3, 4 or 5 set 10.

aside

if don't permute , bsxfun approach, 1 way have for loop , true array, keep logical anding final result logical map consists of locations not equal each value in x. in end, have logical map true locations neither equal 1, 2, 3, 4 or 5.

therefore, this:

ind = true(size(img)); idx = 1 : 5     ind = ind & img ~= idx; end img(ind) = 10; 

if instead, you'll see same answer.


Comments

Popular posts from this blog

node.js - Mongoose: Cast to ObjectId failed for value on newly created object after setting the value -

[C++][SFML 2.2] Strange Performance Issues - Moving Mouse Lowers CPU Usage -

ios - Possible to get UIButton sizeThatFits to work? -