利用MATLAB批量读取图像时出现名称排序错乱问题解决方法sort-nat函数

利用MATLAB批量读取图像时出现名称排序错乱问题解决方法sort-nat函数

欢迎学习交流!
邮箱: z…@1…6.com
网站: https://zephyrhours.github.io/

一、问题描述

使用MATLAB批量读取图像文件,会发现提取出来的图像名词显示错乱,并不是我们想要的排列方式。具体问题如下:
MATLAB代码如下:

clc;clear;close all;

file_path ='C:\Users\zephy\Desktop\CSDN\datasets\test';
file_list = dir(fullfile(file_path,'*.jpg'));

file_names1 = {file_list.name}';
disp('文件名称排序前:')
disp(file_names1)

该代码运行结果如下:
在这里插入图片描述

二、解决方法

这种情况下,就需要我们使用MATLAB对读取的所有的文件名进行重新排序。下面给出MATLAB社区提供的文件命名函数,具体如下:

clc;clear;close all;

file_path ='C:\Users\zephy\Desktop\CSDN\datasets\test';
file_list = dir(fullfile(file_path,'*.jpg'));

disp('文件名称排序后:')
file_names2 = sort_nat({file_list.name}');
disp(file_names2)

这里使用的sort_nat函数即名称排序整理函数,在我们默认的MATLAB函数库中一般没有该函数,因此需要我们自己定义该函数。下面是笔者找到的MATLAB社区提供的该函数,具体如下:
MATLAB社区提供的sort_nat函数

具体的源码如下,

function [cs,index] = sort_nat(c,mode)
%sort_nat: Natural order sort of cell array of strings.
% usage:  [S,INDEX] = sort_nat(C)
%
% where,
%    C is a cell array (vector) of strings to be sorted.
%    S is C, sorted in natural order.
%    INDEX is the sort order such that S = C(INDEX);
%
% Natural order sorting sorts strings containing digits in a way such that
% the numerical value of the digits is taken into account.  It is
% especially useful for sorting file names containing index numbers with
% different numbers of digits.  Often, people will use leading zeros to get
% the right sort order, but with this function you don't have to do that.
% For example, if C = {'file1.txt','file2.txt','file10.txt'}, a normal sort
% will give you
%
%       {'file1.txt'  'file10.txt'  'file2.txt'}
%
% whereas, sort_nat will give you
%
%       {'file1.txt'  'file2.txt'  'file10.txt'}
%
% See also: sort
% Version: 1.4, 22 January 2011
% Author:  Douglas M. Schwarz
% Email:   dmschwarz=ieee*org, dmschwarz=urgrad*rochester*edu
% Real_email = regexprep(Email,{'=','*'},{'@','.'})
% Set default value for mode if necessary.
if nargin < 2
	mode = 'ascend';
end
% Make sure mode is either 'ascend' or 'descend'.
modes = strcmpi(mode,{'ascend','descend'});
is_descend = modes(2);
if ~any(modes)
	error('sort_nat:sortDirection',...
		'sorting direction must be ''ascend'' or ''descend''.')
end
% Replace runs of digits with '0'.
c2 = regexprep(c,'\d+','0');
% Compute char version of c2 and locations of zeros.
s1 = char(c2);
z = s1 == '0';
% Extract the runs of digits and their start and end indices.
[digruns,first,last] = regexp(c,'\d+','match','start','end');
% Create matrix of numerical values of runs of digits and a matrix of the
% number of digits in each run.
num_str = length(c);
max_len = size(s1,2);
num_val = NaN(num_str,max_len);
num_dig = NaN(num_str,max_len);
for i = 1:num_str
	num_val(i,z(i,:)) = sscanf(sprintf('%s ',digruns{i}{:}),'%f');
	num_dig(i,z(i,:)) = last{i} - first{i} + 1;
end
% Find columns that have at least one non-NaN.  Make sure activecols is a
% 1-by-n vector even if n = 0.
activecols = reshape(find(~all(isnan(num_val))),1,[]);
n = length(activecols);
% Compute which columns in the composite matrix get the numbers.
numcols = activecols + (1:2:2*n);
% Compute which columns in the composite matrix get the number of digits.
ndigcols = numcols + 1;
% Compute which columns in the composite matrix get chars.
charcols = true(1,max_len + 2*n);
charcols(numcols) = false;
charcols(ndigcols) = false;
% Create and fill composite matrix, comp.
comp = zeros(num_str,max_len + 2*n);
comp(:,charcols) = double(s1);
comp(:,numcols) = num_val(:,activecols);
comp(:,ndigcols) = num_dig(:,activecols);
% Sort rows of composite matrix and use index to sort c in ascending or
% descending order, depending on mode.
[unused,index] = sortrows(comp);
if is_descend
	index = index(end:-1:1);
end
index = reshape(index,size(c));
cs = c(index);

运行后的结果为:

在这里插入图片描述
为了方便对比,下面给出整段代码与对比结果。具体如下:

clc;clear;close all;

file_path ='C:\Users\zephy\Desktop\CSDN\datasets\test';
file_list = dir(fullfile(file_path,'*.jpg'));

file_names1 = {file_list.name}';
disp('文件名称排序前:')
disp(file_names1)

disp('文件名称排序后:')
file_names2 = sort_nat({file_list.name}');
disp(file_names2)

运行结果如下,从下面结果,可看到明显差异,因此使用好该函数sort_nat,可在后期处理任务时起到事半功倍的效果。
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

独不懂

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值