Reputation: 33
I have a matlab script for 8-bit image analysis and I'm trying to enhance objects in the image by subtracting the background with no objects present. What I want to do at a pixel level is:
if B-I>50 then E=I
else E=255-B-I
Where, B
is the background, I
the image and E
my enhanced image. I know I can do this by looping through each element of the image matrix by the following:
diff=imsubtract(B,I);
nrows=1024;
ncols=1360;
for r=1:nrows
for c=1:ncols
if diff(r,c)>50
E=I(r,c);
else
E=255-diff(r,c);
end
end
end
But is this rather slow when going multiple images. I've also tried the follow:
E=255-diff;
E(diff>50)=I;
But receive the following error:
In an assignment A(I) = B
, the
number of elements in B and I must
be the same.
Any tips on optimizing this would be greatly apprenticed!
Upvotes: 3
Views: 136
Reputation: 221614
Try this vectorized approach that uses logical indexing. I could not test it out on images though, so would be great if that's taken care of.
Code
diff1=double(imsubtract(B,I));
E = double(I).*(diff1>50) + (255-diff1).*(diff1<=50);
You might be needed to convert the datatype back to unsigned integer formats as used for images.
Upvotes: 0
Reputation: 7817
In an assignment A(I) = B, the number of elements in B and I must be the same.
The reason for this error is that you are trying to assign all the content of I
to a subset of E
(those pixels where diff>50
). You have to specifically tell MATLAB that you want those pixels set to the matching pixels in I
.
E(diff>50)=I(diff>50);
Incidentally you should be careful using imsubtract
here. For pixels where I
has a higher value than B
, that will result in zeros (if your values are uint8
). It may be okay (not 100% clear if you're looking for the absolute difference or really just where B
is larger than I
)
Upvotes: 4