Here is the implementation for MATLAB function that I use to average Quaternions for orientation estimation.It is straightforward to convert the MATLAB to any other language, except that this particular method (Markley 2007) requires the calculation of the eigenvectors and eigenvalues. There are many libraries (including Eigen C++) that can do this for you.
You can read the description/header of the file to see the math from the original paper.
matlab file taken from http://www.mathworks.com/matlabcentral/fileexchange/40098-tolgabirdal-averaging-quaternions :
% by Tolga Birdal% Q is an Mx4 matrix of quaternions. weights is an Mx1 vector, a weight for% each quaternion.% Qavg is the weightedaverage quaternion% This function is especially useful for example when clustering poses% after a matching process. In such cases a form of weighting per rotation% is available (e.g. number of votes), which can guide the trust towards a% specific pose. weights might then be interpreted as the vector of votes % per pose.% Markley, F. Landis, Yang Cheng, John Lucas Crassidis, and Yaakov Oshman. % "Averaging quaternions." Journal of Guidance, Control, and Dynamics 30, % no. 4 (2007): 1193-1197.function [Qavg]=quatWAvgMarkley(Q, weights)% Form the symmetric accumulator matrixA=zeros(4,4);M=size(Q,1);wSum = 0;for i=1:M q = Q(i,:)'; w_i = weights(i); A=w_i.*(q*q')+A; % rank 1 update wSum = wSum + w_i;end% scaleA=(1.0/wSum)*A;% Get the eigenvector corresponding to largest eigen value[Qavg, ~]=eigs(A,1);end