0

I wrote a code in matlab to extract a famous pre-trained neural network features from my dataset:

list_of_images_names = dir("./imagenet_fall2011_oneImagePerCat_21-2k_20230309");
n_images = length(list_of_images_names);

n_feat_selection = 1000; %select 1000 random features from the network
%%
net = alexnet; 
sz = net.Layers(1).InputSize;

faild = []

%%
dictionary_imagenames_features = dictionary();
layers_to_extract = ["conv2", "conv4", "fc6", "fc8"];

for j= 1:length(layers_to_extract)
    dictionary_imagenames_features = dictionary();
    dictionary_name = "imgnet19k_less_feature_map_20230412_alexnet_" + layers_to_extract(j) + "_dict.mat";

    for i= 1:length(list_of_images_names);
        %I = imread("./imagenet_fall2011_oneImagePerCat_21-2k_20230309" + list_of_images_names(i))
        if(i==1 | i==2)
            continue;
        end
        
        try
            image_dir = "./imagenet_fall2011_oneImagePerCat_21-2k_20230309/" + list_of_images_names(i).name;
            I = imread(image_dir);
            I = imresize(I, sz(1:2)); %resize the image to the input size of the network
        
            features = activations(net, I, layers_to_extract(j));
            features = squeeze(features);
            features = features(:);
            
            feat_size = numel(features);
            features_1000 = features(randperm(feat_size, n_feat_selection));
        
            dictionary_imagenames_features(list_of_images_names(i).name) = {features_1000};
        catch
            failed = [failed, list_of_images_names(i).name];
        end
        
    
    end
    save(dictionary_name, "dictionary_imagenames_features");
end

So I save these as

.mat

files.

Then I try to read them in python:

annots = loadmat(normal_semantic_features_dir + 'cnn2_keys_in_order_imagenet_19k_v2.mat')

for k, v in annots.items():
    print(k,"........" ,annots[k])
    print("....")

and answer is:

__header__ ........ b'MATLAB 5.0 MAT-file, Platform: PCWIN64, Created on: Fri Apr 14 13:32:47 2023'
....
__version__ ........ 1.0
....
__globals__ ........ []
....
None ........ [(b'keys_in_order', b'MCOS', b'string', array([[3707764736],
       [         2],
       [         1],
       [         1],
       [         1],
       [         1]], dtype=uint32))]
....
__function_workspace__ ........ [[ 0  1 73 ...  0  0  0]]
....

I wonder how to get access to the elements, and convert it to a python dictionary.

Thank you very much.

Kadaj13
  • 1,423
  • 3
  • 17
  • 41
  • Does this answer your question? [Read .mat files in Python](https://stackoverflow.com/questions/874461/read-mat-files-in-python) – buran Apr 14 '23 at 06:49

0 Answers0