Image Representation in Octave / MATLAB


Some Basics & a bit of terminology:
An image of m, n dimensions obviously consists of M rows and N columns and can be defined as a 2D function f(x,y).

Similarly we can represent an image in MATLAB thought an M x N matrix where f(1,1) in MATLAB would represent the f(0,0) pixel value of the actual image, resulting in an array of the form:

A matrix of size 1 x N is called a row vector.
A matrix of size N x 1 is called a column vector.
A matrix of size 1 x 1 is called a scalar.

Reading an image in MATLAB:

In the following scenario, we are loading a jpg image. By definition the JPG image type means that the image carries 3 greyscale images, one for each RGB color.

MATLAB
img = imread('ds.jpg');

[M,N,O] = size(img)
R = size(img, 1)
whos img 
OUTPUT
M = 3088
N = 2316
O = 3

R = 3088

Variables visible from the current scope:
variables in scope: top scope
  Attr   Name        Size                     Bytes  Class
  ====   ====        ====                     =====  ===== 
         img      3088x2316x3              21455424  uint8
Total is 21455424 elements using 21455424 bytes

So if we check its size property, on line3, MATLAB returns 3 separate values. One for the row pixels (M, height of the image), one for the columns (N, width) and a 3rd one (O) with the number of channels. Size accepts another parameter for cases where we need to explicitly access a specific image dimension, as shown on line 4. Finally, using the whos method, we can get additional information on that JPG file.

MATLAB
imfinfo('ds.jpg')

iminfo can reveal a lot more from an image’s EXIF data, like the GPS coordinates.

Showing an image in MATLAB:

MATLAB
img = imread('ds.jpg');
imshow(img)
figure, imshow(img)

imshow can be used to show the matrix/image. When used again, MATLAB will replace the current window with the second image. In order to open it on a new window, figure can be used as shown on line 3.

Writing an image in MATLAB:

MATLAB
imwrite(img, 'myNewIMG.jpg', 'quality', 100)

imwrite can be used to write a matrix into an image file on disk. Beside parameters for the matrix object and the file name (including the needed file extension), in case of writing a JPG, additional / optional parameters are provided like the quality. It ranges from 0 to 100 and it degrades the JPG compression (higher the better). TIFF has the type parameter that sets the compression method, etc.