loading multiple tiff images as matrices from a dir - matlab

my problem is this one:
I have a directory full of .tif images and I want to import them in MATLAB each one as a matrix.
If I do right click on the file in the dir and say "Import Data" it works: I have a matrix of elements that are my pixels that I can treat with imagesc and so on.
I want to make it automatic with a script.
what I have written is this one but it opens the Import Wizard, ask me to click enter for importing the first one and then stops.
contents = dir('*pulse1us100ms26_00*'); % this is part of the name of the images I want to load
for i = 1:numel(contents)
filename = contents(i).name;
uiimport(filename);
end
??? Error using ==> uiimport at 65
Cannot open the Import Wizard on a file while the Import Wizard is open.
May you please help me?

I think imread may be what you need,
% this is part of the name of the images I want to load
contents = dir('pulse1us100ms26_00*');
for i = 1:numel(contents)
filename = contents(i).name;
im = imread(filename,'tiff');
imagesc(im(:,:,1:3))
pause(3)
end
The result will be a matrix of uint8 from 0 to 255 (depending on the picture format). You can then work with them as needed.

Related

Nib.load() error - Trying to load PNG and DICOM images to be resized for FCNN

Have 40 DICOM and 40 PNG images (data and their masks) for a Fully CNN that are loaded into my Google Drive and have been found by the notebook via the print(os.listdir(...)), as evidenced below in the first block of code where all the names of the 80 data in the above sets are listed.
Also have globbed all of the DICOM and PNG into img_path and mask_path, both with lengths of 40, in the second block of code that is below.
Now attempting to resize all of the images to 256 x 256 before inputting them into the U-net like architecture for segmentation. However, cannot load them via the nib.load() call, as it cannot work out the file type of the DCM and PNG files, even though for the latter it will not error but still produce an empty set of data like the last block of code yields.
Assuming that, once the first couple of lines inside the for loop in the third block of code are rectified, pre-processing should be completed and I can move onto the U-net implementation.
Have the current pydicom running in the Colab notebook and tried it in lieu of the nib.load() call, which produced the same error as the current one.
#import data as data
import pydicom
from PIL import Image
import numpy as np
import glob
import imageio
print(os.listdir("/content/drive/My Drive/Images"))
print(os.listdir("/content/drive/My Drive/Masks"))
pixel_data = []
images = glob.glob("/content/drive/My Drive/Images/IMG*.dcm");
for image in images:
dataset = pydicom.dcmread(image)
pixel_data.append(dataset.pixel_array)
#print(len(images))
#print(pixel_data)
pixel_data1 = [] ----------------> this section is the trouble area <-------
masks = glob.glob("content/drive/My Drive/Masks/IMG*.png");
for mask in masks:
dataset1 = imageio.imread(mask)
pixel_data1.append(dataset1.pixel_array)
print(len(masks))
print(pixel_data1)
['IMG-0004-00040.dcm', 'IMG-0002-00018.dcm', 'IMG-0046-00034.dcm', 'IMG-0043-00014.dcm', 'IMG-0064-00016.dcm',....]
['IMG-0004-00040.png', 'IMG-0002-00018.png', 'IMG-0046-00034.png', 'IMG-0043-00014.png', 'IMG-0064-00016.png',....]
0 ----------------> outputs of trouble area <--------------
[]
import glob
img_path = glob.glob("/content/drive/My Drive/Images/IMG*.dcm")
mask_path = glob.glob("/content/drive/My Drive/Masks/IMG*.png")
print(len(img_path))
print(len(mask_path))
40
40
images=[]
a=[]
for a in pixel_data:
a=resize(a,(a.shape[0],256,256))
a=a[:,:,:]
for j in range(a.shape[0]):
images.append((a[j,:,:]))
No output, this section works fine.
images=np.asarray(images)
print(len(images))
10880
masks=[] -------------------> the other trouble area <-------
b=[]
for b in masks:
b=resize(b,(b.shape[0],256,256))
b=b[:,:,:]
for j in range(b.shape[0]):
masks.append((b[j,:,:]))
No output, trying to solve the problem of how to fix this section.
masks=np.asarray(masks) ------------> fix the above section and this
print(len(masks)) should have no issues
[]
You are trying to load the DICOM files again using nib.load, which does not work, as you already found out:
for name in img_path:
a=nib.load(name) # does not work with DICOM files
a=a.get_data()
a=resize(a,(a.shape[0],256,256))
You already have the data from the DICOM files in the pixel_data list, so you should use these:
for a in pixel_data:
a=resize(a,(a.shape[0],256,256)) # or something similar, depending on the shape of pixel_data
...
Your last loop for mask in masks: is never executed because two lines about it you set masks = [].
It looks like it should to be for mask in mask_path:. mask_path is the list of mask file names.

How to automatically save the output image file in a specified folder?

I am using Canny edge detection on images. Since my original 10 images are in the path folder, C:\Users\X\Desktop\FoodRGB as 01.jpg, 02.jpg, 03.jpg and so on, I want to save all my output images in the folder C:\Users\X\Desktop\FoodCanny as 01.jpg, 02.jpg, 03.jpg.
I figured that I have to use imwrite() function to write the output images in a specific folder but I am not sure about the big idea.
The following code I am using is saving the images as 0%d.jpg in FoodCanny Folder I manually created.
for k = 1:10
img = sprintf('C:\Users\X\Desktop\4\Food Canny\0%d.jpg',k);
imwrite(canny_image, 'C:\Users\X\Desktop\4\Food Canny\0%d.jpg');
end
Supposing you want to get canny edges of all screenshots in the C:\Users\Asus\Pictures\Screenshots and save them to the other folder D:\. You can do this by :
clc;clear all;
fpath = fullfile('C:\Users\Asus\Pictures\Screenshots','*.png');
img_dir = dir(fpath);
for k=1:length(img_dir)
input_image=strcat('C:\Users\Asus\Pictures\Screenshots\',img_dir(k).name);
original = rgb2gray(imread(input_image));
original= edge(original,'canny');
imwrite(original,strcat('D:\',sprintf('edge(%d).jpg',k)));
end

How can I save set of altered images in new folder in MATLAB?

I have folder that consists of 10 images.
I am trying to apply a gaussian filter to each of them. I read images from a folder named dd and then I want to save the altered images in newfolder. However, when I look at the image it is empty.
How can I do this in correct way , read 10 images , filter them , save altered 10 images in new folder.
Here is the code that I have so far:
for img = 1:10
a = imread(['\dd\',int2str(img),'.pgm']);
G = fspecial('gaussian',[3 3],2);
Ig = imfilter(a,G,'same');
imshow(Ig);
imwrite( Ig, 'Ig.pgm '); % does not work !!
save ([ path,'\newfolder\', 'new.pgm'],'Ig');% it save empty image !!!
end
save is not for saving images. Instead, you will want to use imwrite for that. You will also want to provide the full path to imwrite and here we use mat2gray just to ensure that your data covers the entire dynamic range of the image type. You'll also want to be sure that each output image has a unique name so that they don't overwrite one another.
output_filename = fullfile(path, 'newfolder', sprintf('%d_new.pgm', img));
imwrite(mat2gray(Ig), output_filename, 'pgm');
As a side note, you'll want to use fullfile to reliably construct your folder paths across computers and operating systems.

Being able to read images from any directory

I'm new to Matlab and I am having some problems with reading images and dealing with directories and things like that. I had an assignment where I was to write a script that converts an image that is not grayscale into grayscale (for example, if the image is truecolor, convert to grayscale).
This was my code:
img = uigetfile('*');
imgx = imfinfo(img);
imgx.ColorType
if imgx.ColorType == 'truecolor'
img = imread(img);
img = rgb2gray(img);
end
However, I ended up getting points off for the following:
"only works if image is in the same folder as script"
I realize that my script only works for images that are in folders that are on the MATLAB path, so I don't know if that's a separate issue from what he said or if that's what he meant. I assume he wants to be able to select any image on your computer to be able to read and perform the operation, but I don't know how to approach this. Can anyone help me?
The problem is that img = uigetfile('*') returns only the file name as string. To work with pictures in folders other than matlab folder you would need to extract the full path. You can do this using the following approach:
[fileName, folderName] = uigetfile('*');
img=fullfile(folderName, fileName);
imgx = imfinfo(img);
The rest of your code should work after this small change

Dicom Images in Matlab gui

I need to make a matlab gui that reads and displays a directory of Dicom files. The gui needs to have a file menu. 2. In the File menu, there is a file Open function which can read the directory of DICOM files. I have no idea how to do this. Can someone help me with this?
Here is some code to get you going. You should absolutely follow this link and try the code provided for yourself. I think this will greatly help you for the remainder of your project and help you understand what is going on as well.
That being said, the following creates a simple figure with an axes to display images. There is also a menu with a button used to open files, in this case DICOM files (.dcm). The hardest part is taken care of my Matlab; you only need to call a function (uigetfile) in the callback of that "open" button and then call the function dicomread to read the content of a dicom file.
I'll leave the rest to you but this should help you get started.If something is unclear please don't hesitate to ask.
Code:
function DicomReadGUI
%// Create figure
hFigure = figure('Position',[200 200 600 600],'MenuBar','none', ...
'Toolbar','none','HandleVisibility','callback');
%// Add an axes just to display an image.
hAxes = axes('Position',[.1 .1 .8 .8],'Parent',hFigure);
%// Add menu in which you will add the "open" button
hFileMenu = uimenu('Parent',hFigure,'HandleVisibility','callback','Label','File');
%// Add a button to browse and open files
hOpenMenuitem = uimenu('Parent',hFileMenu,...
'Label','Open','HandleVisibility','callback', ...
'Callback', #hOpenMenuitemCallback);
%// Callback of the "open" button
function hOpenMenuitemCallback(hObject,eventdata)
%// Browse the computer and select .dcm files.
FileToRead = uigetfile('*.dcm')
[YourImage, ColorMap] = dicomread(FileToRead);
%// Display image in Axes1
imshow(YourImage,'Parent',hAxes)
end
end
And screenshot of the GUI with the button used to unroll a menu from which you can select files to open (circled in red):