特定の画像ファイル名​の表示、分類されたイ​メージ表示の方法

6 views (last 30 days)
Kohei 
Kohei  on 7 Jan 2022
Edited: Kohei  on 10 Jan 2022
初歩的な質問ですみません、質問が2つあります。現在、目の画像で病気別の多クラス分類を行っています。
https://jp.mathworks.com/help/deeplearning/ug/train-deep-learning-network-to-classify-new-images.htmlを参考に、テスト用画像のラベル予測と[ ]に正解(その画像が持つ)ラベル、予測確立を表示させています(下図)。
figure;
for i = 1:6
subplot(2,3,i)
I = readimage(imds,perm(i));
imshow(I)
label = testcted_labels(perm(i));
title(string(label) + "[ " +string(imds.Labels(perm(i))) + "]" + "," + "確率予測" + num2str(100*max(posterior(perm(i),:)),3) + "%")
end
Unrecognized function or variable 'imds'.
ここに、画像自体のファイル名(例:001.jpg)を画像下に追加するにはどうすればよいでしょうか。
②学習を行い、分類されたテスト用画像で混同行列をプロットしています。
figure;
plotconfusion(imds.Labels,testcted_labels');
title('Confusion:Testdata');
この場合、どの画像が何に分類されたのかを確認したいので、分類された中身の画像を表示するコード方法がありましたらお教えください。
*追記
全体のソースコードを記載しておきます。
を参考に5分割交差検証を行っています。
5分割されたデータセットのうち、3分割を学習用、1分割を検証用、1分割をテスト用としています。
テスト用データの評価は、①のラベル予測などを参考にしています。よろしくお願いいたします。
%% フォルダパスの指定
% test画像が保存されるフォルダパスの指定
trainDatasetPath = fullfile('fvggs');
% ラベル付与と画像データの格納
imds = imageDatastore(trainDatasetPath, ...
'IncludeSubfolders',true,'LabelSource','foldernames');
% 分類を確認
total_split=countEachLabel(imds);
% 画像の長さ
num_images=length(imds.Labels);
% 画像の表示
perm=randperm(num_images,6);
figure;
for idx=1:length(perm)
subplot(2,3,idx);
imshow(imread(imds.Files{perm(idx)}));
title(sprintf('%s',imds.Labels(perm(idx))))
end
%% k-分割交差検証
% Number of folds
num_folds=5;
% Loop for each fold
for fold_idx=1:num_folds
%%
fprintf('Processing %d among %d folds \n',fold_idx,num_folds);
% Validation Indices for current fold
val_idx=fold_idx:num_folds :num_images;
% Validation cases for current fold
imdsValidation = subset(imds,val_idx);
% Test Indices for current fold
test_idx=fold_idx+1:num_folds :num_images;
% Test cases for current fold
imdsTest = subset(imds,test_idx);
% Train indices for current fold
Atrain_idx=setdiff(1:length(imds.Files),val_idx);
train_idx = setdiff(Atrain_idx,test_idx);
% Train cases for current fold
imdsTrain = subset(imds,train_idx);
%% ネットワークの呼び出し
% ResNet Architecture
net=vgg16;
% 最終層の変更
if isa(net,'SeriesNetwork')
lgraph = layerGraph(net.Layers);
else
lgraph = layerGraph(net);
end
inputSize = net.Layers(1).InputSize;
classes = net.Layers(end).Classes;
%{
clear net;
%}
%% 変更層の検索
[learnableLayer,classLayer] = findLayersToReplace(lgraph);
[learnableLayer,classLayer];
%% 全結合層の変更
% Number of categories
numClasses = numel(categories(imdsTrain.Labels));
if isa(learnableLayer,'nnet.cnn.layer.FullyConnectedLayer')
newLearnableLayer = fullyConnectedLayer(numClasses, ...
'Name','new_fc', ...
'WeightLearnRateFactor',10, ...
'BiasLearnRateFactor',10);
elseif isa(learnableLayer,'nnet.cnn.layer.Convolution2DLayer')
newLearnableLayer = convolution2dLayer(1,numClasses, ...
'Name','new_conv', ...
'WeightLearnRateFactor',10, ...
'BiasLearnRateFactor',10);
end
lgraph = replaceLayer(lgraph,learnableLayer.Name,newLearnableLayer);
newClassLayer = classificationLayer('Name','new_classoutput');
lgraph = replaceLayer(lgraph,classLayer.Name,newClassLayer);
% 初期層の凍結
layers = lgraph.Layers;
connections = lgraph.Connections;
layers(1:10) = freezeWeights(layers(1:10));
lgraph = createLgraphUsingConnections(layers,connections);
pixelRange = [-30 30];
scaleRange = [0.9 1.1];
imageAugmenter = imageDataAugmenter( ...
'RandXReflection',true, ...
'RandXTranslation',pixelRange, ...
'RandYTranslation',pixelRange, ...
'RandXScale',scaleRange, ...
'RandYScale',scaleRange);
augimds = augmentedImageDatastore(inputSize(1:2),imdsTrain, ...
'DataAugmentation',imageAugmenter);
augvalimds = augmentedImageDatastore(inputSize(1:2),imdsValidation);
augtestimds = augmentedImageDatastore(inputSize(1:2),imdsTest);
%% ネットワークの設定
options = trainingOptions('adam',...
'MaxEpochs',60,'MiniBatchSize',128,...
'Shuffle','every-epoch', ...
'InitialLearnRate',1e-4, ...
'ValidationData',augvalimds, ...
'ValidationFrequency',10, ...
'Verbose',false, ...
'Plots','training-progress');
% 学習
netTransfer = trainNetwork(augimds,lgraph,options);
%%
% 各ケースのテストとそれに対応するラベル及び%
[testcted_labels(test_idx),testerior(test_idx,:)] = classify(netTransfer,augtestimds);
[predicted_labels(val_idx),posterior(val_idx,:)] = classify(netTransfer,augvalimds);
% フォールドごとに取得した独立したvgg16アーキテクチャを保存
save(sprintf('vgg16_%d_among_%d_folds',fold_idx,num_folds),'netTransfer','val_idx','train_idx','test_idx');
% 不要な変数のクリア
clearvars -except fold_idx num_folds num_images predicted_labels posterior testcted_labels testerior imds netTransfer;
end
%% Validationデータとの予測結果
% 実際のラベル
actual_labels=imds.Labels;
% 混合行列 
figure
plotconfusion(actual_labels,predicted_labels');
title('Confusion:Validationdata');
%% Testデータとの予測結果
num_images=length(imds.Labels);
perm=randperm(num_images,10);
%テストイメージでの混合行列
figure;
plotconfusion(imds.Labels,testcted_labels');
title('Confusion:Testdata');
% テストイメージの予測
figure;
for i = 1:6
subplot(2,3,i)
I = readimage(imds,perm(i));
imshow(I)
label = testcted_labels(perm(i));
title(string(label) + " [" +string(imds.Labels(perm(i))) + "]" + " , " + " 予測確率" + num2str(100*max(posterior(perm(i),:)),3) +"%")
end
%% ROC曲線
test_labels=double(nominal(imds.Labels));
[fp_rate,tp_rate,T,AUC]=perfcurve(test_labels,posterior(:,1),1);
figure;
plot(fp_rate,tp_rate,'b-');
grid on;
xlabel('偽陽性率');
ylabel('真陽出率');
% AUCの下の面積
AUC

Answers (1)

Atsushi Ueno
Atsushi Ueno on 9 Jan 2022
①画像自体のファイル名(例:001.jpg)を画像下に追加するにはどうすればよいでしょうか
画像ファイル名(フルパス)はセル配列としてイメージデータストア内(imds.Files)に格納されています。fileparts関数でパス・ファイル名・拡張子を分離します。画像の下にテキストを表示する為xlabel関数を用いました。表示位置や表示形式に拘るならばtext関数の方が適すると思います。
folder_name = pwd;
imds = imageDatastore(folder_name);
for i = 1:2
[folder, FileName, ext] = fileparts(imds.Files{i}); % imds.Filesで抽出、fileparts関数でファイル名を分離
subplot(1,2,i); imshow(readimage(imds,i));
xlabel([FileName, ext],'Interpreter','none'); % ファイル名を表示、オプションはLateX形式表示をキャンセルする為
end
  2 Comments
Atsushi Ueno
Atsushi Ueno on 9 Jan 2022
動作確認していませんが、下記2行の追加で表示されると思います。
figure;
for i = 1:6
subplot(2,3,i)
I = readimage(imds,perm(i));
imshow(I)
label = testcted_labels(perm(i));
title(string(label) + "[ " +string(imds.Labels(perm(i))) + "]" + "," + "確率予測" + num2str(100*max(posterior(perm(i),:)),3) + "%")
[folder, FileName, ext] = fileparts(imds.Files{perm(i)}); % 追加
xlabel([FileName, ext]); % 追加
end
Kohei 
Kohei  on 10 Jan 2022
Edited: Kohei  on 10 Jan 2022
コメントありがとうございます。追加したコードで無事に画像ファイル名を表示することができました。
②につながる質問なのですが、①は全テスト用画像1470枚のうち、ランダムに6枚を表示していました。
全テスト画像をこの6枚の表示のように、1つのウインドウでなくてもよいので、どう分類されているのか表示する、もしくは特定のラベル(例:Fineと正しく分類された)画像を表示するには
上記figureを元に、どう変更すればよいのか教えていただけると幸いです。

Sign in to comment.

Products


Release

R2020b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!