在 MatLab 中,如何从单元格数组创建字符向量?



我显然无法区分不同类型的向量和数组以及字符串、单元格、字符等命令。我的代码在另一个网络上,但基本上,我收到一个错误,说我的 imread 语句中的参数必须是字符向量。参数是一个 1x30 的文件名数组,是一个单元格数组,因为我使用了 iscell 命令并且它返回了一个 1。我已经尝试了上面列出的命令的几个组合,并且一直在阅读我能阅读的所有内容,但无法确定如何将 1x30 单元格数组更改为字符向量,以便 imread 语句起作用。文件名从文件夹(使用 uigetfile(读入为 757-01.bmp、757-02.bmp ...757-30.bmp.我想我需要将它们设为"757-01.bmp"、"757-02.bmp"......'757-30.bmp",并可能变成 30x1 矢量副 1x30?或者,对于代码接下来会遇到的 for 循环来说,这并不重要..?感谢您的任何帮助...

[imagefiles,file_path]=uigetfile({'*.jpeg;*.jpg;*.bmp;*.tif;*.tiff;*.png;*.gif','Image Files (JPEG, BMP, TIFF, PNG and GIF)'},'Select Images','multiselect','on');
imagefiles = cellstr(imagefiles);
imagefiles = sort(imagefiles);
nfiles = length(imagefiles);
r = inputdlg('At what pixel row do you want to start the cropping?        .','Row');
r = str2num(r{l});
c = inputdlg('At what pixel column do you want to start the cropping (Must be > 0)?        .','Column');
c = str2num(c{l});
h = inputdlg('How many pixel rows do you want to include in the crop?        .','Height');
h = str2num(h{l});
w = inputdlg('How many pixel columns do you want to include in the crop?        .','Width');
w = str2num(w{l});
factor = inputdlg('By what real number factor do you want to enlarge the cropped image?        .','Factor');
factor = str2num(factor{l});
outdimR = h * factor;
outdimC = w * factor;
for loop=l:nfiles
filename = imagefiles(loop);
[mybmp, map] = imread(filename);
myimage = ind2rgb(mybmp,map);
crop = myimage(r:r+h-1, c:c+w-1, :);
imwrite(crop, sprintf('crop757-%03i.bmp',loop));
end

关于你最初的问题:

在 MatLab 中,如何从单元格数组创建字符向量?

您可以使用单元格访问器操作数 ({}( 从单元格中获取字符串,如 @ben-voight 指出的那样,或者将char()括在您的语句周围(我会同意 Ben 的建议(。

关于您的后续问题:

它在 imread 时出错,说文件"757-01.bmp"不存在。在 imagefiles 数组中,30 个值中的第一个是 757-01.bmp(没有引号(,但我不知道 MatLab 在文件名周围加上引号是否意味着它在数组中寻找带引号的值。

听起来您的文件位于另一个目录中,而不是您从中运行代码的目录。

使用fullfile 创建完整文件名以使用文件的绝对路径而不是相对路径(此处不起作用(。

假设您的文件位于路径~/bpfreefly/images/中。

然后你可以像这样更改你的代码:

imgPath = '~/bpfreefly/images/'
for loop=l:nfiles
filename = fullfile(imgPath,imagefiles{loop});
[mybmp, map] = imread(filename);
myimage = ind2rgb(mybmp,map);
crop = myimage(r:r+h-1, c:c+w-1, :);
imwrite(crop, sprintf('crop757-%03i.bmp',loop));
end

顺便说一下,你可以从uigetfile的第二个输出参数中获取路径名。

最新更新