MATLAB Answers

How to use saveas for binary images?

32 views (last 30 days)
Veronika
Veronika on 8 Apr 2017
Commented: Veronika on 16 Apr 2017
Dear all,
I would like to saveas jpg my DICOM images, which I transform to binary images. So I would like to save these binary images. But I only did, that all of these images are in one .jpg picture, but I want to save them separately, for example: binaryImage1.jpg, binaryImage2.jpg,.....binaryImage37.jpg. This is my code:
Folder = 'C:/Users/ced0005/DP/DP_framework/DICOM/slicesCT/';
for i=0;
i = i+1;
for p = 48:86
filename = fullfile(Folder, sprintf('%06d.dcm', p));
grayImage(:,:,1,p - 47)= dicomread(filename);
grayImage_pater(:,:,1,p - 47)= dicomread(filename);
[rows, columns, numberOfColorChannels] = size(grayImage);
if numberOfColorChannels > 1
% Máme barevný obraz, musíme ho převést na černobílý = vybereme zelený kanál
grayImage = grayImage(:, :, 2); % zelený kanál
end
eq_grayImage = histeq(grayImage);%ekvalizace pomocí histogramu obrazu
[rows, columns, numberOfColorChannels] = size(grayImage_pater);
if numberOfColorChannels > 1
% Máme barevný obraz, musíme ho převést na černobílý = vybereme zelený kanál
grayImage_pater = grayImage_pater(:, :, 2); % zelený kanál
end
eq_grayImage_pater = histeq(grayImage_pater);
thresholdValue = 900;
binaryImage_okoli = grayImage > thresholdValue;
% Odstranění okolí.
binaryImage_okoli = imclearborder(binaryImage_okoli);
% Vyplnění otvorů.
binaryImage_okoli = imfill(binaryImage_okoli, 'holes');
% Vymazání menších otvorů.
binaryImage_okoli = bwareaopen(binaryImage_okoli, 750);
%Roztažení binárního obrazu pro přesnější segmentaci
se = strel('line',5,100);
binaryImage_okoli= imdilate(binaryImage_okoli,se);
imshow(binaryImage_okoli, []);
% X(:,:,1,p - 47) = imadjust(X(:,:,1,p - 47),[0 0.022],[]); % increase contrast
saveas(gcf(i),'Binarizace_okoli.png')
end
end
Can you advise me? Thank you for your answers.

  2 Comments

Guillaume
Guillaume on 11 Apr 2017
A bit off topic, but saving a binary image as JPEG is not a good idea. Unless you use the rarely used non-lossy compression option, JPEG will result in colour gradients at the transitions between black and white.
Thankfully, in the answers that have been provided I see that the format has been changed to PNG which is a much better format for saving binary images.
Veronika
Veronika on 11 Apr 2017
Yes, I save images in PNG format, but still, first two are saved right, but the other images are only black.
Do you know, where is a problem, please?
This is my recent code:
Folder = 'C:/Users/ced0005/DP/DP_framework/DICOM/slicesCT/';
for p = 54:86
filename = fullfile(Folder, sprintf('%06d.dcm', p));
grayImage(:,:,1,p - 53)= dicomread(filename);
%grayImage_pater(:,:,1,p - 53)= dicomread(filename);
[rows, columns, numberOfColorChannels] = size(grayImage);
if numberOfColorChannels > 1
% Máme barevný obraz, musíme ho převést na černobílý = vybereme zelený kanál
grayImage = grayImage(:, :, 2); % zelený kanál
end
eq_grayImage = histeq(grayImage);%ekvalizace pomocí histogramu obrazu
%Práh pro vytvoření binárního obrazu okolí
thresholdValue = 900
binaryImage_okoli = grayImage > thresholdValue;
% Odstranění okolí.
binaryImage_okoli = imclearborder(binaryImage_okoli);
% Vyplnění otvorů.
binaryImage_okoli = imfill(binaryImage_okoli, 'holes');
% Vymazání menších otvorů.
binaryImage_okoli = bwareaopen(binaryImage_okoli, 1150);
%Roztažení binárního obrazu pro přesnější segmentaci
se = strel('line',5,100);
binaryImage_okoli= imdilate(binaryImage_okoli,se);
imshow(binaryImage_okoli, []);
output_name = sprintf('Binarizace_okoli_%3d_%3d.png', p)
imwrite(logical(binaryImage_okoli), output_name);

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 8 Apr 2017

  13 Comments

Veronika
Veronika on 12 Apr 2017
I have 32 DICOM images and these images I transferred into binary images and then I would like to these binary images save into file. Problem is, that first two binary images are saving right, and the other (56-86) are saving like black image. I attach for example 12 DICOM images. And my code:
Folder = 'path,where is CTslices is';
filePattern = fullfile(Folder, '/*.dcm*');
ImageFiles = dir(filePattern);
% Filter the list to pick out only files of
% file types that we want (image and video files).
for Index = 1:length(ImageFiles)
end
for p = numel(Index)
for k = 1:p figure(k);
for p = 54:66
filename = fullfile(Folder, sprintf('%06d.dcm', p));
grayImage(:,:,1,p - 53)= dicomread(filename);
grayImage_pater(:,:,1,p - 53)= dicomread(filename);
[rows, columns, numberOfColorChannels] = size(grayImage);
if numberOfColorChannels > 1
% Máme barevný obraz, musíme ho převést na černobílý = vybereme zelený kanál
grayImage = grayImage(:, :, 2); % zelený kanál
end
eq_grayImage = histeq(grayImage);%ekvalizace pomocí histogramu obrazu
[rows, columns, numberOfColorChannels] = size(grayImage_pater);
if numberOfColorChannels > 1
% Máme barevný obraz, musíme ho převést na černobílý = vybereme zelený kanál
grayImage_pater = grayImage_pater(:, :, 2); % zelený kanál
end
eq_grayImage_pater = histeq(grayImage_pater);
thresholdValue = 900;
binaryImage_okoli = grayImage > thresholdValue;
% Odstranění okolí.
binaryImage_okoli = imclearborder(binaryImage_okoli);
% Vyplnění otvorů.
binaryImage_okoli = imfill(binaryImage_okoli, 'holes');
% Vymazání menších otvorů.
binaryImage_okoli = bwareaopen(binaryImage_okoli, 750);
%Roztažení binárního obrazu pro přesnější segmentaci
se = strel('line',5,100);
binaryImage_okoli= imdilate(binaryImage_okoli,se);
imshow(binaryImage_okoli);
% temp=['fig',num2str(k),'.png'];
uint8Image = uint8(255 * binaryImage_okoli);
temp=['fig',uint8Image,'.png'];
saveas(gca,temp);
end
end
end
So, PLEASE, try this and answer, if you have the same (wrong) result as me. Or there is something wrong. Thank you for your time and answer.
Image Analyst
Image Analyst on 12 Apr 2017
The poorly-named "temp" is, or should be a filename. However you're sticking an actual binary image into it for some reason. Why are you doing that? You should not.
Use sprintf() to make up a valid filename. Check what it is before you just blindly use it.
Also, why do you have this:
for p = numel(Index)
for k = 1:p figure(k);
for p = 54:66
You have a loop over p inside an outer loop over p. What is your thought process there????
Veronika
Veronika on 12 Apr 2017
So I must rename temp to binaryImage_okoli?
for p = numel(Index)
this I have for counting the number of images in file
for k = 1:p figure(k);
this is for create figure (1-33)
and this
for p = 54:66
for better name of file.
Please, if you can, transform my code for better function.

Sign in to comment.

More Answers (2)

Image Analyst
Image Analyst on 9 Apr 2017
Try this:
uint8Image = uint8(255 * binaryImage_okoli);
imwrite(uint8Image, 'Binarizace_okoli.png') ;

  9 Comments

Show 6 older comments
Veronika
Veronika on 16 Apr 2017
My current directory is
C:/Users/ced0005/DP/DP_framework/TIFF
and directory, where MATLAB is installed is:
C:/ProgramFiles/MATLAB/R2016a.
Is it problem?
I changed the raw, which you mentioned, but still it doesn´t work.
Image Analyst
Image Analyst on 16 Apr 2017
This works perfectly fine as far as I can tell.
% Initialization steps.
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
clear; % Erase all existing variables. Or clearvars if you want.
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 20;
% Specify the folder where the files live.
folder = 'C:\Users\Mark\Documents\MATLAB\work\Tests\Scans';
% Check to make sure that folder actually exists. Warn user if it doesn't.
if ~isdir(folder)
errorMessage = sprintf('Error: The following folder does not exist:\n%s', folder);
uiwait(warndlg(errorMessage));
return;
end
% Get a list of all files in the folder with the desired file name pattern.
filePattern = fullfile(folder, '*.dcm'); % Change to whatever pattern you need.
theFiles = dir(filePattern);
for k = 1 : length(theFiles)
baseFileName = theFiles(k).name;
fullFileName = fullfile(folder, baseFileName);
fprintf(1, 'Now reading %s\n', fullFileName);
% Now do whatever you want with this file name,
% such as reading it in as an image array with imread()
grayImage= dicomread(fullFileName);
subplot(1, 2, 1);
imshow(grayImage, []); % Display image.
axis on;
title(baseFileName, 'FontSize', fontSize);
drawnow; % Force display to update immediately.
% Convert to gra scale if necessary.
[rows, columns, numberOfColorChannels] = size(grayImage);
if numberOfColorChannels > 1
% % Máme barevný obraz, musíme ho převést na černobílý = vybereme %zelený kanál
grayImage = grayImage(:, :, 2); % zelený kanál
end
% Do totally unnecessary histogram equalization.
eq_grayImage = histeq(grayImage);%ekvalizace pomocí histogramu obrazu
% Do morphological processing
% Práh pro vytvoření binárního obrazu okolí
thresholdValue = 900;
binaryImage_okoli = grayImage > thresholdValue;
% Odstranění okolí.
binaryImage_okoli = imclearborder(binaryImage_okoli);
% Vyplnění otvorů.
binaryImage_okoli = imfill(binaryImage_okoli, 'holes');
% Vymazání menších otvorů.
binaryImage_okoli = bwareaopen(binaryImage_okoli, 1150);
% Roztažení binárního obrazu pro přesnější segmentaci
se = strel('line',5,100);
binaryImage_okoli= imdilate(binaryImage_okoli,se);
% Display the image.
subplot(1, 2, 2);
imshow(binaryImage_okoli, []);
title('Binarized', 'FontSize', fontSize);
% Enlarge figure to full screen.
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0 0 1 1]);
drawnow;
% Save output image.
baseOutputFileName = sprintf('Binarizace_okoli_%3d.png', k);
fullOutputFileName = fullfile(folder, baseOutputFileName);
imwrite(logical(binaryImage_okoli), fullOutputFileName);
fprintf('Saved %s.\n', fullOutputFileName);
promptMessage = sprintf('Do you want to Continue processing,\nor Quit processing?');
titleBarCaption = 'Continue?';
buttonText = questdlg(promptMessage, titleBarCaption, 'Continue', 'Quit', 'Continue');
if strcmpi(buttonText, 'Quit')
break;
end
end
% Set up figure properties:
% Enlarge figure to full screen.
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0 0 1 1]);
% Get rid of tool bar and pulldown menus that are along top of figure.
set(gcf, 'Toolbar', 'none', 'Menu', 'none');
% Give a name to the title bar.
set(gcf, 'Name', 'Demo by ImageAnalyst for Veronika', 'NumberTitle', 'Off')
msgbox('Done with Program');
Veronika
Veronika on 16 Apr 2017
Thank you, sooo much. You are amazing!

Sign in to comment.


Payam Khoshkenar
Payam Khoshkenar on 9 Apr 2017
Edited: Walter Roberson on 9 Apr 2017
I have a microscope image with three channels (RED, GREEN and BLUE), each channel is unit 16 intensity image. I want to show each channel in a subplot (1,3), but in their color form (RGB). I figured it out that with the following command, I can all channels into one RGB image, but I want to show each channel in one subplot.
overlay=cat(3,imadjust(mat2gray(RED)),imadjust(mat2gray(GREEN)),imadjust(mat2gray(BLUE)));
Is there anyway to show/convert my intensity grayscale images into RGB format? I also found in one of your replies that following line can show each channel in RGB format but the output image is not adjusted and also I cannot adjust the output of following code by imadjust because it's not grayscale anymore:
red_IM = cast(cat(3, RED, zeros(size(RED)), zeros(size(RED))), class(RED));
I would appreciate if you could help me.
Thanks

  1 Comment

Walter Roberson
Walter Roberson on 9 Apr 2017
red_IM = cast(cat(3, imadjust(mat2gray(RED)), zeros(size(RED)), zeros(size(RED))), class(RED));

Sign in to comment.


Translated by