How to choose a ROI of an image and make rest transparent, then save it?
2 views (last 30 days)
Show older comments
Pascal Gschwend
on 15 Dec 2019
Commented: Pascal Gschwend
on 15 Dec 2019
I have two images of the same object: 1) bright-field, 2) a luminescence intensity. To create an overlay, I would like to define a ROI of the image 2), and then overlay this to the image 1). The area outside of ROI in image 2) should be transparent.
I got the ROI working and it also displays as the region outside of the ROI is transparent, but then exporting/saving fails
I=imread('cameraman.tif');
I=double(I); %convert to my typical form of input
% Define the Region of Interest
c = [100 200 200 100];
r = [100 100 200 200];
% Creates a Mask
BW = roipoly(I,c,r);
BW = double(BW);
BW(BW==0) = NaN; %set elements outside to NaN
filter_1 = I.*BW; % multipliy to get old intensity
image(filter_1);
transparent=image(I, 'AlphaData', filter_1);
imwrite(I, 'test.png', 'Alpha', filter_1) %doesn't work
0 Comments
Accepted Answer
Thiago Henrique Gomes Lobato
on 15 Dec 2019
To write the image I has to be either a double normalized to 1 or a uint8 with values from 0 to 255, in your case you had double values from 0 to 255. Alpha also has to be between 0 and 1. Changing just the last line of your code produces the results that you want
imwrite(uint8(I), 'test.png', 'Alpha', filter_1/max(filter_1(:)))
0 Comments
More Answers (1)
Pascal Gschwend
on 15 Dec 2019
3 Comments
Image Analyst
on 15 Dec 2019
You can convert your indexed image to an RGB image before saving, but you don't have to. You can save indexed images along with their colormaps. See the code below:
grayImage = imread('moon.tif');
cmap = hsv(256);
imshow(grayImage, 'Colormap', cmap);
colorbar
% Save indexed image along with it's color map to disk.
imwrite(grayImage, cmap, 'deleteme.tif');
% Read it back in and apply the colormap and observe it looks the same.
figure
[grayImage2, cmap2] = imread('deleteme.tif');
imshow(grayImage2, 'Colormap', cmap2); % Looks exactly the same
See Also
Categories
Find more on Red 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!