MATLAB-Stuff

Code and other snippets

Write a multipage TIFF

for i=1:100
    a(:,:,i)=rand(256);
    imwrite(a(:,:,i),'file.tif', 'writemode', 'append')
end
size(a)

Adapted from this MATLAB support question. Generates a random 256×256 pixel large image, saves it in the ith slice of a while looping through i. In the same loop MATLAB writes the slice to a tif-File with the 'append' write mode, resulting in a random tif-File with a size of 256x256x100 pixels.

start matlab headless with some file

cd filepath
matlab -r file (WITHOUT .m extension!)

turn off warning about big images

warning off Images:initSize:adjustingMag

Overlay Image over another one

Img = imnoise(phantom(64));   % Load 64 pixel wide Phantom and make it noisy
Threshold = graythresh(Img);  % calculate Otsu-Threshold
BW = im2bw(Img,Threshold );   % binarize with above Threshold
 
Color = [155 188 221] % define overlay colour RGB (this is the unibe-presentation color)
 
Img = im2uint8(mat2gray(Img)); % separate image into 3 channels
red = Img;
green = Img;
blue = Img;
 
red(BW) = Color(1);    % populate channels with thresholded image
green(BW) = Color(2);
blue(BW) = Color(3);
 
Overlay = cat(3, red, green, blue); % make RGB-image
 
figure % display everything
    subplot(131)
        imshow(Img,[])
        title('Original')
    subplot(132)
        imshow(BW,[])
        title(['Thresholded with: ' num2str(intmax(class(Img))*Threshold) ]); % see http://www.ana.unibe.ch/~haberthuer/matlab#threshold_image 
    subplot(133)    
        imshow(Overlay,[])
        title('Overlay')

adapted from upslope area functions

Threshold Image

And return Human-readable Threshold

Img = imread('rice.png');       % read Image
Threshold = graythresh(Img);    % calculate Otsu Threshold of Image   
BW = im2bw(Img,Threshold);      % Threshold Image
Bitdepth = intmax(class(Img));  % Get Bitdepth of Image
disp(['Image has been thresholded with ' num2str(Threshold) ' (grayvalue: ' num2str(Bitdepth*Threshold) ')' ]);
figure
    subplot(121)
        imshow(Img)
        title('Original')
    subplot(122)
        imshow(BW)
        title(['Thresholded with: ' num2str(Bitdepth*Threshold) ])

Select Components in a (thresholded) Image

BW = imread('rice.png');        % Load Image
BW = im2bw(BW,graythresh(BW));  % Threshold Image with Otsu
 
% inform user
wait=helpdlg('Select rice corns in the picture. Stop with right mouse button','Corn Selection');
uiwait(wait)
 
% open figure (bwselect outputs figure to screen, so we put it in a subplot
% to start with. when right mouse button is pressed, right figure is updated
figure;
    subplot(121)
        BW2 = bwselect(BW);
    subplot(122)
        imshow(BW2)