Why does Matlab duplicate the output image ?
4 views (last 30 days)
Show older comments
Hello,
I tried to implement the thresholding technique in image processing to an image, it works but the image appears 3 times instead of one, Does anyone have an idea what went wrong?
code:
i=imread("jk.jpg");
[a,b]=size(i);
new=zeros(size(i));
n=input("Enter thresholding key");
for x=1:a
for y=1:b
if i(x,y)<=n
new(x,y)=0;
else
new(x,y)=255;
end
end
end
imshow(new);
0 Comments
Accepted Answer
DGM
on 28 May 2023
Edited: DGM
on 28 May 2023
There are a number of things going wrong here, none of which should cause an image to be displayed multiple times. ... at least not as far as I've noticed.
i=imread('peppers.png'); % this is likely uint8, RGB
[a,b]=size(i); % for any RGB image, b will be wrong
new=zeros(size(i)); % the class of this array is 'double'
% you're writing a script do do something programmatically
% so why force your script to stop and ask you repeatedly
% for a number that you could have just written as a parameter?
n=128;%input("Enter thresholding key");
% this entire loop is unnecessary
for x=1:a % x and y are backwards
for y=1:b
if i(x,y)<=n
new(x,y)=0;
else
% you're assigning the output scale contrary to the
% class of the preallocated array. The output image
% will be improperly scaled for its class, though the
% gross truncation won't be consequential in this case.
new(x,y)=255;
end
end
end
imshow(new);
[a b] % the image is 384x512
If you request N outputs from size(), the Nth output argument isn't the size of the Nth dimension. It's the product of the sizes of the Nth dimension and all higher dimensions. Surprisingly, the fact that b is wrong doesn't result in an indexing error, though I don't know that it would be good practice to rely on tricks like that.
This whole thing can be simplified.
inpict = imread('peppers.png'); % read any image
threshold = 128; % threshold value as a simple parameter
mask = inpict > threshold; % this is a logical image
mask = im2uint8(mask); % now it's a uint8 image
imshow(mask);
0 Comments
More Answers (0)
See Also
Categories
Find more on Image Processing Toolbox in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!