对于涉及
plot
和 ginput
的非常简单但乏味且耗时的界面,我需要某种并行化:当用户决定并选择其输入时,正在加载和处理图像。
由于带有
parfor
batch
的 Matlab 并行工作器在图形上是静音的,是否有一些解决方法可以实现这一点?,而不需要实际打开两个不同的 Matlab 命令行实例并处理之后的混乱?
你尝试过 parfeval 功能吗?它在Matlab中提供异步操作
https://uk.mathworks.com/help/distcomp/parfeval.html
不是理想的解决方案,但它会起作用。
clc
clear
close all
format compact
p = gcp;
I = imread('peppers.png');
f = figure;
[h,w,c] = size(I);
imshow(I);
k = 0;
while true
[xb,yb,button] = ginput(1);
if button == 3
% If mouse right button was clicked brake the loop
break
else
% For other button add job to the cue
xe = xb+99;
xe(xe>w) = w;
ye = yb+99;
ye(ye>h) = h;
Imini = I(yb:ye,xb:xe,:);
filt = fspecial('motion', 50, 45);
ff(k+1) = parfeval(p,@imfilter,1,Imini,filt);
k = k +1;
end
% Check the cue for finished jobs and get output.
idx = [];
for k = 1:length(ff)
if strcmp(ff(k).State,'finished')
idx(k) = 1;
Ifilt = ff(k).OutputArguments{1};
figure; imshow(Ifilt);
else
idx(k) = 0;
end
end
% Remove finished jobs from cue
idx = logical(idx);
ff(idx) = [];
set(0, 'currentfigure', f);
end
更好的解决方案可以使用figure WindowButtonDownFcn方法将作业添加到parfeval提示和WindowButtonMotionFcn来检查提示是否已完成作业。
我提出了一个“类似的解决方案”来并行执行某些操作,然后受限于单个进程。在本例中,这是数据库写入。我不太确定您需要什么类型的输入,但这可能对您有帮助。
注意您可能需要放置一些控制逻辑来暂停,控制图形可见性,以免淹没您的用户。所有这些都可以放入一个函数中并在 afterEach
上执行。
clearvars
close all
% wrap the user input section in a function
f = @(ax) disp(ax.Title.String);
% set up a data que
q = parallel.pool.DataQueue;
% do something after each arrives.
afterEach(q, f);
parfor k = 1 : 10
name = "My Fig " + num2str(k);
% loading the figure
f = figure;
ax = gca;
title(ax, name);
% send back to client for their input
send(q,ax);
end