Matlab Bag of Words 图片范畴分类

来源:互联网 发布:优化发展环境调研报告 编辑:程序博客网 时间:2024/05/18 02:00

Matlab Bag of Visual Words 范畴分类

Bag of words的原理 (附opencv代码)http://blog.csdn.net/wsj998689aa/article/details/47089153

Matlab的官方教程:
https://cn.mathworks.com/help/vision/ug/image-classification-with-bag-of-visual-words.html
https://cn.mathworks.com/help/vision/examples/image-category-classification-using-bag-of-features.html
代码:
Matlab提供的代码里需要下载Caltech101数据集,下了半天才下下来。现在上传到百度云。链接:https://pan.baidu.com/s/1dFrMGvv

% % Location of the compressed data set% url = 'http://www.vision.caltech.edu/Image_Datasets/Caltech101/101_ObjectCategories.tar.gz';% % Store the output in a temporary folder% outputFolder = fullfile(tempdir, 'caltech101'); % define output folder% if ~exist(outputFolder, 'dir') % download only once%     disp('Downloading 126MB Caltech101 data set...');%     untar(url, outputFolder);% end% rootFolder = fullfile(outputFolder, '101_ObjectCategories');rootFolder='D:\TensorflowProjects\6class\101_ObjectCategories';categories = {'airplanes', 'ferry', 'laptop'};imds = imageDatastore(fullfile(rootFolder, categories), 'LabelSource', 'foldernames');tbl = countEachLabel(imds)   %计算每一个label的个数minSetCount = min(tbl{:,2}); % determine the smallest amount of images in a category 最小的图片集的个数% Use splitEachLabel method to trim the set.  每一类随机选取minSetCount个图片imds = splitEachLabel(imds, minSetCount, 'randomize');% Notice that each set now has exactly the same number of images.countEachLabel(imds)%分为验证集和训练集[trainingSet, validationSet] = splitEachLabel(imds, 0.3, 'randomize');% Find the first instance of an image for each category%读取一张图片并显示airplanes = find(trainingSet.Labels == 'airplanes', 1);ferry = find(trainingSet.Labels == 'ferry', 1);laptop = find(trainingSet.Labels == 'laptop', 1);% figuresubplot(1,3,1);imshow(readimage(trainingSet,airplanes))subplot(1,3,2);imshow(readimage(trainingSet,ferry))subplot(1,3,3);imshow(readimage(trainingSet,laptop))bag = bagOfFeatures(trainingSet);%获取视觉语义包img = readimage(imds, 1);featureVector = encode(bag, img);% Plot the histogram of visual word occurrencesfigurebar(featureVector)title('Visual word occurrences')xlabel('Visual word index')ylabel('Frequency of occurrence')categoryClassifier = trainImageCategoryClassifier(trainingSet, bag);confMatrix = evaluate(categoryClassifier, trainingSet);confMatrix = evaluate(categoryClassifier, validationSet);% Compute average accuracymean(diag(confMatrix));img = imread(fullfile(rootFolder, 'airplanes', 'image_0690.jpg'));[labelIdx, scores] = predict(categoryClassifier, img);% Display the string labelcategoryClassifier.Labels(labelIdx)