我有一个包含10个子文件夹的文件夹,每个文件夹包含大约100个不同的文件,包括文本文件和不同的扩展图像。我只需要用JPG扩展名复制图像文件并将其移动到另一个文件夹。
我正在使用此代码:
clear all
clc
M_dir = 'X:\Datasets to be splitted\Action3\Action3\'% source directory
D_dir = 'X:\Datasets to be splitted\Action3\Depth\'
files = dir(M_dir);% main directory
dirFlags = [files.isdir];
subFolders = files(dirFlags);%list of folders
for k = 1 :length(subFolders)
if any(isletter(subFolders(k).name))
c_dtry = strcat(M_dir,subFolders(k).name)
fileList = getAllFiles(c_dtry)%list of files in subfolder
for n1 = 1:length(fileList)
[pathstr,name,ext] = fileparts(fileList{n1})% file type
%s = dir(fileList{n1});
%S = s.bytes/1000;%file size
Im = imread(fileList{n1});
%[h,w,d] = size(Im);%height width and dimension
if strcmp(ext,'.jpg')|strcmp(ext,'.JPG')%)&S>=50&(write image dimension condition))% here you need to modify
baseFileName = strcat(name,ext);
fullFileName = fullfile(D_dir, baseFileName); % No need to worry about slashes now!
imwrite(Im, fullFileName);
else
end
end
end
end
但正在处理文本文件时,代码会因错误而停止。
错误说:
Error using imread>get_format_info (line 491)
Unable to determine the file format.
Error in imread (line 354)
fmt_s = get_format_info(fullname);
Error in ReadFromSubFolder (line 16)
Im = imread(fileList{n1});
由于
答案 0 :(得分:2)
在检查扩展名
之前,您的代码正在读取数据Im = imread(fileList{n1});
之前
if strcmp(ext,'.jpg')|strcmp(ext,'.JPG')
修改强>
要查找以'vis'结尾的文件,您可以使用strcmp
strcmp ( name(end-2:end), 'vis' )
为完整起见,您还应检查名称是否超过3个字符。
答案 1 :(得分:0)
以下是使用dir
和movefile
或copyfile
的相对简单的解决方案,具体取决于您是要移动还是复制:
%searching jpg files in all subdirectories of 'X:\Datasets to be splitted\Action3\Action3'
file = dir('X:\Datasets to be splitted\Action3\Action3\**\*.jpg');
filenames_with_path = strcat({file.folder},'\',{file.name});
destination_dir = 'X:\Datasets to be splitted\Action3\Depth\';
%mkdir(destination_dir); %create the directory if it doesn't exist
for k=1:length(filenames_with_path)
movefile(filenames_with_path{k}, destination_dir, 'f'); %moving the files
%or if you want to copy then: copyfile(filenames_with_path{k}, destination_dir, 'f');
end