You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用parfor计算图像中位数时出现内存不足错误,求解决方案

时序图像中位数计算的parfor内存溢出问题解决建议

我需要计算一系列图像的中位数图像,其中tableau4D是时序图像数组,维度为tableau4D(pixel_x, pixel_y, value_grayscale, time t)。图像数量较多,尝试用parfor循环提速时触发内存不足错误,换成普通for循环可正常运行。

原代码

% Calcul mediane serie image
function Io_mediane = median_images(tableau4D)
    %Io_mediane = median(tableau4D, 4);
    % Calcul taille du tableau
    [m,n,c,nombre_images] = size(tableau4D);

    % init temp
    Io_med_temp = zeros(m,n,c,nombre_images);

    parfor i = 1:nombre_images %parfor bug 
        Io_med_temp(:,:,:,i) = medfilt2(tableau4D(:,:,:,i));
    end
    Io_mediane = mean(Io_med_temp,4);
end 

错误信息

Starting parallel pool (parpool) using the 'Processes' profile ...
Connected to parallel pool with 20 workers.
Warning: X does not support locale fr_FR.utf8
Error using post>median_images/parfor%supply_3
Out of memory.

Error in post>median_images (line 195)
    parfor i = 1:nombre_images %parfor bug

Error in post (line 33)
Io_mediane = median_images(Io_land);
 
Starting parallel pool (parpool) using the 'Processes' profile ...
Parallel pool using the 'Processes' profile is shutting down.

解决建议

  • 取消预分配超大临时数组:原代码预分配了与原始数组同尺寸的Io_med_temp,parfor下每个工作进程会复制部分数据,叠加临时数组的内存占用直接触发溢出。改为边计算边累加,无需存储所有中间结果:
    function Io_mediane = median_images(tableau4D)
        [m,n,c,nombre_images] = size(tableau4D);
        Io_mediane = zeros(m,n,c);
        
        parfor i = 1:nombre_images
            temp = medfilt2(tableau4D(:,:,:,i));
            % 原子操作累加,避免竞态条件
            Io_mediane = Io_mediane + temp;
        end
        Io_mediane = Io_mediane / nombre_images;
    end
    
  • 减少工作进程数量:当前启用了20个worker,每个worker都需要分配内存处理数据。可手动指定worker数量(建议设为CPU核心数的一半,根据自身内存情况调整),降低并发内存占用:
    parpool('Processes', 8); % 示例:设置为8个worker
    
  • 核对计算逻辑:原代码先对单帧做medfilt2(空间中值滤波)再求时序均值,若需求是每个像素在时序上的中位数,直接使用median(tableau4D, 4)更高效,无需循环,内存占用也更低。
  • 分块处理大图像:若图像尺寸极大,可将图像分割为小块,分块处理后拼接结果,进一步降低单进程的内存负载。

内容的提问来源于stack exchange,提问作者Suntory

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 22:46:21