Main Content

读取和分析图像文件

此示例说明如何为图像集合创建数据存储,读取图像文件,并找到具有最大平均色调、饱和度和亮度 (HSV) 的图像。有关使用 mapreduce 函数进行图像处理的类似示例,请参阅Compute Maximum Average HSV of Images with MapReduce

确定两个 MATLAB® 目录并创建一个数据存储,其中包含在这些目录中具有 .jpg.tif.png 扩展名的图像。

location1 = fullfile(matlabroot,'toolbox','matlab','demos');
location2 = fullfile(matlabroot,'toolbox','matlab','imagesci');

ds = imageDatastore({location1,location2},'FileExtensions',{'.jpg','.tif','.png'});

初始化最大平均 HSV 值和对应的图像数据。

maxAvgH = 0;
maxAvgS = 0;
maxAvgV = 0;

dataH = 0;
dataS = 0;
dataV = 0;

对于集合中的每个图像,读取图像文件并计算所有图像像素的平均 HSV 值。如果平均值大于先前图像的平均值,则将其记录为新的最大值(maxAvgHmaxAvgSmaxAvgV),并记录对应的图像数据(dataHdataSdataV)。

for i = 1:length(ds.Files)
    data = readimage(ds,i);     % Read the ith image    
    if ~ismatrix(data)          % Only process 3-dimensional color data        
        hsv = rgb2hsv(data);    % Compute the HSV values from the RGB data 
        
        h = hsv(:,:,1);         % Extract the HSV values
        s = hsv(:,:,2);            
        v = hsv(:,:,3);            

        avgH = mean(h(:));      % Find the average HSV values across the image
        avgS = mean(s(:));
        avgV = mean(v(:));
        
        if avgH > maxAvgH       % Check for new maximum average hue
           maxAvgH = avgH;
           dataH = data;
        end

        if avgS > maxAvgS       % Check for new maximum average saturation
           maxAvgS = avgS;
           dataS = data;
        end

        if avgV > maxAvgV       % Check for new maximum average brightness
           maxAvgV = avgV;
           dataV = data;
        end
    end
end

查看具有最大平均色调、饱和度和亮度的图像。

imshow(dataH,'InitialMagnification','fit');
title('Maximum Average Hue')

Figure contains an axes object. The axes object with title Maximum Average Hue contains an object of type image.

figure
imshow(dataS,'InitialMagnification','fit');
title('Maximum Average Saturation');

Figure contains an axes object. The axes object with title Maximum Average Saturation contains an object of type image.

figure
imshow(dataV,'InitialMagnification','fit');
title('Maximum Average Brightness');

Figure contains an axes object. The axes object with title Maximum Average Brightness contains an object of type image.

另请参阅

| |

相关主题