Eamonn McEvoy
Eamonn McEvoy

Reputation: 8986

MATLAB class for loading files

Beginner with MATLAB here. I'm trying to write a class that will load in images from a folder, and here's what I have:

classdef ImageLoader
    %IMAGELOADER Summary of this class goes here
    %   Detailed explanation goes here

    properties
        currentImage = 0;
        filenames={};
        filenamesSorted={};
    end

    methods
        function imageLoader = ImageLoader(FolderDir)
            path = dir(FolderDir);
            imageLoader.filenames = {path.name};
            imageLoader.filenames = sort(imageLoader.filenames);
        end

        function image = CurrentImage(this)
            image = imread(this.filenames{this.currentImage});
        end

        function image = NextImage(this)
            this.currentImage = this.currentImage + 1;
            image = imread(this.filenames{this.currentImage});
        end
    end    
end

This is how I'm calling it:

i = ImageLoader('football//Frame*');
image=i.NextImage;

imshow(image);

The files are named Frame0000.jpg, Frame0001.jpg ... etc. I want the constructor to load in all the file names so that I can then retrieve the next file simply by calling i.NextImage, but I can't get it working.


Got it working.

class:

classdef ImageLoader
    %IMAGELOADER Summary of this class goes here
    %   Detailed explanation goes here

    properties(SetAccess = private)
        currentImage
        filenames
        path
        filenamesSorted;
    end

    methods
        function imageLoader = ImageLoader(Path,FileName)
            imageLoader.path = Path;
            temp = dir(strcat(Path,FileName));
            imageLoader.filenames = {temp.name};
            imageLoader.filenames = sort(imageLoader.filenames);
            imageLoader.currentImage = 0;
        end

        function image = CurrentImage(this)
            image = imread(this.filenames{this.currentImage});
        end

        function [this image] = NextImage(this)
            this.currentImage = this.currentImage + 1;
            image = imread(strcat(this.path,this.filenames{this.currentImage}));
        end
    end    
end

call:

i = ImageLoader('football//','Frame*');
[i image]=i.NextImage;

imshow(image);

Upvotes: 1

Views: 184

Answers (1)

Acorbe
Acorbe

Reputation: 8391

AFAIK you can't change the state of an object (as you do when incrementing the currentimage pointer) without explicitly updating the value of the object itself at the end. AFAIK every function call passes objects byval, that means that NextImage just modifies a local copy of this (which is not a pointer/reference to the current object, rather a copy).

Thus, what you can do is writing your method as

  function [this image] = NextImage(this)
        this.currentImage = this.currentImage + 1;
        image = imread(this.filenames{this.currentImage});
  end

and call it as

 [i image]=i.NextImage;

Upvotes: 1

Related Questions