【问题标题】:MATLAB class for loading files用于加载文件的 MATLAB 类
【发布时间】:2012-11-26 19:44:21
【问题描述】:

这里是 MATLAB 初学者。我正在尝试编写一个从文件夹加载图像的类,这就是我所拥有的:

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

我是这样称呼它的:

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

imshow(image);

这些文件被命名为 Frame0000.jpg、Frame0001.jpg ... 等。 我希望构造函数加载所有文件名,这样我就可以通过调用i.NextImage 来检索下一个文件,但我无法让它工作。


搞定了。

类:

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

呼叫:

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

imshow(image);

【问题讨论】:

    标签: matlab matlab-class


    【解决方案1】:

    AFAIK 你不能改变对象的状态(就像你在递增 currentimage 指针时所做的那样),除非最后显式更新对象本身的值。 AFAIK 每个函数调用都传递对象 byval,这意味着 NextImage 只是修改了 this 的本地副本(这不是当前对象的指针/引用,而是副本)。

    因此,您可以将方法编写为

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

    并将其称为

     [i image]=i.NextImage;
    

    【讨论】:

    • 请注意,您可以在不使用句柄对象显式回传对象的情况下实现此行为。 mathworks.com/help/matlab/ref/handle.html 虽然我发现这些使用起来非常棘手,因为尽管这些对象的行为与所有其他 MATLAB 变量的行为完全不同,但语法是相同的
    • @Pete,非常感谢您提供这些信息!确实,我在发布的代码中看到了巨大的开销;句柄,提供类似 java 的引用,绝对可以修复它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-09
    • 1970-01-01
    • 1970-01-01
    • 2010-10-16
    相关资源
    最近更新 更多