How do I save an image generated by imshow(image) into a variable?

2.4k views Asked by At

This is my code. I want to save the image displayed on imshow(img) into a variable to use it later. Thanks!

img=imread('image1.bmp');
figure(1), imshow(img);

[r c]=ginput(4);
Bw=roipoly(img,r,c);
% figure,imshow(Bw)
   [R C]=size(Bw);

for i=1:R
    for j=1:C
        if Bw(i,j)==1
            img(i,j)=img(i,j);
        else
            img(i,j)=0;
        end
    end
end
figure,
imshow(img); title ('Output Image');
1

There are 1 answers

0
rayryeng On BEST ANSWER

You can use the classic getframe / cdata idiom. With the figure window open, simply do this:

figure;
imshow(img); title('Output Image');
h = getframe;
im = h.cdata;

h is a handle to the current frame that is open, and the cdata field contains image data for the frame. The above code stores the frame image data into a variable called im for use for later.

Minor Comment

That for loop code to set the output is a bit inefficient. You can do this completely vectorized and you'll notice significant speedups.

This code:

for i=1:R
    for j=1:C
        if Bw(i,j)==1
            img(i,j)=img(i,j);
        else
            img(i,j)=0;
        end
    end
end

... can be replaced with:

img(~BW) = 0;

I also don't understand why you'd need to store the image data inside the frame of imshow... when img already contains your data and you are ultimately showing the data contained in img. Why can't you just use img directly for your application? Nevertheless, the above solution will work.