function [CallA,CallB,CallC,CallD,Calls] = QCallDetection(app)
Calls = cell(1,4);
pos = cell(1,4);
curtime = app.curLoadInterval*app.loadIntervalRate;
time = curtime:1:(curtime+app.loadIntervalRate);
value = app.QuailCallTemplateDropDown.Value;
if isempty(app.template) || strcmp(value,"Real Bird")
template=mat2gray(double(imread('template_combined_real_bird_2.jpg')));
else
template = app.template;
end
if strcmp(value,"Real Bird") || strcmp(value,"Import")
ceil_x = 30;
MinProm_x = 0.25;
temp_length_x = 0.5;
else
ceil_x = 10;
MinProm_x = 0.5;
temp_length_x = 2/3;
end
temp_width=size(template,1);
temp_length=size(template,2);
spec_duration = 10;
CallA = [];CallB = [];CallC = [];CallD = [];
Spectrograms = app.Spectrograms;
parfor i = 1:4
Ispec= Spectrograms{i};
if ~isempty(Spectrograms{i})
spec_len=size(Ispec,2);
spec_width=size(Ispec,1);
figure();imshow(Ispec)
band=round((spec_width-temp_width)/3);
spec_seg_size=ceil(spec_len/ceil_x);
call_candidates=[];
no_seg=ceil(spec_len/spec_seg_size)*2-1;
for s=1:no_seg
spec_seg=Ispec(band:end-band,(s-1)*ceil(spec_seg_size/2)+1:min((s-1)*ceil(spec_seg_size/2)+1+spec_seg_size,spec_len));
cc=xcorr2(spec_seg,template);
cc_signal=mat2gray(max(cc));
cc_signal=cc_signal(round(temp_length/2)-1:end-round(temp_length/2));
TF = islocalmax(cc_signal,'MinProminence',MinProm_x,'ProminenceWindow',temp_length/2);
locs=find(TF);
call=(((s-1)*ceil(spec_seg_size/2)+1)+locs)';
call_candidates=[call_candidates;call];
end
if ~isempty(call_candidates)
if length(call_candidates)>1
[L,n]=bwlabel(squareform(pdist(call_candidates))<temp_length*temp_length_x,4);
for k=1:n
[rows,~]=find(L==k);
rows=unique(rows);
spec_seg=Ispec(band:end-band,max(call_candidates(min(rows))-...
round(temp_length/2),1):min(call_candidates(min(rows))+round(temp_length/2),spec_len));
cc=xcorr2(spec_seg,template);
cc_signal=mat2gray(max(cc));
cc_signal=cc_signal(round(temp_length/2)-1:end-round(temp_length/2));
TF = islocalmax(cc_signal,'MinProminence',MinProm_x,'ProminenceWindow',temp_length/2);
location=find(TF);
if call_candidates(min(rows)) <round(temp_length/2)
call=(time(1)+(spec_duration/spec_len)*location);
Calls{i}=[Calls{i};call'];
else
call=(time(1)+(spec_duration/spec_len)*(call_candidates(min(rows))+location-round(temp_length/2)));
Calls{i}=[Calls{i};call'];
end
end
else
spec_seg=Ispec(band:end-band,max(call_candidates(1)-round(temp_length/2),1):min(call_candidates(1)+round(temp_length/2),spec_len));
cc=xcorr2(spec_seg,template);
cc_signal=mat2gray(max(cc));
cc_signal=cc_signal(round(temp_length/2)-1:end-round(temp_length/2));
TF = islocalmax(cc_signal,'MinProminence',MinProm_x,'ProminenceWindow',temp_length/2);
location=find(TF);
if call_candidates(1) <round(temp_length/2)
call=(time(1)+(spec_duration/spec_len)*location)';
Calls{i}=[Calls{i};call'];
else
call=(time(1)+(spec_duration/spec_len)*(call_candidates(1)+location-round(temp_length/2)));
Calls{i}=[Calls{i};call'];
end
end
end
end
end