2015-11-13 110 views
1

我是新來的matlab和圖像分析。我非常感謝以下問題的一些見解/幫助。我正嘗試將具有隨機名稱的文件夾中的圖像(jpg)重命名爲特定(新)名稱。我做了一個帶有兩列的excel文件,第一列包含舊名稱,第二列包含新名稱。我發現堆棧溢出的下一個代碼(Rename image file name in matlab):在matlab中重命名JPG圖像

dirData = dir('*.jpg');   %# Get the selected file data 
fileNames = {dirData.name};  %# Create a cell array of file names 
for iFile = 1:numel(fileNames) %# Loop over the file names 
    newName = sprintf('image%05d.jpg',iFile); %# Make the new name 
    movefile(fileNames{iFile},newName);  %# Rename the file 
end 

的代碼給所有的相關的照片基礎上,舊的新名稱,但是這不是我想要的,我用的都是不鏈接到新名稱舊的。我試了下面的代碼:

g= xlsread('names.xlsx') % names.xlsx the excel file with old and new names  
for i=1:nrows(g) 
image=open(g(i,1)); 
save(g(i,2),image); 
end 

它不起作用。我收到錯誤消息:using open(line 68) NAME必須包含單個字符串。我不認爲開放是正確的功能使用。

謝謝!

+1

爲什麼不創建一個單元陣列相同的大小'fileNames'與相應的新名字? – beaker

+0

如果不是字符串,g(i,1)是什麼?另外爲什麼不'movefile(g(i,1),g(i,2))'? – Sean

+0

也許我不明白你的建議。圖像在目錄中以隨機順序排列,新名稱必須專門分配給正確的「舊」圖像。如果我使用此代碼,它將按照目錄中的順序將新文件名分配給圖像。這不是正確的任務。 – YV3003

回答

0

如何:

% Get the jpeg names 
dir_data = dir('*.jpg'); 
jpg_names = {dir_data.name}; 

% Rename the files according to the .xlsx file 
[~,g,~] = xlsread('names.xlsx'); % Thanks to the post of Sean 
old_names = g(:,1); 
new_names = g(:,2); 

for k = 1:numel(old_names) 
     % check if the file exists 
     ix_file = strcmpi(old_names{k}, jpg_names); 
     if any(ix_file) 
       movefile(old_names{k}, new_names{k}); 
     end; 
end; 
+0

@ YV3003在Excel文件的舊文件列中是否有重複項?另外,第一列是舊文件名的列嗎? – 2015-11-13 21:53:39

+0

謝謝你的工作!位於MATLAB文件夾內的文件夾內的圖像。這是造成錯誤的原因。 – YV3003

+0

@ YV3003那麼選擇我的答案作爲正確的答案會很好。 :-) – 2015-11-13 21:56:34

0

看起來好像g = xlsread(file)只從file(參見here)讀取數字數據。 xlsread的第三個輸出參數返回包含字符串的原始數據;做了以下工作? (我沒有Excel,不能進行測試)

[~, ~, g] = xlsread('names.xlsx') 
for i = 1:nrows(g) 
    movefile(g{i,1}, g{i,2}) 
end