读入训练集设置标签,训练集为名字为Orange_01的文件夹,其中包含多张橘子图片,要从中提取三个特征向量,使用matlab实现
时间: 2024-03-25 18:42:08 浏览: 40
可以按照以下步骤实现:
1. 首先需要读取文件夹中的所有图片,可以使用`dir`函数获取文件夹中所有文件的信息,然后筛选出图片文件的路径。
```matlab
folder_name = 'Orange_01';
file_list = dir(folder_name);
img_list = {file_list(~[file_list.isdir]).name};
img_paths = fullfile(folder_name, img_list);
```
2. 接下来需要提取特征向量。可以使用预训练好的卷积神经网络模型来提取图片的特征向量。这里以VGG-16为例,使用`vl_simplenn`函数加载模型,然后对每张图片进行特征提取。
```matlab
net = load('imagenet-vgg-verydeep-16.mat');
feature_dim = 4096;
features = zeros(length(img_paths), feature_dim);
for i = 1:length(img_paths)
img = imread(img_paths{i});
img = imresize(img, net.meta.normalization.imageSize(1:2));
img = single(img) - net.meta.normalization.averageImage;
res = vl_simplenn(net, img);
feature = squeeze(res(end-2).x);
feature = feature(:);
features(i, :) = feature;
end
```
3. 最后需要设置标签。可以根据文件名中的信息来设置标签。这里以文件名中是否包含`good`和`bad`关键字来作为标签。
```matlab
labels = zeros(length(img_paths), 1);
for i = 1:length(img_paths)
if contains(img_list{i}, 'good')
labels(i) = 1;
elseif contains(img_list{i}, 'bad')
labels(i) = -1;
end
end
```
完整代码如下:
```matlab
folder_name = 'Orange_01';
file_list = dir(folder_name);
img_list = {file_list(~[file_list.isdir]).name};
img_paths = fullfile(folder_name, img_list);
net = load('imagenet-vgg-verydeep-16.mat');
feature_dim = 4096;
features = zeros(length(img_paths), feature_dim);
for i = 1:length(img_paths)
img = imread(img_paths{i});
img = imresize(img, net.meta.normalization.imageSize(1:2));
img = single(img) - net.meta.normalization.averageImage;
res = vl_simplenn(net, img);
feature = squeeze(res(end-2).x);
feature = feature(:);
features(i, :) = feature;
end
labels = zeros(length(img_paths), 1);
for i = 1:length(img_paths)
if contains(img_list{i}, 'good')
labels(i) = 1;
elseif contains(img_list{i}, 'bad')
labels(i) = -1;
end
end
```
阅读全文