plateform
stringclasses
1 value
repo_name
stringlengths
13
113
name
stringlengths
3
74
ext
stringclasses
1 value
path
stringlengths
12
229
size
int64
23
843k
source_encoding
stringclasses
9 values
md5
stringlengths
32
32
text
stringlengths
23
843k
github
UCL-SML/pilco-matlab-master
dynamics_cdp.m
.m
pilco-matlab-master/scenarios/cartDoublePendulum/dynamics_cdp.m
2,891
utf_8
8e34721756a5a3b7a6f8558a2e93b4b4
%% dynamics_cdp.m % *Summary:* Implements ths ODE for simulating the cart-double pendulum % dynamics. % % function dz = dynamics_cdp(t,z,f) % % % *Input arguments:* % % t current time step (called from ODE solver) % z state [6 x 1] % f (optional): force f(t) % % *Output arguments:* % % dz if 3 input arguments: state derivative wrt time % if only 2 input arguments: total mechanical energy % % Note: It is assumed that the state variables are of the following order: % x: [m] position of cart % dx: [m/s] velocity of cart % dtheta1: [rad/s] angular velocity of inner pendulum % dtheta2: [rad/s] angular velocity of outer pendulum % theta1: [rad] angle of inner pendulum % theta2: [rad] angle of outer pendulum % % % A detailed derivation of the dynamics can be found in: % % M.P. Deisenroth: % Efficient Reinforcement Learning Using Gaussian Processes, Appendix C, % KIT Scientific Publishing, 2010. % % Copyright (C) 2008-2013 by % Marc Deisenroth, Andrew McHutchon, Joe Hall, and Carl Edward Rasmussen. % % Last modified: 2013-03-05 function dz = dynamics_cdp(t,z,f) %% Code % set up the system m1 = 0.5; % [kg] mass of cart m2 = 0.5; % [kg] mass of 1st pendulum m3 = 0.5; % [kg] mass of 2nd pendulum l2 = 0.6; % [m] length of 1st pendulum l3 = 0.6; % [m] length of 2nd pendulum b = 0.1; % [Ns/m] coefficient of friction between cart and ground g = 9.82; % [m/s^2] acceleration of gravity if nargin == 3 A = [2*(m1+m2+m3) -(m2+2*m3)*l2*cos(z(5)) -m3*l3*cos(z(6)) -(3*m2+6*m3)*cos(z(5)) (2*m2+6*m3)*l2 3*m3*l3*cos(z(5)-z(6)) -3*cos(z(6)) 3*l2*cos(z(5)-z(6)) 2*l3]; b = [2*f(t)-2*b*z(2)-(m2+2*m3)*l2*z(3)^2*sin(z(5))-m3*l3*z(4)^2*sin(z(6)) (3*m2+6*m3)*g*sin(z(5))-3*m3*l3*z(4)^2*sin(z(5)-z(6)) 3*l2*z(3)^2*sin(z(5)-z(6))+3*g*sin(z(6))]; x = A\b; dz = zeros(6,1); dz(1) = z(2); dz(2) = x(1); dz(3) = x(2); dz(4) = x(3); dz(5) = z(3); dz(6) = z(4); else dz = (m1+m2+m3)*z(2)^2/2+(m2/6+m3/2)*l2^2*z(3)^2+m3*l3^2*z(4)^2/6 ... -(m2/2+m3)*l2*z(2)*z(3)*cos(z(5))-m3*l3*z(2)*z(4)*cos(z(6))/2 ... +m3*l2*l3*z(3)*z(4) *cos(z(5)-z(6))/2+(m2/2+m3)*l2*g*cos(z(5)) ... +m3*l3*g*cos(z(6))/2; % I2 = m2*l2^2/12; % moment of inertia around pendulum midpoint (1st link) % I3 = m3*l3^2/12; % moment of inertia around pendulum midpoint (2nd link) % % % dz = m1*z(2)^2/2 + m2/2*(z(2)^2-l2*z(2)*z(3)*cos(z(5))) ... % + m3/2*(z(2)^2 - 2*l2*z(2)*z(3)*cos(z(5)) - l3*z(2)*z(4)*cos(z(6))) ... % + m2*l2^2*z(3)^2/8 + I2*z(3)^2/2 ... % + m3/2*(l2^2*z(3)^2 + l3^2*z(4)^2/4 + l2*l3*z(3)*z(4)*cos(z(5)-z(6))) ... % + I3*z(4)^2/2 ... % + m2*g*l2*cos(z(5))/2 + m3*g*(l2*cos(z(5))+l3*cos(z(6))/2); end
github
UCL-SML/pilco-matlab-master
dynamics_pendulum.m
.m
pilco-matlab-master/scenarios/pendulum/dynamics_pendulum.m
1,302
utf_8
093b761dfe36df40ca96d15de3e6232d
%% dynamics_pendulum.m % *Summary:* Implements ths ODE for simulating the pendulum dynamics, where % an input torque f can be applied % % function dz = dynamics_pendulum(t,z,u) % % % *Input arguments:* % % t current time step (called from ODE solver) % z state [2 x 1] % u (optional): torque f(t) applied to pendulum % % *Output arguments:* % % dz if 3 input arguments: state derivative wrt time % % Note: It is assumed that the state variables are of the following order: % dtheta: [rad/s] angular velocity of pendulum % theta: [rad] angle of pendulum % % A detailed derivation of the dynamics can be found in: % % M.P. Deisenroth: % Efficient Reinforcement Learning Using Gaussian Processes, Appendix C, % KIT Scientific Publishing, 2010. % % % Copyright (C) 2008-2013 by % Marc Deisenroth, Andrew McHutchon, Joe Hall, and Carl Edward Rasmussen. % % Last modified: 2013-03-18 function dz = dynamics_pendulum(t,z,u) %% Code l = 1; % [m] length of pendulum m = 1; % [kg] mass of pendulum g = 9.82; % [m/s^2] acceleration of gravity b = 0.01; % [s*Nm/rad] friction coefficient dz = zeros(2,1); dz(1) = ( u(t) - b*z(1) - m*g*l*sin(z(2))/2 ) / (m*l^2/3); dz(2) = z(1);
github
UCL-SML/pilco-matlab-master
loss_pendulum.m
.m
pilco-matlab-master/scenarios/pendulum/loss_pendulum.m
4,270
utf_8
919853b11632e5c459d540abf96e2219
%% loss_pendulum.m % *Summary:* Pendulum loss function; the loss is % $1-\exp(-0.5*d^2*a)$, where $a>0$ and $d^2$ is the squared difference % between the actual and desired position of the tip of the pendulum. % The mean and the variance of the loss are computed by averaging over the % Gaussian distribution of the state $p(x) = \mathcal N(m,s)$ with mean $m$ % and covariance matrix $s$. % Derivatives of these quantities are computed when desired. % % % function [L, dLdm, dLds, S2] = loss_pendulum(cost, m, s) % % % *Input arguments:* % % cost cost structure % .p lengths of the pendulum [1 x 1 ] % .width array of widths of the cost (summed together) % .expl (optional) exploration parameter % .angle (optional) array of angle indices % .target target state [D x 1 ] % m mean of state distribution [D x 1 ] % s covariance matrix for the state distribution [D x D ] % % *Output arguments:* % % L expected cost [1 x 1 ] % dLdm derivative of expected cost wrt. state mean vector [1 x D ] % dLds derivative of expected cost wrt. state covariance matrix [1 x D^2] % S2 variance of cost [1 x 1 ] % % Copyright (C) 2008-2013 by % Marc Deisenroth, Andrew McHutchon, Joe Hall, and Carl Edward Rasmussen. % % Last modified: 2014-01-05 % %% High-Level Steps % # Precomputations % # Define static penalty as distance from target setpoint % # Trigonometric augmentation % # Calculate loss function [L, dLdm, dLds, S2] = loss_pendulum(cost, m, s) %% Code if isfield(cost,'width'); cw = cost.width; else cw = 1; end if ~isfield(cost,'expl') || isempty(cost.expl); b = 0; else b = cost.expl; end % 1. Some precomputations D0 = size(s,2); % state dimension D1 = D0 + 2*length(cost.angle); % state dimension (with sin/cos) M = zeros(D1,1); M(1:D0) = m; S = zeros(D1); S(1:D0,1:D0) = s; Mdm = [eye(D0); zeros(D1-D0,D0)]; Sdm = zeros(D1*D1,D0); Mds = zeros(D1,D0*D0); Sds = kron(Mdm,Mdm); % 2. Define static penalty as distance from target setpoint ell = cost.p; Q = zeros(D1); Q(D0+1:D0+2,D0+1:D0+2) = eye(2)*ell^2; % 3. Trigonometric augmentation if D1-D0 > 0 target = [cost.target(:); ... gTrig(cost.target(:), zeros(numel(cost.target)), cost.angle)]; i = 1:D0; k = D0+1:D1; [M(k), S(k,k), C, mdm, sdm, Cdm, mds, sds, Cds] = ... gTrig(M(i),S(i,i),cost.angle); [S, Mdm, Mds, Sdm, Sds] = ... fillIn(S,C,mdm,sdm,Cdm,mds,sds,Cds,Mdm,Sdm,Mds,Sds,i,k,D1); end % 4. Calculate loss L = 0; dLdm = zeros(1,D0); dLds = zeros(1,D0*D0); S2 = 0; for i = 1:length(cw) % scale mixture of immediate costs cost.z = target; cost.W = Q/cw(i)^2; [r, rdM, rdS, s2, s2dM, s2dS] = lossSat(cost, M, S); L = L + r; S2 = S2 + s2; dLdm = dLdm + rdM(:)'*Mdm + rdS(:)'*Sdm; dLds = dLds + rdM(:)'*Mds + rdS(:)'*Sds; if (b~=0 || ~isempty(b)) && abs(s2)>1e-12 L = L + b*sqrt(s2); dLdm = dLdm + b/sqrt(s2) * ( s2dM(:)'*Mdm + s2dS(:)'*Sdm )/2; dLds = dLds + b/sqrt(s2) * ( s2dM(:)'*Mds + s2dS(:)'*Sds )/2; end end % normalize n = length(cw); L = L/n; dLdm = dLdm/n; dLds = dLds/n; S2 = S2/n; % Fill in covariance matrix...and derivatives ---------------------------- function [S, Mdm, Mds, Sdm, Sds] = ... fillIn(S,C,mdm,sdm,Cdm,mds,sds,Cds,Mdm,Sdm,Mds,Sds,i,k,D) X = reshape(1:D*D,[D D]); XT = X'; % vectorised indices I=0*X; I(i,i)=1; ii=X(I==1)'; I=0*X; I(k,k)=1; kk=X(I==1)'; I=0*X; I(i,k)=1; ik=X(I==1)'; ki=XT(I==1)'; Mdm(k,:) = mdm*Mdm(i,:) + mds*Sdm(ii,:); % chainrule Mds(k,:) = mdm*Mds(i,:) + mds*Sds(ii,:); Sdm(kk,:) = sdm*Mdm(i,:) + sds*Sdm(ii,:); Sds(kk,:) = sdm*Mds(i,:) + sds*Sds(ii,:); dCdm = Cdm*Mdm(i,:) + Cds*Sdm(ii,:); dCds = Cdm*Mds(i,:) + Cds*Sds(ii,:); S(i,k) = S(i,i)*C; S(k,i) = S(i,k)'; % off-diagonal SS = kron(eye(length(k)),S(i,i)); CC = kron(C',eye(length(i))); Sdm(ik,:) = SS*dCdm + CC*Sdm(ii,:); Sdm(ki,:) = Sdm(ik,:); Sds(ik,:) = SS*dCds + CC*Sds(ii,:); Sds(ki,:) = Sds(ik,:);
github
UCL-SML/pilco-matlab-master
draw_pendulum.m
.m
pilco-matlab-master/scenarios/pendulum/draw_pendulum.m
2,290
utf_8
c50e71f7b37fb137cfc5459d39c5c495
%% draw_pendulum.m % *Summary:* Draw the pendulum system with reward, applied torque, % and predictive uncertainty of the tips of the pendulums % % function draw_pendulum(theta, torque, cost, text1, text2, M, S) % % % *Input arguments:* % % theta1 angle of inner pendulum % theta2 angle of outer pendulum % f1 torque applied to inner pendulum % f2 torque applied to outer pendulum % cost cost structure % .fcn function handle (it is assumed to use saturating cost) % .<> other fields that are passed to cost % text1 (optional) text field 1 % text2 (optional) text field 2 % M (optional) mean of state % S (optional) covariance of state % % % Copyright (C) 2008-2013 by % Marc Deisenroth, Andrew McHutchon, Joe Hall, and Carl Edward Rasmussen. % % Last modified: 2013-03-18 function draw_pendulum(theta, torque, cost, text1, text2, M, S) %% Code l = 0.6; xmin = -1.2*l; xmax = 1.2*l; umax = 0.5; height = 0; % Draw pendulum pendulum = [0, 0; l*sin(theta), -l*cos(theta)]; clf; hold on plot(pendulum(:,1), pendulum(:,2),'r','linewidth',4) % plot ellipses around tips of pendulum (if M, S exist) try if max(max(S))>0 err = linspace(-1,1,100)*sqrt(S(2,2)); plot(l*sin(M(2)+2*err),-l*cos(M(2)+2*err),'b','linewidth',1) plot(l*sin(M(2)+err),-l*cos(M(2)+err),'b','linewidth',2) plot(l*sin(M(2)),-l*cos(M(2)),'b.','markersize',20) end catch end % Draw useful information % target location plot(0,l,'k+','MarkerSize',20); plot([xmin, xmax], [-height, -height],'k','linewidth',2) % joint plot(0,0,'k.','markersize',24) plot(0,0,'y.','markersize',14) % tip of pendulum plot(l*sin(theta),-l*cos(theta),'k.','markersize',24) plot(l*sin(theta),-l*cos(theta),'y.','markersize',14) plot(0,-2*l,'.w','markersize',0.005) % applied torque plot([0 torque/umax*xmax],[-0.5, -0.5],'g','linewidth',10); % immediate reward reward = 1-cost.fcn(cost,[0, theta]',zeros(2)); plot([0 reward*xmax],[-0.7, -0.7],'y', 'linewidth',10); text(0,-0.5,'applied torque') text(0,-0.7,'immediate reward') if exist('text1','var') text(0,-0.9, text1) end if exist('text2','var') text(0,-1.1, text2) end set(gca,'DataAspectRatio',[1 1 1],'XLim',[xmin xmax],'YLim',[-2*l 2*l]); axis off; drawnow;
github
UCL-SML/pilco-matlab-master
gp0d.m
.m
pilco-matlab-master/gp/gp0d.m
6,121
utf_8
d73ef5c95a55519268da282ffbc627ca
%% gp0d.m % *Summary:* Compute joint predictions and derivatives for multiple GPs % with uncertain inputs. Predictive variances contain uncertainty about the % function, but no noise. % If gpmodel.nigp exists, individial noise contributions are added. % % % function [M, S, V, dMdm, dSdm, dVdm, dMds, dSds, dVds] = gp0d(gpmodel, m, s) % % *Input arguments:* % % gpmodel GP model struct % hyp log-hyper-parameters [D+2 x E ] % inputs training inputs [ n x D ] % targets training targets [ n x E ] % nigp (optional) individual noise variance terms [ n x E ] % m mean of the test distribution [ D x 1 ] % s covariance matrix of the test distribution [ D x D ] % % *Output arguments:* % % M mean of pred. distribution [ E x 1 ] % S covariance of the pred. distribution [ E x E ] % V inv(s) times covariance between input and output [ D x E ] % dMdm output mean by input mean [ E x D ] % dSdm output covariance by input mean [E*E x D ] % dVdm inv(s)*input-output covariance by input mean [D*E x D ] % dMds ouput mean by input covariance [ E x D*D] % dSds output covariance by input covariance [E*E x D*D] % dVds inv(s)*input-output covariance by input covariance [D*E x D*D] % % % Copyright (C) 2008-2013 by % Marc Deisenroth, Andrew McHutchon, Joe Hall, and Carl Edward Rasmussen. % % Last modified: 2013-05-24 % %% High-Level Steps % # If necessary, compute kernel matrix and cache it % # Compute predicted mean and inv(s) times input-output covariance % # Compute predictive covariance matrix, non-central moments % # Centralize moments % # Vectorize derivatives function [M, S, V, dMdm, dSdm, dVdm, dMds, dSds, dVds] = gp0d(gpmodel, m, s) %% Code % If no derivatives required, call gp0 if nargout < 4; [M S V] = gp0(gpmodel, m, s); return; end persistent K iK beta oldX oldn; [n, D] = size(gpmodel.inputs); % number of examples and dimension of inputs E = size(gpmodel.targets,2); % number of outputs X = gpmodel.hyp; % short hand for hyperparameters % 1) if necessary: re-compute cached variables if numel(X) ~= numel(oldX) || isempty(iK) || sum(any(X ~= oldX)) || n ~= oldn oldX = X; oldn = n; iK = zeros(n,n,E); K = iK; beta = zeros(n,E); for i=1:E % compute K and inv(K) inp = bsxfun(@rdivide,gpmodel.inputs,exp(X(1:D,i)')); K(:,:,i) = exp(2*X(D+1,i)-maha(inp,inp)/2); if isfield(gpmodel,'nigp') L = chol(K(:,:,i) + exp(2*X(D+2,i))*eye(n) + diag(gpmodel.nigp(:,i)))'; else L = chol(K(:,:,i) + exp(2*X(D+2,i))*eye(n))'; end iK(:,:,i) = L'\(L\eye(n)); beta(:,i) = L'\(L\gpmodel.targets(:,i)); end end k = zeros(n,E); M = zeros(E,1); V = zeros(D,E); S = zeros(E); % initialize dMds = zeros(E,D,D); dSdm = zeros(E,E,D); dSds = zeros(E,E,D,D); dVds = zeros(D,E,D,D); T = zeros(D); inp = bsxfun(@minus,gpmodel.inputs,m'); % centralize inputs % 2) compute predicted mean and inv(s) times input-output covariance for i=1:E iL = diag(exp(-X(1:D,i))); % inverse length scales in = inp*iL; B = iL*s*iL+eye(D); LiBL = iL/B*iL; t = in/B; l = exp(-sum(in.*t,2)/2); lb = l.*beta(:,i); tL = t*iL; tlb = bsxfun(@times,tL,lb); c = exp(2*X(D+1,i))/sqrt(det(B)); M(i) = c*sum(lb); V(:,i) = tL'*lb*c; % inv(s) times input-output covariance dMds(i,:,:) = c*tL'*tlb/2 - LiBL*M(i)/2; for d = 1:D dVds(d,i,:,:) = c*bsxfun(@times,tL,tL(:,d))'*tlb/2 - LiBL*V(d,i)/2 ... - (V(:,i)*LiBL(d,:) + LiBL(:,d)*V(:,i)')/2; end k(:,i) = 2*X(D+1,i)-sum(in.*in,2)/2; end dMdm = V'; dVdm = 2*permute(dMds,[2 1 3]); % derivatives wrt m iell2 = exp(-2*gpmodel.hyp(1:D,:)); inpiell2 = bsxfun(@times,inp,permute(iell2,[3,1,2])); % N-by-D-by-E % 3) compute predictive covariance matrix, non-central moments for i=1:E ii = inpiell2(:,:,i); for j=1:i R = s*diag(iell2(:,i)+iell2(:,j))+eye(D); t = 1/sqrt(det(R)); ij = inpiell2(:,:,j); L = exp(bsxfun(@plus,k(:,i),k(:,j)')+maha(ii,-ij,R\s/2)); if i==j iKL = iK(:,:,i).*L; s1iKL = sum(iKL,1); s2iKL = sum(iKL,2); S(i,j) = t*(beta(:,i)'*L*beta(:,i) - sum(s1iKL)); zi = ii/R; bibLi = L'*beta(:,i).*beta(:,i); cbLi = L'*bsxfun(@times, beta(:,i), zi); r = (bibLi'*zi*2 - (s2iKL' + s1iKL)*zi)*t; for d = 1:D T(d,1:d) = 2*(zi(:,1:d)'*(zi(:,d).*bibLi) + ... cbLi(:,1:d)'*(zi(:,d).*beta(:,i)) - zi(:,1:d)'*(zi(:,d).*s2iKL) ... - zi(:,1:d)'*(iKL*zi(:,d))); T(1:d,d) = T(d,1:d)'; end else zi = ii/R; zj = ij/R; S(i,j) = beta(:,i)'*L*beta(:,j)*t; S(j,i) = S(i,j); bibLj = L*beta(:,j).*beta(:,i); bjbLi = L'*beta(:,i).*beta(:,j); cbLi = L'*bsxfun(@times, beta(:,i), zi); cbLj = L*bsxfun(@times, beta(:,j), zj); r = (bibLj'*zi+bjbLi'*zj)*t; for d = 1:D T(d,1:d) = zi(:,1:d)'*(zi(:,d).*bibLj) + ... cbLi(:,1:d)'*(zj(:,d).*beta(:,j)) + zj(:,1:d)'*(zj(:,d).*bjbLi) + ... cbLj(:,1:d)'*(zi(:,d).*beta(:,i)); T(1:d,d) = T(d,1:d)'; end end dSdm(i,j,:) = r - M(i)*dMdm(j,:)-M(j)*dMdm(i,:); dSdm(j,i,:) = dSdm(i,j,:); T = (t*T-S(i,j)*diag(iell2(:,i)+iell2(:,j))/R)/2; T = T - reshape(M(i)*dMds(j,:,:) + M(j)*dMds(i,:,:),D,D); dSds(i,j,:,:) = T; dSds(j,i,:,:) = T; end S(i,i) = S(i,i) + exp(2*X(D+1,i)); end % 4) centralize moments S = S - M*M'; % 5) vectorize derivatives dMds = reshape(dMds,[E D*D]); dSds = reshape(dSds,[E*E D*D]); dSdm = reshape(dSdm,[E*E D]); dVds = reshape(dVds,[D*E D*D]); dVdm = reshape(dVdm,[D*E D]);
github
UCL-SML/pilco-matlab-master
gp2d.m
.m
pilco-matlab-master/gp/gp2d.m
13,617
utf_8
25edf637a6e3ad389ac32a3c5547aa74
%% gp2d.m % *Summary:* Compute joint predictions and derivatives for multiple GPs % with uncertain inputs. Does not consider the uncertainty about the underlying % function (in prediction), hence, only the GP mean function is considered. % Therefore, this representation is equivalent to a regularized RBF % network. % If gpmodel.nigp exists, individial noise contributions are added. % % % function [M, S, V, dMdm, dSdm, dVdm, dMds, dSds, dVds, dMdi, dSdi, dVdi, ... % dMdt, dSdt, dVdt, dMdX, dSdX, dVdX] = gp2d(gpmodel, m, s) % % *Input arguments:* % % gpmodel GP model struct % hyp log-hyper-parameters [D+2 x E ] % inputs training inputs [ n x D ] % targets training targets [ n x E ] % nigp (optional) individual noise variance terms [ n x E ] % m mean of the test distribution [ D x 1 ] % s covariance matrix of the test distribution [ D x D ] % % *Output arguments:* % % M mean of pred. distribution [ E x 1 ] % S covariance of the pred. distribution [ E x E ] % V inv(s) times covariance between input and output [ D x E ] % dMdm output mean by input mean [ E x D ] % dSdm output covariance by input mean [E*E x D ] % dVdm inv(s)*input-output covariance by input mean [D*E x D ] % dMds ouput mean by input covariance [ E x D*D] % dSds output covariance by input covariance [E*E x D*D] % dVds inv(s)*input-output covariance by input covariance [D*E x D*D] % % dMdi output mean by inputs [ E x n*D] % dSdi output covariance by inputs [E*E x n*D] % dVdi inv(s) times input-output covariance by inputs [D*E x n*D] % dMdt output mean by targets [ E x n*E] % dSdt output covariance by targets [E*E x n*E] % dVdt inv(s) times input-output covariance by targets [D*E x n*E] % dMdX output mean by hyperparameters [ E x P*E] % dSdX output covariance by hyperparameters [E*E x P*E] % dVdX inv(s) times input-output covariance by hyper-par. [D*E x P*E] % % % % Copyright (C) 2008-2013 by % Marc Deisenroth, Andrew McHutchon, Joe Hall, and Carl Edward Rasmussen. % % Last modified: 2013-05-24 % %% High-Level Steps % # If necessary, re-compute cached variables % # Compute predicted mean and inv(s) times input-output covariance % # Compute predictive covariance matrix, non-central moments % # Centralize moments % # Vectorize derivatives function [M, S, V, dMdm, dSdm, dVdm, dMds, dSds, dVds, dMdi, dSdi, dVdi, ... dMdt, dSdt, dVdt, dMdX, dSdX, dVdX] = gp2d(gpmodel, m, s) %% Code input = gpmodel.inputs; target = gpmodel.targets; X = gpmodel.hyp; if nargout < 4; [M, S, V] = gp2(gpmodel, m, s); return; end persistent K iK oldX oldIn oldOut beta oldn; % cache some variables D = size(input,2); % number of examples and dimension of input space [n, E] = size(target); % number of examples and number of outputs X = reshape(X, D+2, E); % 1) If necessary, re-compute cached variables if numel(X) ~= numel(oldX) || isempty(iK) || n ~= oldn || ... sum(any(X ~= oldX)) || sum(any(oldIn ~= input)) || ... sum(any(oldOut ~= target)) oldX = X; oldIn = input; oldOut = target; oldn = n; K = zeros(n,n,E); iK = K; beta = zeros(n,E); % compute K and inv(K) and beta for i=1:E inp = bsxfun(@rdivide,input,exp(X(1:D,i)')); K(:,:,i) = exp(2*X(D+1,i)-maha(inp,inp)/2); if isfield(gpmodel,'nigp') L = chol(K(:,:,i) + exp(2*X(D+2,i))*eye(n) + diag(gpmodel.nigp(:,i)))'; else L = chol(K(:,:,i) + exp(2*X(D+2,i))*eye(n))'; end iK(:,:,i) = L'\(L\eye(n)); beta(:,i) = L'\(L\gpmodel.targets(:,i)); end end % initializations k = zeros(n,E); M = zeros(E,1); V = zeros(D,E); S = zeros(E); dMds = zeros(E,D,D); dSdm = zeros(E,E,D); r = zeros(1,D); dSds = zeros(E,E,D,D); dVds = zeros(D,E,D,D); T = zeros(D); tlbdi = zeros(n,D); dMdi = zeros(E,n,D); dMdt = zeros(E,n,E); dVdt = zeros(D,E,n,E); dVdi = zeros(D,E,n,D); dSdt = zeros(E,E,n,E); dSdi = zeros(E,E,n,D); dMdX = zeros(E,D+2,E); dSdX = zeros(E,E,D+2,E); dVdX = zeros(D,E,D+2,E); Z = zeros(n,D); bdX = zeros(n,E,D); kdX = zeros(n,E,D+1); % centralize training inputs inp = bsxfun(@minus,input,m'); % 2) compute predicted mean and input-output covariance for i = 1:E % first some useful intermediate terms K2 = K(:,:,i)+exp(2*X(D+2,i))*eye(n); % K + sigma^2*I inp2 = bsxfun(@rdivide,input,exp(X(1:D,i)')); ii = bsxfun(@rdivide,input,exp(2*X(1:D,i)')); R = s+diag(exp(2*X(1:D,i))); L = diag(exp(-X(1:D,i))); B = L*s*L+eye(D); iR = L/B*L; t = inp*iR; l = exp(-sum(t.*inp,2)/2); lb = l.*beta(:,i); tliK = t'*bsxfun(@times,l,iK(:,:,i)); liK = K2\l; tlb = bsxfun(@times,t,lb); c = exp(2*X(D+1,i))/sqrt(det(R))*exp(sum(X(1:D,i))); detdX = diag(bsxfun(@times,det(R)*iR',2.*exp(2.*X(1:D,i)))); % d(det R)/dX cdX = -0.5*c/det(R).*detdX'+ c.*ones(1,D); % derivs w.r.t length-scales dldX = bsxfun(@times,l,bsxfun(@times,t,2.*exp(2*X(1:D,i)')).*t./2); M(i) = sum(lb)*c; % predicted mean iK2beta = K2\beta(:,i); dMds(i,:,:) = c*t'*tlb/2-iR*M(i)/2; dMdX(i,D+2,i) = -c*sum(l.*(2*exp(2*X(D+2,i))*iK2beta)); % OK dMdX(i,D+1,i) = -dMdX(i,(i-1)*(D+2)+D+2); dVdX(:,i,D+2,i) = -((l.*(2*exp(2*X(D+2,i))*iK2beta))'*t*c)'; dVdX(:,i,D+1,i) = -dVdX(:,i,D+2,i); dsi = -bsxfun(@times,inp2,2.*inp2); % d(sum(inp2.*inp2,2))/dX dslb = zeros(1,D); for d = 1:D sqdi = K(:,:,i).*bsxfun(@minus,ii(:,d),ii(:,d)'); sqdiBi = sqdi*beta(:,i); tlbdi(:,d) = sqdi*liK.*beta(:,i) + sqdiBi.*liK; tlbdi2 = -tliK*(-bsxfun(@times,sqdi,beta(:,i))'-diag(sqdiBi)); dVdi(:,i,:,d) = c*(iR(:,d)*lb' - bsxfun(@times,t,tlb(:,d))' + tlbdi2); dsqdX = bsxfun(@plus,dsi(:,d),dsi(:,d)') + 4.*inp2(:,d)*inp2(:,d)'; dKdX = -K(:,:,i).*dsqdX./2; % dK/dX(1:D) dKdXbeta = dKdX*beta(:,i); bdX(:,i,d) = -K2\dKdXbeta; % dbeta/dX dslb(d) = -liK'*dKdXbeta + beta(:,i)'*dldX(:,d); dlb = dldX(:,d).*beta(:,i) + l.*bdX(:,i,d); dtdX = inp*(-bsxfun(@times,iR(:,d),2.*exp(2*X(d,i))*iR(d,:))); dlbt = lb'*dtdX + dlb'*t; dVdX(:,i,d,i) = (dlbt'*c + cdX(d)*(lb'*t)'); end % d dMdi(i,:,:) = c*(tlbdi - tlb); dMdt(i,:,i) = c*liK'; dMdX(i,1:D,i) = cdX.*sum(beta(:,i).*l) + c.*dslb; v = bsxfun(@rdivide,inp,exp(X(1:D,i)')); k(:,i) = 2*X(D+1,i)-sum(v.*v,2)/2; V(:,i) = t'*lb*c; % input-output covariance for d = 1:D dVds(d,i,:,:) = c*bsxfun(@times,t,t(:,d))'*tlb/2 - iR*V(d,i)/2 ... - V(:,i)*iR(d,:)/2 -iR(:,d)*V(:,i)'/2; kdX(:,i,d) = bsxfun(@times,v(:,d),v(:,d)); end % d dVdt(:,i,:,i) = c*tliK; kdX(:,i,D+1) = 2*ones(1,n); % pre-computation for later end % i dMdm = V'; % derivatives w.r.t m dVdm = 2*permute(dMds,[2 1 3]); % 3) predictive covariance matrix (non-central moments) for i = 1:E K2 = K(:,:,i)+exp(2*X(D+2,i))*eye(n); ii = bsxfun(@rdivide,inp,exp(2*X(1:D,i)')); for j = 1:i % if i==j: diagonal elements of S; see Marc's thesis around eq. (2.26) R = s*diag(exp(-2*X(1:D,i))+exp(-2*X(1:D,j)))+eye(D); t = 1./sqrt(det(R)); if rcond(R) < 1e-15; fprintf('R-matrix in gp2d ill-conditioned'); keyboard; end iR = R\eye(D); ij = bsxfun(@rdivide,inp,exp(2*X(1:D,j)')); L = exp(bsxfun(@plus,k(:,i),k(:,j)')+maha(ii,-ij,R\s/2)); % called Q in thesis A = beta(:,i)*beta(:,j)'; A = A.*L; ssA = sum(sum(A)); S(i,j) = t*ssA; S(j,i) = S(i,j); zzi = ii*(R\s); zzj = ij*(R\s); zi = ii/R; zj = ij/R; tdX = -0.5*t*sum(iR'.*bsxfun(@times,s,-2*exp(-2*X(1:D,i)')-2*exp(-2*X(1:D,i)'))); tdXi = -0.5*t*sum(iR'.*bsxfun(@times,s,-2*exp(-2*X(1:D,i)'))); tdXj = -0.5*t*sum(iR'.*bsxfun(@times,s,-2*exp(-2*X(1:D,j)'))); bLiKi = iK(:,:,j)*(L'*beta(:,i)); bLiKj = iK(:,:,i)*(L*beta(:,j)); Q2 = R\s/2; aQ = ii*Q2; bQ = ij*Q2; for d = 1:D Z(:,d) = exp(-2*X(d,i))*(A*zzj(:,d) + sum(A,2).*(zzi(:,d) - inp(:,d)))... + exp(-2*X(d,j))*((zzi(:,d))'*A + sum(A,1).*(zzj(:,d) - inp(:,d))')'; Q = bsxfun(@minus,inp(:,d),inp(:,d)'); B = K(:,:,i).*Q; Z(:,d) = Z(:,d)+exp(-2*X(d,i))*(B*beta(:,i).*bLiKj+beta(:,i).*(B*bLiKj)); if i~=j; B = K(:,:,j).*Q; end Z(:,d) = Z(:,d)+exp(-2*X(d,j))*(bLiKi.*(B*beta(:,j))+B*bLiKi.*beta(:,j)); B = bsxfun(@plus,zi(:,d),zj(:,d)').*A; r(d) = sum(sum(B))*t; T(d,1:d) = sum(zi(:,1:d)'*B,2) + sum(B*zj(:,1:d))'; T(1:d,d) = T(d,1:d)'; if i==j RTi = bsxfun(@times,s,(-2*exp(-2*X(1:D,i)')-2*exp(-2*X(1:D,j)'))); diRi = -R\bsxfun(@times,RTi(:,d),iR(d,:)); else RTi = bsxfun(@times,s,-2*exp(-2*X(1:D,i)')); RTj = bsxfun(@times,s,-2*exp(-2*X(1:D,j)')); diRi = -R\bsxfun(@times,RTi(:,d),iR(d,:)); diRj = -R\bsxfun(@times,RTj(:,d),iR(d,:)); QdXj = diRj*s/2; % dQ2/dXj end QdXi = diRi*s/2; % dQ2/dXj if i==j daQi = ii*QdXi + bsxfun(@times,-2*ii(:,d),Q2(d,:)); % d(ii*Q)/dXi dsaQi = sum(daQi.*ii,2) - 2.*aQ(:,d).*ii(:,d); dsaQj = dsaQi; dsbQi = dsaQi; dsbQj = dsbQi; dm2i = -2*daQi*ii' + 2*(bsxfun(@times,aQ(:,d),ii(:,d)')... +bsxfun(@times,ii(:,d),aQ(:,d)')); dm2j = dm2i; % -2*aQ*ij'/di else dbQi = ij*QdXi; % d(ij*Q)/dXi dbQj = ij*QdXj + bsxfun(@times,-2*ij(:,d),Q2(d,:)); % d(ij*Q)/dXj daQi = ii*QdXi + bsxfun(@times,-2*ii(:,d),Q2(d,:)); % d(ii*Q)/dXi daQj = ii*QdXj; % d(ii*Q)/dXj dsaQi = sum(daQi.*ii,2) - 2.*aQ(:,d).*ii(:,d); dsaQj = sum(daQj.*ii,2); dsbQi = sum(dbQi.*ij,2); dsbQj = sum(dbQj.*ij,2) - 2.*bQ(:,d).*ij(:,d); dm2i = -2*daQi*ij'; % second part of the maha(..) function wrt Xi dm2j = -2*ii*(dbQj)'; % second part of the maha(..) function wrt Xj end dm1i = bsxfun(@plus,dsaQi,dsbQi'); % first part of the maha(..) function wrt Xi dm1j = bsxfun(@plus,dsaQj,dsbQj'); % first part of the maha(..) function wrt Xj dmahai = dm1i-dm2i; dmahaj = dm1j-dm2j; if i==j LdXi = L.*(dmahai + bsxfun(@plus,kdX(:,i,d),kdX(:,j,d)')); dSdX(i,i,d,i) = beta(:,i)'*LdXi*beta(:,j); else LdXi = L.*(dmahai + bsxfun(@plus,kdX(:,i,d),zeros(n,1)')); LdXj = L.*(dmahaj + bsxfun(@plus,zeros(n,1),kdX(:,j,d)')); dSdX(i,j,d,i) = beta(:,i)'*LdXi*beta(:,j); dSdX(i,j,d,j) = beta(:,i)'*LdXj*beta(:,j); end end % d if i==j dSdX(i,i,1:D,i) = reshape(dSdX(i,i,1:D,i),D,1) + reshape(bdX(:,i,:),n,D)'*(L+L')*beta(:,i); dSdX(i,i,1:D,i) = reshape(t*dSdX(i,i,1:D,i),D,1)' + tdX*ssA; dSdX(i,i,D+2,i) = 2*exp(2*X(D+2,i))*t*(-sum(beta(:,i).*bLiKi)-sum(beta(:,i).*bLiKi)); else dSdX(i,j,1:D,i) = reshape(dSdX(i,j,1:D,i),D,1) + reshape(bdX(:,i,:),n,D)'*(L*beta(:,j)); dSdX(i,j,1:D,j) = reshape(dSdX(i,j,1:D,j),D,1) + reshape(bdX(:,j,:),n,D)'*(L'*beta(:,i)); dSdX(i,j,1:D,i) = reshape(t*dSdX(i,j,1:D,i),D,1)' + tdXi*ssA; dSdX(i,j,1:D,j) = reshape(t*dSdX(i,j,1:D,j),D,1)' + tdXj*ssA; dSdX(i,j,D+2,i) = 2*exp(2*X(D+2,i))*t*(-beta(:,i)'*bLiKj); dSdX(i,j,D+2,j) = 2*exp(2*X(D+2,j))*t*(-beta(:,j)'*bLiKi); end dSdm(i,j,:) = r - M(i)*dMdm(j,:)-M(j)*dMdm(i,:); dSdm(j,i,:) = dSdm(i,j,:); T = (t*T-S(i,j)*diag(exp(-2*X(1:D,i))+exp(-2*X(1:D,j)))/R)/2; T = T - reshape(M(i)*dMds(j,:,:) + M(j)*dMds(i,:,:),D,D); dSds(i,j,:,:) = T; dSds(j,i,:,:) = T; if i==j dSdt(i,i,:,i) = (beta(:,i)'*(L+L'))/(K2)*t ... - 2*dMdt(i,:,i)*M(i); dSdX(i,j,:,i) = reshape(dSdX(i,j,:,i),1,D+2) - M(i)*dMdX(j,:,j)-M(j)*dMdX(i,:,i); else dSdt(i,j,:,i) = (beta(:,j)'*L')/(K2)*t ... - dMdt(i,:,i)*M(j); dSdt(i,j,:,j) = beta(:,i)'*L/(K(:,:,j)+exp(2*X(D+2,j))*eye(n))*t ... - dMdt(j,:,j)*M(i); dSdt(j,i,:,:) = dSdt(i,j,:,:); dSdX(i,j,:,j) = reshape(dSdX(i,j,:,j),1,D+2) - M(i)*dMdX(j,:,j); dSdX(i,j,:,i) = reshape(dSdX(i,j,:,i),1,D+2) - M(j)*dMdX(i,:,i); end dSdi(i,j,:,:) = Z*t - reshape(M(i)*dMdi(j,:,:) + dMdi(i,:,:)*M(j),n,D); dSdi(j,i,:,:) = dSdi(i,j,:,:); dSdX(j,i,:,:) = dSdX(i,j,:,:); end % j S(i,i) = S(i,i) + 1e-06; % add small diagonal jitter for numerical reasons end % i dSdX(:,:,D+1,:) = -dSdX(:,:,D+2,:); dSdX(:,:,D+1,:) = -dSdX(:,:,D+2,:); % 4) centralize moments S = S - M*M'; %S(diag(S)<0,diag(S)<0) = 1e-6; % 5) Vectorize derivatives dMds=reshape(dMds,[E D*D]); dSdm=reshape(dSdm,[E*E D]); dSds=reshape(dSds,[E*E D*D]); dVdm=reshape(dVdm,[D*E D]); dVds=reshape(dVds,[D*E D*D]); dMdi=reshape(dMdi,E,[]); dMdt=reshape(dMdt,E,[]); dMdX=reshape(dMdX,E,[]); dSdi=reshape(dSdi,E*E,[]);dSdt=reshape(dSdt,E*E,[]);dSdX=reshape(dSdX,E*E,[]); dVdi=reshape(dVdi,D*E,[]);dVdt=reshape(dVdt,D*E,[]);dVdX=reshape(dVdX,D*E,[]);
github
UCL-SML/pilco-matlab-master
hypCurb.m
.m
pilco-matlab-master/gp/hypCurb.m
2,378
utf_8
2aa8259c63afdfece72ccc8a31ef5e82
%% hypCurb.m % *Summary:* Wrapper for GP training (via gpr.m), penalizing large SNR and % extreme length-scales to avoid numerical instabilities % % function [f df] = hypCurb(lh, covfunc, x, y, curb) % % *Input arguments:* % % lh log-hyper-parameters [D+2 x E ] % covfunc covariance function, e.g., % covfunc = {'covSum', {'covSEard', 'covNoise'}}; % x training inputs [ n x D ] % y training targets [ n x E ] % curb (optional) parameters to penalize extreme hyper-parameters % .ls length-scales % .snr signal-to-noise ratio (try to keep it below 500) % .std additional parameter required for length-scale penalty % % *Output arguments:* % % f penalized negative log-marginal likelihood % df derivative of penalized negative log-marginal likelihood wrt % GP log-hyper-parameters % % % Copyright (C) 2008-2013 by % Marc Deisenroth, Andrew McHutchon, Joe Hall, and Carl Edward Rasmussen. % % Last modified: 2011-12-19 % %% High-Level Steps % # Compute the negative log-marginal likelihood (plus derivatives) % # Add penalties and change derivatives accordingly function [f df] = hypCurb(lh, covfunc, x, y, curb) %% Code if nargin < 5, curb.snr = 500; curb.ls = 100; curb.std = 1; end % set default p = 30; % penalty power D = size(x,2); if size(lh,1) == 3*D+2; li = 1:2*D; sfi = 2*D+1:3*D+1; % 1D and DD terms elseif size(lh,1) == 2*D+1; li = 1:D; sfi = D+1:2*D; % Just 1D terms elseif size(lh,1) == D+2; li = 1:D; sfi = D+1; % Just DD terms else error('Incorrect number of hyperparameters'); end ll = lh(li); lsf = lh(sfi); lsn = lh(end); % 1) compute the negative log-marginal likelihood (plus derivatives) [f df] = gpr(lh, covfunc, x, y); % first, call gpr % 2) add penalties and change derivatives accordingly f = f + sum(((ll - log(curb.std'))./log(curb.ls)).^p); % length-scales df(li) = df(li) + p*(ll - log(curb.std')).^(p-1)/log(curb.ls)^p; f = f + sum(((lsf - lsn)/log(curb.snr)).^p); % signal to noise ratio df(sfi) = df(sfi) + p*(lsf - lsn).^(p-1)/log(curb.snr)^p; df(end) = df(end) - p*sum((lsf - lsn).^(p-1)/log(curb.snr)^p);
github
UCL-SML/pilco-matlab-master
gp1.m
.m
pilco-matlab-master/gp/gp1.m
4,916
utf_8
d5d2ccda21c8686f5c72a3b7dcba2d62
%% gp1.m % *Summary:* Compute joint predictions for the FITC sparse approximation to % multiple GPs with uncertain inputs. % Predictive variances contain uncertainty about the function, but no noise. % If gpmodel.nigp exists, individual noise contributions are added. % % function [M, S, V] = gp1d(gpmodel, m, s) % % *Input arguments:* % % gpmodel GP model struct % hyp log-hyper-parameters [D+2 x E ] % inputs training inputs [ n x D ] % targets training targets [ n x E ] % nigp (optional) individual noise variance terms [ n x E ] % m mean of the test distribution [ D x 1 ] % s covariance matrix of the test distribution [ D x D ] % % *Output arguments:* % % M mean of pred. distribution [ E x 1 ] % S covariance of the pred. distribution [ E x E ] % V inv(s) times covariance between input and output [ D x E ] % % % Copyright (C) 2008-2013 by % Marc Deisenroth, Andrew McHutchon, Joe Hall, and Carl Edward Rasmussen. % % Last modified: 2013-03-05 % %% High-Level Steps % # If necessary, compute kernel matrix and cache it % # Compute predicted mean and inv(s) times input-output covariance % # Compute predictive covariance matrix, non-central moments % # Centralize moments function [M, S, V] = gp1(gpmodel, m, s) %% Code if ~isfield(gpmodel,'induce') || numel(gpmodel.induce)==0, [M, S, V] = gp0(gpmodel, m, s); return; end persistent iK iK2 beta oldX; ridge = 1e-6; % jitter to make matrix better conditioned [n, D] = size(gpmodel.inputs); % number of examples and dimension of inputs E = size(gpmodel.targets,2); % number of examples and number of outputs X = gpmodel.hyp; input = gpmodel.inputs; targets = gpmodel.targets; [np pD pE] = size(gpmodel.induce); % number of pseudo inputs per dimension pinput = gpmodel.induce; % all pseudo inputs % 1) If necessary: re-compute cached variables if numel(X) ~= numel(oldX) || isempty(iK) || isempty(iK2) || ... % if necessary sum(any(X ~= oldX)) || numel(iK2) ~=E*np^2 || numel(iK) ~= n*np*E oldX = X; % compute K, inv(K), inv(K2) iK = zeros(np,n,E); iK2 = zeros(np,np,E); beta = zeros(np,E); for i=1:E pinp = bsxfun(@rdivide,pinput(:,:,min(i,pE)),exp(X(1:D,i)')); inp = bsxfun(@rdivide,input,exp(X(1:D,i)')); Kmm = exp(2*X(D+1,i)-maha(pinp,pinp)/2) + ridge*eye(np); % add small ridge Kmn = exp(2*X(D+1,i)-maha(pinp,inp)/2); L = chol(Kmm)'; V = L\Kmn; % inv(sqrt(Kmm))*Kmn if isfield(gpmodel,'nigp') G = exp(2*X(D+1,i))-sum(V.^2)+gpmodel.nigp(:,i)'; else G = exp(2*X(D+1,i))-sum(V.^2); end G = sqrt(1+G/exp(2*X(D+2,i))); V = bsxfun(@rdivide,V,G); Am = chol(exp(2*X(D+2,i))*eye(np) + V*V')'; At = L*Am; % chol(sig*B) [thesis, p. 40] iAt = At\eye(np); % The following is not an inverse matrix, but we'll treat it as such: multiply % the targets from right and the cross-covariances left to get predictive mean. iK(:,:,i) = ((Am\(bsxfun(@rdivide,V,G)))'*iAt)'; beta(:,i) = iK(:,:,i)*targets(:,i); iB = iAt'*iAt.*exp(2*X(D+2,i)); % inv(B), [Ed's thesis, p. 40] iK2(:,:,i) = Kmm\eye(np) - iB; % covariance matrix for predictive variances end end k = zeros(np,E); M = zeros(E,1); V = zeros(D,E); S = zeros(E); % allocate inp = zeros(np,D,E); % 2) Compute predicted mean and inv(s) times input-output covariance for i=1:E inp(:,:,i) = bsxfun(@minus,pinput(:,:,min(i,pE)),m'); L = diag(exp(-X(1:D,i))); in = inp(:,:,i)*L; B = L*s*L+eye(D); t = in/B; l = exp(-sum(in.*t,2)/2); lb = l.*beta(:,i); tL = t*L; c = exp(2*X(D+1,i))/sqrt(det(B)); M(i) = sum(lb)*c; % predicted mean V(:,i) = tL'*lb*c; % inv(s) times input-output covariance k(:,i) = 2*X(D+1,i)-sum(in.*in,2)/2; end % 3) Compute predictive covariance matrix, non-central moments for i=1:E ii = bsxfun(@rdivide,inp(:,:,i),exp(2*X(1:D,i)')); for j=1:i R = s*diag(exp(-2*X(1:D,i))+exp(-2*X(1:D,j)))+eye(D); t = 1./sqrt(det(R)); ij = bsxfun(@rdivide,inp(:,:,j),exp(2*X(1:D,j)')); L = exp(bsxfun(@plus,k(:,i),k(:,j)')+maha(ii,-ij,R\s/2)); if i==j S(i,i) = t*(beta(:,i)'*L*beta(:,i) - sum(sum(iK2(:,:,i).*L))); else S(i,j) = beta(:,i)'*L*beta(:,j)*t; S(j,i) = S(i,j); end end S(i,i) = S(i,i) + exp(2*X(D+1,i)); end % 4) Centralize moments S = S - M*M';
github
UCL-SML/pilco-matlab-master
covSEard.m
.m
pilco-matlab-master/gp/covSEard.m
1,734
utf_8
1f400b4ffc10975b4572164e889e177c
%% covSEard.m % Squared Exponential covariance function with Automatic Relevance Detemination % (ARD) distance measure. The covariance function is parameterized as: % % k(x^p,x^q) = sf2 * exp(-(x^p - x^q)'*inv(P)*(x^p - x^q)/2) % % where the P matrix is diagonal with ARD parameters ell_1^2,...,ell_D^2, where % D is the dimension of the input space and sf2 is the signal variance. The % hyperparameters are: % % loghyper = [ log(ell_1) % log(ell_2) % . % log(ell_D) % log(sqrt(sf2)) ] % % For more help on design of covariance functions, try "help covFunctions". % % (C) Copyright 2006 by Carl Edward Rasmussen (2006-03-24) function [A, B] = covSEard(loghyper, x, z) %% Code if nargin == 0, A = '(D+1)'; return; end % report number of parameters persistent K; [n D] = size(x); ell = exp(loghyper(1:D)); % characteristic length scale sf2 = exp(2*loghyper(D+1)); % signal variance if nargin == 2 K = sf2*exp(-sq_dist(diag(1./ell)*x')/2); A = K; elseif nargout == 2 % compute test set covariances A = sf2*ones(size(z,1),1); B = sf2*exp(-sq_dist(diag(1./ell)*x',diag(1./ell)*z')/2); else % compute derivative matrix % check for correct dimension of the previously calculated kernel matrix if any(size(K)~=n) K = sf2*exp(-sq_dist(diag(1./ell)*x')/2); end if z <= D % length scale parameters A = K.*sq_dist(x(:,z)'/ell(z)); else % magnitude parameter A = 2*K; clear K; end end
github
UCL-SML/pilco-matlab-master
gp1d.m
.m
pilco-matlab-master/gp/gp1d.m
7,391
utf_8
b53a266575ac4ef1f2678674efe61708
%% gp1d.m % *Summary:* Compute joint predictions (and derivatives) for the FITC sparse % approximation to multiple GPs with uncertain inputs. % Predictive variances contain uncertainty about the function, but no noise. % If gpmodel.nigp exists, individual noise contributions are added. % % function [M, S, V, dMdm, dSdm, dVdm, dMds, dSds, dVds] = gp1d(gpmodel, m, s) % % *Input arguments:* % % gpmodel GP model struct % hyp log-hyper-parameters [D+2 x E ] % inputs training inputs [ n x D ] % targets training targets [ n x E ] % nigp (optional) individual noise variance terms [ n x E ] % m mean of the test distribution [ D x 1 ] % s covariance matrix of the test distribution [ D x D ] % % *Output arguments:* % % M mean of pred. distribution [ E x 1 ] % S covariance of the pred. distribution [ E x E ] % V inv(s) times covariance between input and output [ D x E ] % dMdm output mean by input mean [ E x D ] % dSdm output covariance by input mean [E*E x D ] % dVdm inv(s)*input-output covariance by input mean [D*E x D ] % dMds ouput mean by input covariance [ E x D*D] % dSds output covariance by input covariance [E*E x D*D] % dVds inv(s)*input-output covariance by input covariance [D*E x D*D] % % % Copyright (C) 2008-2013 by % Marc Deisenroth, Andrew McHutchon, Joe Hall, and Carl Edward Rasmussen. % % Last modified: 2013-05-24 % %% High-Level Steps % # If necessary, compute kernel matrix and cache it % # Compute predicted mean and inv(s) times input-output covariance % # Compute predictive covariance matrix, non-central moments % # Centralize moments % # Vectorize derivatives function [M, S, V, dMdm, dSdm, dVdm, dMds, dSds, dVds] = gp1d(gpmodel, m, s) %% Code % If no derivatives are required, call gp1 if nargout < 4; [M S V] = gp1(gpmodel, m, s); return; end % If there are no inducing inputs, back off to gp0d (no sparse GP required) if numel(gpmodel.induce) == 0 [M S V dMdm dSdm dVdm dMds dSds dVds] = gp0d(gpmodel, m, s); return; end % 1) If necessary: re-compute cached variables persistent iK iK2 beta oldX; ridge = 1e-6; % jitter to make matrix better conditioned [n, D] = size(gpmodel.inputs); % number of examples and dimension of inputs E = size(gpmodel.targets,2); % number of examples and number of outputs X = gpmodel.hyp; input = gpmodel.inputs; targets = gpmodel.targets; [np pD pE] = size(gpmodel.induce); % number of pseudo inputs per dimension pinput = gpmodel.induce; % all pseudo inputs if numel(X) ~= numel(oldX) || isempty(iK) || isempty(iK2) || ... % if necessary sum(any(X ~= oldX)) || numel(iK2) ~=E*np^2 || numel(iK) ~= n*np*E oldX = X; % compute K, inv(K), inv(K2) iK = zeros(np,n,E); iK2 = zeros(np,np,E); beta = zeros(np,E); for i = 1:E pinp = bsxfun(@rdivide,pinput(:,:,min(i,pE)),exp(X(1:D,i)')); inp = bsxfun(@rdivide,input,exp(X(1:D,i)')); Kmm = exp(2*X(D+1,i)-maha(pinp,pinp)/2) + ridge*eye(np); % add small ridge Kmn = exp(2*X(D+1,i)-maha(pinp,inp)/2); L = chol(Kmm)'; V = L\Kmn; % inv(sqrt(Kmm))*Kmn if isfield(gpmodel,'nigp') G = exp(2*X(D+1,i))-sum(V.^2)+gpmodel.nigp(:,i)'; else G = exp(2*X(D+1,i))-sum(V.^2); end G = sqrt(1+G/exp(2*X(D+2,i))); V = bsxfun(@rdivide,V,G); Am = chol(exp(2*X(D+2,i))*eye(np) + V*V')'; At = L*Am; % chol(sig*B) [Snelson's thesis, p. 40] iAt = At\eye(np); % The following is not an inverse matrix, but we'll treat it as such: multiply % the targets from right and the cross-covariances left to get predictive mean. iK(:,:,i) = ((Am\(bsxfun(@rdivide,V,G)))'*iAt)'; beta(:,i) = iK(:,:,i)*targets(:,i); iB = iAt'*iAt.*exp(2*X(D+2,i)); % inv(B), [Snelson's thesis, p. 40] iK2(:,:,i) = Kmm\eye(np) - iB; % covariance matrix for predictive variances end end k = zeros(np,E); M = zeros(E,1); V = zeros(D,E); S = zeros(E); % allocate dMds = zeros(E,D,D); dSdm = zeros(E,E,D); r = zeros(1,D); dSds = zeros(E,E,D,D); dVds = zeros(D,E,D,D); T = zeros(D); inp = zeros(np,D,E); % 2) Compute predicted mean and inv(s) times input-output covariance for i = 1:E inp(:,:,i) = bsxfun(@minus,pinput(:,:,min(i,pE)),m'); % centralize p-inputs L = diag(exp(-X(1:D,i))); in = inp(:,:,i)*L; B = L*s*L+eye(D); LiBL = L/B*L; % iR = LiBL; t = in/B; l = exp(-sum(in.*t,2)/2); lb = l.*beta(:,i); tL = t*L; tlb = bsxfun(@times,tL,lb); c = exp(2*X(D+1,i))/sqrt(det(B)); M(i) = c*sum(lb); V(:,i) = tL'*lb*c; % inv(s) times input-output covariance dMds(i,:,:) = c*tL'*tlb/2 - LiBL*M(i)/2; for d = 1:D dVds(d,i,:,:) = c*bsxfun(@times,tL,tL(:,d))'*tlb/2 - LiBL*V(d,i)/2 ... - (V(:,i)*LiBL(d,:) + LiBL(:,d)*V(:,i)')/2; end k(:,i) = 2*X(D+1,i)-sum(in.*in,2)/2; end dMdm = V'; dVdm = 2*permute(dMds,[2 1 3]); % derivatives wrt m iell2 = exp(-2*gpmodel.hyp(1:D,:)); inpiell2 = bsxfun(@times,inp,permute(iell2,[3,1,2])); % N-by-D-by-E % 3) Compute predictive covariance matrix, non-central moments for i=1:E ii = inpiell2(:,:,i); for j=1:i R = s*diag(iell2(:,i)+iell2(:,j))+eye(D); t = 1/sqrt(det(R)); ij = inpiell2(:,:,j); L = exp(bsxfun(@plus,k(:,i),k(:,j)')+maha(ii,-ij,R\s/2)); if i==j iKL = iK2(:,:,i).*L; s1iKL = sum(iKL,1); s2iKL = sum(iKL,2); S(i,j) = t*(beta(:,i)'*L*beta(:,i) - sum(s1iKL)); zi = ii/R; bibLi = L'*beta(:,i).*beta(:,i); cbLi = L'*bsxfun(@times, beta(:,i), zi); r = (bibLi'*zi*2 - (s2iKL' + s1iKL)*zi)*t; for d = 1:D T(d,1:d) = 2*(zi(:,1:d)'*(zi(:,d).*bibLi) + ... cbLi(:,1:d)'*(zi(:,d).*beta(:,i)) - zi(:,1:d)'*(zi(:,d).*s2iKL) ... - zi(:,1:d)'*(iKL*zi(:,d))); T(1:d,d) = T(d,1:d)'; end else zi = ii/R; zj = ij/R; S(i,j) = beta(:,i)'*L*beta(:,j)*t; S(j,i) = S(i,j); bibLj = L*beta(:,j).*beta(:,i); bjbLi = L'*beta(:,i).*beta(:,j); cbLi = L'*bsxfun(@times, beta(:,i), zi); cbLj = L*bsxfun(@times, beta(:,j), zj); r = (bibLj'*zi+bjbLi'*zj)*t; for d = 1:D T(d,1:d) = zi(:,1:d)'*(zi(:,d).*bibLj) + ... cbLi(:,1:d)'*(zj(:,d).*beta(:,j)) + zj(:,1:d)'*(zj(:,d).*bjbLi) + ... cbLj(:,1:d)'*(zi(:,d).*beta(:,i)); T(1:d,d) = T(d,1:d)'; end end dSdm(i,j,:) = r - M(i)*dMdm(j,:)-M(j)*dMdm(i,:); dSdm(j,i,:) = dSdm(i,j,:); T = (t*T-S(i,j)*diag(iell2(:,i)+iell2(:,j))/R)/2; T = T - squeeze(M(i)*dMds(j,:,:) + M(j)*dMds(i,:,:)); dSds(i,j,:,:) = T; dSds(j,i,:,:) = T; end S(i,i) = S(i,i) + exp(2*X(D+1,i)); end % 4) Centralize moments S = S - M*M'; % 5) Vectorize derivatives dMds = reshape(dMds,[E D*D]); dSds = reshape(dSds,[E*E D*D]); dSdm = reshape(dSdm,[E*E D]); dVds = reshape(dVds,[D*E D*D]); dVdm = reshape(dVdm,[D*E D]);
github
UCL-SML/pilco-matlab-master
covSum.m
.m
pilco-matlab-master/gp/covSum.m
2,403
utf_8
bf6228b9460e36949e8a52e49b67666e
%% covSum.m % *Summary:* Compose a covariance function as the sum of other covariance % functions. This function doesn't actually compute very much on its own, it % merely does some bookkeeping, and calls other covariance functions to do the % actual work. % % function [A, B] = covSum(covfunc, logtheta, x, z) % % (C) Copyright 2006 by Carl Edward Rasmussen, 2006-03-20. % function [A, B] = covSum(covfunc, logtheta, x, z) %% Code for i = 1:length(covfunc) % iterate over covariance functions f = covfunc(i); if iscell(f{:}), f = f{:}; end % dereference cell array if necessary j(i) = cellstr(feval(f{:})); end if nargin == 1, % report number of parameters A = char(j(1)); for i=2:length(covfunc), A = [A, '+', char(j(i))]; end return end [n, D] = size(x); v = []; % v vector indicates to which covariance parameters belong for i = 1:length(covfunc), v = [v repmat(i, 1, eval(char(j(i))))]; end switch nargin case 3 % compute covariance matrix A = zeros(n, n); % allocate space for covariance matrix for i = 1:length(covfunc) % iteration over summand functions f = covfunc(i); if iscell(f{:}), f = f{:}; end % dereference cell array if necessary A = A + feval(f{:}, logtheta(v==i), x); % accumulate covariances end case 4 % compute derivative matrix or test set covariances if nargout == 2 % compute test set cavariances A = zeros(size(z,1),1); B = zeros(size(x,1),size(z,1)); % allocate space for i = 1:length(covfunc) f = covfunc(i); if iscell(f{:}), f = f{:}; end % dereference cell array if necessary [AA BB] = feval(f{:}, logtheta(v==i), x, z); % compute test covariances A = A + AA; B = B + BB; % and accumulate end else % compute derivative matrices i = v(z); % which covariance function j = sum(v(1:z)==i); % which parameter in that covariance f = covfunc(i); if iscell(f{:}), f = f{:}; end % dereference cell array if necessary A = feval(f{:}, logtheta(v==i), x, j); % compute derivative end end
github
UCL-SML/pilco-matlab-master
gp2.m
.m
pilco-matlab-master/gp/gp2.m
3,808
utf_8
5483b52dac200a108b03fb1d9e43b9a8
%% gp2.m % *Summary:* Compute joint predictions and derivatives for multiple GPs % with uncertain inputs. Does not consider the uncertainty about the underlying % function (in prediction), hence, only the GP mean function is considered. % Therefore, this representation is equivalent to a regularized RBF % network. % If gpmodel.nigp exists, individial noise contributions are added. % % % function [M, S, V] = gp2(gpmodel, m, s) % % *Input arguments:* % % gpmodel GP model struct % hyp log-hyper-parameters [D+2 x E ] % inputs training inputs [ n x D ] % targets training targets [ n x E ] % nigp (optional) individual noise variance terms [ n x E ] % m mean of the test distribution [ D x 1 ] % s covariance matrix of the test distribution [ D x D ] % % *Output arguments:* % % M mean of pred. distribution [ E x 1 ] % S covariance of the pred. distribution [ E x E ] % V inv(s) times covariance between input and output [ D x E ] % % % Copyright (C) 2008-2013 by % Marc Deisenroth, Andrew McHutchon, Joe Hall, and Carl Edward Rasmussen. % % Last modified: 2013-03-05 % %% High-Level Steps % # If necessary, re-compute cached variables % # Compute predicted mean and inv(s) times input-output covariance % # Compute predictive covariance matrix, non-central moments % # Centralize moments function [M, S, V] = gp2(gpmodel, m, s) %% Code persistent iK oldX oldIn oldOut beta oldn; D = size(gpmodel.inputs,2); % number of examples and dimension of inputs [n, E] = size(gpmodel.targets); % number of examples and number of outputs input = gpmodel.inputs; target = gpmodel.targets; X = gpmodel.hyp; % 1) if necessary: re-compute cached variables if numel(X) ~= numel(oldX) || isempty(iK) || n ~= oldn || ... sum(any(X ~= oldX)) || sum(any(oldIn ~= input)) || ... sum(any(oldOut ~= target)) oldX = X; oldIn = input; oldOut = target; oldn = n; K = zeros(n,n,E); iK = K; beta = zeros(n,E); for i=1:E % compute K and inv(K) inp = bsxfun(@rdivide,gpmodel.inputs,exp(X(1:D,i)')); K(:,:,i) = exp(2*X(D+1,i)-maha(inp,inp)/2); if isfield(gpmodel,'nigp') L = chol(K(:,:,i) + exp(2*X(D+2,i))*eye(n) + diag(gpmodel.nigp(:,i)))'; else L = chol(K(:,:,i) + exp(2*X(D+2,i))*eye(n))'; end iK(:,:,i) = L'\(L\eye(n)); beta(:,i) = L'\(L\gpmodel.targets(:,i)); end end k = zeros(n,E); M = zeros(E,1); V = zeros(D,E); S = zeros(E); inp = bsxfun(@minus,gpmodel.inputs,m'); % centralize inputs % 2) Compute predicted mean and inv(s) times input-output covariance for i=1:E iL = diag(exp(-X(1:D,i))); % inverse length-scales in = inp*iL; B = iL*s*iL+eye(D); t = in/B; l = exp(-sum(in.*t,2)/2); lb = l.*beta(:,i); tL = t*iL; c = exp(2*X(D+1,i))/sqrt(det(B)); M(i) = sum(lb)*c; % predicted mean V(:,i) = tL'*lb*c; % inv(s) times input-output covariance k(:,i) = 2*X(D+1,i)-sum(in.*in,2)/2; end % 3) Compute predictive covariance, non-central moments for i=1:E ii = bsxfun(@rdivide,inp,exp(2*X(1:D,i)')); for j=1:i R = s*diag(exp(-2*X(1:D,i))+exp(-2*X(1:D,j)))+eye(D); t = 1/sqrt(det(R)); ij = bsxfun(@rdivide,inp,exp(2*X(1:D,j)')); L = exp(bsxfun(@plus,k(:,i),k(:,j)')+maha(ii,-ij,R\s/2)); S(i,j) = t*beta(:,i)'*L*beta(:,j); S(j,i) = S(i,j); end S(i,i) = S(i,i) + 1e-6; % add small jitter for numerical reasons end % 4) Centralize moments S = S - M*M';
github
UCL-SML/pilco-matlab-master
gp0.m
.m
pilco-matlab-master/gp/gp0.m
3,761
utf_8
335c986e61bbf92aae2cc328b0d56a18
%% gp0.m % *Summary:* Compute joint predictions for multiple GPs with uncertain inputs. % If gpmodel.nigp exists, individial noise contributions are added. % Predictive variances contain uncertainty about the function, but no noise. % % function [M, S, V] = gp0(gpmodel, m, s) % % *Input arguments:* % % gpmodel GP model struct % hyp log-hyper-parameters [D+2 x E ] % inputs training inputs [ n x D ] % targets training targets [ n x E ] % nigp (optional) individual noise variance terms [ n x E ] % m mean of the test distribution [ D x 1 ] % s covariance matrix of the test distribution [ D x D ] % % *Output arguments:* % % M mean of pred. distribution [ E x 1 ] % S covariance of the pred. distribution [ E x E ] % V inv(s) times covariance between input and output [ D x E ] % % % Copyright (C) 2008-2013 by % Marc Deisenroth, Andrew McHutchon, Joe Hall, and Carl Edward Rasmussen. % % Last modified: 2013-05-24 % %% High-Level Steps % # If necessary, compute kernel matrix and cache it % # Compute predicted mean and inv(s) times input-output covariance % # Compute predictive covariance matrix, non-central moments % # Centralize moments function [M, S, V] = gp0(gpmodel, m, s) %% Code persistent K iK beta oldX oldn; [n, D] = size(gpmodel.inputs); % number of examples and dimension of inputs [n, E] = size(gpmodel.targets); % number of examples and number of outputs X = gpmodel.hyp; % short hand for hyperparameters % 1) if necessary: re-compute cashed variables if numel(X) ~= numel(oldX) || isempty(iK) || sum(any(X ~= oldX)) || n ~= oldn oldX = X; oldn = n; iK = zeros(n,n,E); K = zeros(n,n,E); beta = zeros(n,E); for i=1:E % compute K and inv(K) inp = bsxfun(@rdivide,gpmodel.inputs,exp(X(1:D,i)')); K(:,:,i) = exp(2*X(D+1,i)-maha(inp,inp)/2); if isfield(gpmodel,'nigp') L = chol(K(:,:,i) + exp(2*X(D+2,i))*eye(n) + diag(gpmodel.nigp(:,i)))'; else L = chol(K(:,:,i) + exp(2*X(D+2,i))*eye(n))'; end iK(:,:,i) = L'\(L\eye(n)); beta(:,i) = L'\(L\gpmodel.targets(:,i)); end end k = zeros(n,E); M = zeros(E,1); V = zeros(D,E); S = zeros(E); inp = bsxfun(@minus,gpmodel.inputs,m'); % centralize inputs % 2) compute predicted mean and inv(s) times input-output covariance for i=1:E iL = diag(exp(-X(1:D,i))); % inverse length-scales in = inp*iL; B = iL*s*iL+eye(D); t = in/B; l = exp(-sum(in.*t,2)/2); lb = l.*beta(:,i); tiL = t*iL; c = exp(2*X(D+1,i))/sqrt(det(B)); M(i) = sum(lb)*c; % predicted mean V(:,i) = tiL'*lb*c; % inv(s) times input-output covariance k(:,i) = 2*X(D+1,i)-sum(in.*in,2)/2; end % 3) ompute predictive covariance, non-central moments for i=1:E ii = bsxfun(@rdivide,inp,exp(2*X(1:D,i)')); for j=1:i R = s*diag(exp(-2*X(1:D,i))+exp(-2*X(1:D,j)))+eye(D); t = 1/sqrt(det(R)); ij = bsxfun(@rdivide,inp,exp(2*X(1:D,j)')); L = exp(bsxfun(@plus,k(:,i),k(:,j)')+maha(ii,-ij,R\s/2)); if i==j S(i,i) = t*(beta(:,i)'*L*beta(:,i) - sum(sum(iK(:,:,i).*L))); else S(i,j) = beta(:,i)'*L*beta(:,j)*t; S(j,i) = S(i,j); end end S(i,i) = S(i,i) + exp(2*X(D+1,i)); end % 4) centralize moments S = S - M*M';
github
UCL-SML/pilco-matlab-master
gpr.m
.m
pilco-matlab-master/gp/gpr.m
2,833
utf_8
3f1c270a5d7daccb9115e4d97f87bb61
%% gpr.m % *Summary:* Gaussian process regression, with a named covariance function. Two % modes are possible: training and prediction: if no test data are given, the % function returns minus the log likelihood and its partial derivatives with % respect to the hyperparameters; this mode is used to fit the hyperparameters. % If test data are given, then (marginal) Gaussian predictions are computed, % whose mean and variance are returned. Note that in cases where the covariance % function has noise contributions, the variance returned in S2 is for noisy % test targets; if you want the variance of the noise-free latent function, you % must substract the noise variance. % % usage: [nlml dnlml] = gpr(logtheta, covfunc, x, y) % or: [mu S2] = gpr(logtheta, covfunc, x, y, xstar) % % where: % % logtheta is a (column) vector of log hyperparameters % covfunc is the covariance function % x is a n by D matrix of training inputs % y is a (column) vector (of size n) of targets % xstar is a nn by D matrix of test inputs % nlml is the returned value of the negative log marginal likelihood % dnlml is a (column) vector of partial derivatives of the negative % log marginal likelihood wrt each log hyperparameter % mu is a (column) vector (of size nn) of prediced means % S2 is a (column) vector (of size nn) of predicted variances % % For more help on covariance functions, see "help covFunctions". % % (C) Copyright 2006 by Carl Edward Rasmussen (2006-03-20). function [out1, out2] = gpr(logtheta, covfunc, x, y, xstar) %% Code if ischar(covfunc), covfunc = cellstr(covfunc); end % convert to cell if needed [n, D] = size(x); if eval(feval(covfunc{:})) ~= size(logtheta, 1) error('Error: Number of parameters do not agree with covariance function') end K = feval(covfunc{:}, logtheta, x); % compute training set covariance matrix L = chol(K)'; % cholesky factorization of the covariance alpha = solve_chol(L',y); if nargin == 4 % if no test cases, compute the negative log marginal likelihood out1 = 0.5*y'*alpha + sum(log(diag(L))) + 0.5*n*log(2*pi); if nargout == 2 % ... and if requested, its partial derivatives out2 = zeros(size(logtheta)); % set the size of the derivative vector W = L'\(L\eye(n))-alpha*alpha'; % precompute for convenience for i = 1:length(out2) out2(i) = sum(sum(W.*feval(covfunc{:}, logtheta, x, i)))/2; end end else % ... otherwise compute (marginal) test predictions ... [Kss, Kstar] = feval(covfunc{:}, logtheta, x, xstar); % test covariances out1 = Kstar' * alpha; % predicted means if nargout == 2 v = L\Kstar; out2 = Kss - sum(v.*v)'; end end
github
UCL-SML/pilco-matlab-master
fitc.m
.m
pilco-matlab-master/gp/fitc.m
4,699
utf_8
388c5581c035c02a82aa9b9526160dd8
%% fitc.m % *Summary:* Compute the FITC negative log marginal likelihood and its % derivatives with respect to the inducing inputs (we don't compute the % derivatives with respect to the GP hyper-parameters) % % function [nml dnml] = fitc(induce, gpmodel) % % *Input arguments:* % % induce matrix of inducing inputs [M x D x uE] % M: number of inducing inputs % E: either 1 (inducing inputs are shared across target dim.) % or E (different inducing inputs for each target dim.) % gpmodel GP structure % .hyp log-hyper-parameters [D+2 x E] % .inputs training inputs [N x D] % .targets training targets [N x E] % .noise (opt) noise % % % *Output arguments:* % % nlml negative log-marginal likelihood % dnlml derivative of negative log-marginal likelihood wrt % inducing inputs % % Adapted from Ed Snelson's SPGP code. % % Copyright (C) 2008-2013 by % Marc Deisenroth, Andrew McHutchon, Joe Hall, and Carl Edward Rasmussen. % % Last modified: 2013-05-21 % %% High-Level Steps % % # Compute FITC marginal likelihood % # Compute corresponding gradients wrt the pseudo inputs function [nlml dnlml] = fitc(induce, gpmodel) %% Code ridge = 1e-06; % jitter to make matrix better conditioned [N D] = size(gpmodel.inputs); E = size(gpmodel.targets,2); [M uD uE] = size(induce); if uD ~= D || (uE~=1 && uE ~= E); error('Wrong size of inducing inputs'); end nlml = 0; dfxb = zeros(M, D); dnlml = zeros(M, D, E); % zero and allocate outputs for j = 1:E if uE > 1; u = induce(:,:,j); else u = induce; end b = exp(gpmodel.hyp(1:D,j)); % length-scales c = gpmodel.hyp(D+1,j); % log signal std dev sig = exp(2.*gpmodel.hyp(D+2,j)); % noise variance xb = bsxfun(@rdivide,u,b'); % divide inducing by lengthscales x = bsxfun(@rdivide,gpmodel.inputs,b'); % divide inputs by length-scales y = gpmodel.targets(:,j); % training targets Kmm = exp(2*c-maha(xb,xb)/2) + ridge*eye(M); Kmn = exp(2*c-maha(xb,x)/2); % Check whether Kmm is no longer positive definite. If so, return try L = chol(Kmm)'; catch nlml = Inf; dnlml = zeros(size(params)); return; end V = L\Kmn; % inv(sqrt(Kmm))*Kmn if isfield(gpmodel,'noise') Gamma = 1 + (exp(2*c)-sum(V.^2)'+gpmodel.noise(:,j))/sig; else Gamma = 1 + (exp(2*c)-sum(V.^2)')/sig; % Gamma = diag(Knn-Qnn)/sig + I end V = bsxfun(@rdivide,V,sqrt(Gamma)'); % inv(sqrt(Kmm))*Kmn * inv(sqrt(Gamma)) y = y./sqrt(Gamma); Am = chol(sig*eye(M) + V*V')'; % chol(inv(sqrt(Kmm))*A*inv(sqrt(Kmm))) % V*V' = inv(chol(Kmm)')*K*inv(diag(Gamma))*K'*inv(chol(Kmm)')' Vy = V*y; beta = Am\Vy; nlml = nlml + sum(log(diag(Am))) + (N-M)/2*log(sig) + sum(log(Gamma))/2 ... + (y'*y - beta'*beta)/2/sig + 0.5*N*log(2*pi); if nargout == 2 % ... and if requested, its partial derivatives At = L*Am; iAt = At\eye(M); % chol(sig*B) [Ed's thesis, p. 40] iA = iAt'*iAt; % inv(sig*B) iAmV = Am\V; % inv(Am)*V B1 = At'\(iAmV); b1 = At'\beta; % b1 = B1*y iLV = L'\V; % inv(Kmm)*Kmn*inv(sqrt(Gamma)) iL = L\eye(M); iKmm = iL'*iL; mu = ((Am'\beta)'*V)'; bs = y.*(beta'*iAmV)'/sig - sum(iAmV.*iAmV)'/2 - (y.^2+mu.^2)/2/sig + 0.5; TT = iLV*(bsxfun(@times,iLV',bs)); Kmn = bsxfun(@rdivide,Kmn,sqrt(Gamma)'); % overwrite Kmn for i = 1:D % derivatives wrt inducing inputs dsq_mm = bsxfun(@minus,xb(:,i),xb(:,i)').*Kmm; dsq_mn = bsxfun(@minus,-xb(:,i),-x(:,i)').*Kmn; dGamma = -2/sig*dsq_mn.*iLV; dfxb(:,i) = -b1.*(dsq_mn*(y-mu)/sig + dsq_mm*b1) + dGamma*bs ... + sum((iKmm - iA*sig).*dsq_mm,2) - 2/sig*sum(dsq_mm.*TT,2); dsq_mn = dsq_mn.*B1; % overwrite dsq_mn dfxb(:,i) = dfxb(:,i) + sum(dsq_mn,2); dfxb(:,i) = dfxb(:,i)/b(i); end dnlml(:,:,j) = dfxb; end end if 1 == uE; dnlml = sum(dnlml,3); end % combine derivatives if sharing inducing
github
UCL-SML/pilco-matlab-master
train.m
.m
pilco-matlab-master/gp/train.m
4,025
utf_8
951ec2e880bdaaee127eb29562311025
%% train.m % *Summary:* Train a GP model with SE covariance function (ARD). First, the % hyper-parameters are trained using a full GP. Then, if gpmodel.induce exists, % indicating sparse approximation, if enough training exmples are present, % train the inducing inputs (hyper-parameters are taken from the full GP). % If no inducing inputs are present, then initialize thme to be a % random subset of the training inputs. % % function [gpmodel nlml] = train(gpmodel, dump, iter) % % *Input arguments:* % % gpmodel GP structure % inputs GP training inputs [ N x D] % targets GP training targets [ N x E] % hyp (optional) GP log-hyper-parameters [D+2 x E] % induce (optional) pseudo inputs for sparse GP % dump not needed for this code, but required % for compatibility reasons % iter optimization iterations for training [1 x 2] % [full GP, sparse GP] % % *Output arguments:* % % gpmodel updated GP structure % nlml negative log-marginal likelihood % % % Copyright (C) 2008-2013 by % Marc Deisenroth, Andrew McHutchon, Joe Hall, and Carl Edward Rasmussen. % % Last modified: 2016-07-11 % %% High-Level Steps % # Initialization % # Train full GP % # If necessary: train sparse GP (FITC/SPGP) function [gpmodel nlml] = train(gpmodel, dump, iter) %% Code % 1) Initialization if nargin < 3, iter = [-500 -1000]; end % default training iterations D = size(gpmodel.inputs,2); E = size(gpmodel.targets,2); % get variable sizes covfunc = {'covSum', {'covSEard', 'covNoise'}}; % specify ARD covariance curb.snr = 1000; curb.ls = 100; curb.std = std(gpmodel.inputs); % set hyp curb if ~isfield(gpmodel,'hyp') % if we don't pass in hyper-parameters, define them gpmodel.hyp = zeros(D+2,E); nlml = zeros(1,E); lh = repmat([log(std(gpmodel.inputs)) 0 -1]',1,E); % init hyp length scales lh(D+1,:) = log(std(gpmodel.targets)); % signal std dev lh(D+2,:) = log(std(gpmodel.targets)/10); % noise std dev else lh = gpmodel.hyp; % GP hyper-parameters end % 2a) Train full GP (always) fprintf('Train hyper-parameters of full GP ...\n'); for i = 1:E % train each GP separately fprintf('GP %i/%i\n', i, E); try % BFGS training [gpmodel.hyp(:,i) v] = minimize(lh(:,i), @hypCurb, iter(1), covfunc, ... gpmodel.inputs, gpmodel.targets(:,i), curb); catch % conjugate gradients (BFGS can be quite aggressive) [gpmodel.hyp(:,i) v] = minimize(lh(:,i), @hypCurb, ... struct('length', iter(1), 'method', 'CG', 'verbosity', 1), covfunc, ... gpmodel.inputs, gpmodel.targets(:,i), curb); end nlml(i) = v(end); end % 2b) If necessary: sparse training using FITC/SPGP (Snelson & Ghahramani, 2006) if isfield(gpmodel,'induce') % are we using a sparse approximation? [N D] = size(gpmodel.inputs); [M uD uE] = size(gpmodel.induce); if M >= N; return; end % if too few training examples, we don't need FITC fprintf('Train pseudo-inputs of sparse GP ...\n'); if uD == 0 % we don't have inducing inputs yet? gpmodel.induce = zeros(M,D,uE); % allocate space iter = 3*iter; % train a lot for the first time (it's still cheap!) % [cidx, ctrs] = kmeans(gpmodel.inputs, M); % kmeans: initialize pseudo inputs for i = 1:uE j = randperm(N); gpmodel.induce(:,:,i) = gpmodel.inputs(j(1:M),:); % random subset % gpmodel.induce(:,:,i) = ctrs; end end % train sparse model [gpmodel.induce nlml2] = minimize(gpmodel.induce, 'fitc', iter(end), gpmodel); fprintf('GP NLML, full: %e, sparse: %e, diff: %e\n', ... sum(nlml), nlml2(end), nlml2(end)-sum(nlml)); end
github
UCL-SML/pilco-matlab-master
covNoise.m
.m
pilco-matlab-master/gp/covNoise.m
1,086
utf_8
40d4e24e7127f8134528c2c8f8772626
%% covNoise.m % Independent covariance function, ie "white noise", with specified variance. % The covariance function is specified as: % % k(x^p,x^q) = s2 * \delta(p,q) % % where s2 is the noise variance and \delta(p,q) is a Kronecker delta function % which is 1 iff p=q and zero otherwise. The hyperparameter is % % logtheta = [ log(sqrt(s2)) ] % % For more help on design of covariance functions, try "help covFunctions". % % (C) Copyright 2006 by Carl Edward Rasmussen, 2006-03-24. function [A, B] = covNoise(logtheta, x, z) %% Code if nargin == 0, A = '1'; return; end % report number of parameters s2 = exp(2*logtheta); % noise variance if nargin == 2 % compute covariance matrix A = s2*eye(size(x,1)); elseif nargout == 2 % compute test set covariances A = s2; B = 0; % zeros cross covariance by independence else % compute derivative matrix A = 2*s2*eye(size(x,1)); end
github
UCL-SML/pilco-matlab-master
minimize.m
.m
pilco-matlab-master/util/minimize.m
13,669
utf_8
4532d014f593db54fa59610e074f6261
%% minimize.m % minimize.m - minimize a smooth differentiable multivariate function using % LBFGS (Limited memory LBFGS) or CG (Conjugate Gradients) % Usage: [X, fX, i] = minimize(X, F, p, other, ... ) % where % X is an initial guess (any type: vector, matrix, cell array, struct) % F is the objective function (function pointer or name) % p parameters - if p is a number, it corresponds to p.length below % p.length allowed 1) # linesearches or 2) if -ve minus # func evals % p.method minimization method, 'BFGS', 'LBFGS' or 'CG' % p.verbosity 0 quiet, 1 line, 2 line + warnings (default), 3 graphical % p.mem number of directions used in LBFGS (default 100) % other, ... other parameters, passed to the function F % X returned minimizer % fX vector of function values showing minimization progress % i final number of linesearches or function evaluations % The function F must take the following syntax [f, df] = F(X, other, ...) % where f is the function value and df its partial derivatives. The types of X % and df must be identical (vector, matrix, cell array, struct, etc). % % Copyright (C) 1996 - 2011 by Carl Edward Rasmussen, 2013-02-12. % Permission is hereby granted, free of charge, to any person OBTAINING A COPY % OF THIS SOFTWARE AND ASSOCIATED DOCUMENTATION FILES (THE "SOFTWARE"), TO DEAL % IN THE SOFTWARE WITHOUT RESTRICTION, INCLUDING WITHOUT LIMITATION THE RIGHTS % to use, copy, modify, merge, publish, distribute, sublicense, and/or sell % copies of the Software, and to permit persons to whom the Software is % furnished to do so, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR % IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, % FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE % AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER % LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, % OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE % SOFTWARE. function [X, fX, i, p] = minimize(X, F, p, varargin) if isnumeric(p), p = struct('length', p); end % convert p to struct if p.length > 0, p.S = 'linesearch #'; else p.S = 'function evaluation #'; end; x = unwrap(X); % convert initial guess to vector if ~isfield(p,'method'), if length(x) > 1000, p.method = @LBFGS; else p.method = @BFGS; end; end % set default method if ~isfield(p,'verbosity'), p.verbosity = 1; end % default 1 line text output if ~isfield(p,'MFEPLS'), p.MFEPLS = 10; end % Max Func Evals Per Line Search if ~isfield(p,'MSR'), p.MSR = 100; end % Max Slope Ratio default if isfield(p,'fh')&&~isempty(p.fh)&&ishandle(p.fh); clf(p.fh); end f(F, X, varargin{:}); % set up the function f [fx, dfx] = f(x); % initial function value and derivatives if ~isscalar(fx); error('Objective function value must be a scalar'); end if any(isnan(fx+dfx)) || any(isinf(fx+dfx)); error('Evaluating objective function with initial parameters returns NaN or Inf'); end if p.verbosity, printf('Initial Function Value %4.6e\n', fx); end if p.verbosity > 2, ah = ahandles(p); hold(ah(1),'on'); xlabel(ah(1),p.S); ylabel(ah(1),'function value'); plot(ah(1),p.length < 0, fx, '+'); drawnow; end [x, fX, i, p] = feval(p.method, x, fx, dfx, p); % minimize using direction method X = rewrap(X, x); % convert answer to original representation if p.verbosity, printf('\n'); end function [x, fx, i, p] = CG(x0, fx0, dfx0, p) if ~isfield(p, 'SIG'), p.SIG = 0.1; end % default for line search quality i = p.length < 0; ok = 1; % initialize resource counter r = -dfx0; s = -r'*r; b = -1/(s-1); bs = -1; fx = fx0; % steepest descent while i < abs(p.length) b = b*bs/min(b*s,bs/p.MSR); % suitable initial step size using slope ratio b = min(b,1/norm(r)); % limit step size in parameter space b = max(b,1e-7/norm(r)); [x, b, fx0, dfx, i] = lineSearch(x0, fx0, dfx0, r, s, b, i, p); if i < 0 % if line search failed i = -i; if ok, ok = 0; r = -dfx; else break; end % try steepest or stop else ok = 1; bs = b*s; % record step times slope (for slope ratio method) r = (dfx'*(dfx-dfx0))/(dfx0'*dfx0)*r - dfx; % Polack-Ribiere CG end s = r'*dfx; if s >= 0, r = -dfx; s = r'*dfx; ok = 0; end % slope must be -ve x0 = x; dfx0 = dfx; fx = [fx; fx0]; % replace old values with new ones end function [x, fx, i, p] = BFGS(x0, fx0, dfx0, p) if ~isfield(p, 'SIG'), p.SIG = 0.5; end % default for line search quality i = p.length < 0; ok = 1; % initialize resource counter x = x0; fx = fx0; r = -dfx0; s = -r'*r; b = -1/(s-1); H = eye(length(x0)); while i < abs(p.length) b = min(b,1/norm(r)); % limit step size in parameter space b = max(b,1e-7/norm(r)); [x, b, fx0, dfx, i] = lineSearch(x0, fx0, dfx0, r, s, b, i, p); if i < 0 i = -i; if ok, ok = 0; else break; end; % try steepest or stop else ok = 1; t = x - x0; y = dfx - dfx0; ty = t'*y; Hy = H*y; H = H + (ty+y'*Hy)/ty^2*t*t' - 1/ty*Hy*t' - 1/ty*t*Hy'; % BFGS update end r = -H*dfx; s = r'*dfx; x0 = x; dfx0 = dfx; fx = [fx; fx0]; p.H = H; end function [x, fx, i, p] = LBFGS(x0, fx0, dfx0, p); if ~isfield(p, 'SIG'), p.SIG = 0.5; end % default for line search quality n = length(x0); k = 0; ok = 1; x = x0; fx = fx0; bs = -1/p.MSR; if isfield(p, 'mem'), m = p.mem; else m = min(100, n); end % set memory size a = zeros(1, m); t = zeros(n, m); y = zeros(n, m); % allocate memory i = p.length < 0; % initialize resource counter while i < abs(p.length) q = dfx0; for j = rem(k-1:-1:max(0,k-m),m)+1 a(j) = t(:,j)'*q/rho(j); q = q-a(j)*y(:,j); end if k == 0, r = -q/(q'*q); else r = -t(:,j)'*y(:,j)/(y(:,j)'*y(:,j))*q; end for j = rem(max(0,k-m):k-1,m)+1 r = r-t(:,j)*(a(j)+y(:,j)'*r/rho(j)); end s = r'*dfx0; if s >= 0, r = -dfx0; s = r'*dfx0; k = 0; ok = 0; end b = bs/min(bs,s/p.MSR); % suitable initial step size (usually 1) b = min(b,1/norm(r)); % limit step size in parameter space b = max(b,1e-7/norm(r)); if isnan(r) | isinf(r) % if nonsense direction i = -i; % try steepest or stop else [x, b, fx0, dfx, i] = lineSearch(x0, fx0, dfx0, r, s, b, i, p); end if i < 0 % if line search failed i = -i; if ok, ok = 0; k = 0; else break; end % try steepest or stop else j = rem(k,m)+1; t(:,j) = x-x0; y(:,j) = dfx-dfx0; rho(j) = t(:,j)'*y(:,j); ok = 1; k = k+1; bs = b*s; end x0 = x; dfx0 = dfx; fx = [fx; fx0]; % replace and add values end function [x, a, fx, df, i] = lineSearch(x0, f0, df0, d, s, a, i, p) if p.length < 0, LIMIT = min(p.MFEPLS, -i-p.length); else LIMIT = p.MFEPLS; end p0.x = 0.0; p0.f = f0; p0.df = df0; p0.s = s; p1 = p0; % init p0 and p1 j = 0; p3.x = a; wp(p0, p.SIG, 0); % set step & Wolfe-Powell conditions if p.verbosity > 2 A = [-a a]/5; nd = norm(d); ah = ahandles(p); hold(ah(2),'off'); plot(ah(2),0, f0, 'k+'); hold(ah(2),'on'); plot(ah(2),nd*A, f0+s*A, 'k-'); xlabel(ah(2),'distance in line search direction'); ylabel(ah(2),'function value'); end while 1 % keep extrapolating as long as necessary ok = 0; while ~ok && j < LIMIT try % try, catch and bisect to safeguard extrapolation evaluation j = j+1; [p3.f p3.df] = f(x0+p3.x*d); p3.s = p3.df'*d; ok = 1; if isnan(p3.f+p3.s) || isinf(p3.f+p3.s) error('Objective function returned Inf or NaN',''); end; catch if p.verbosity > 1, printf('\n'); warning(lasterr); end % warn or silence p3.x = (p1.x+p3.x)/2; ok = 0; p3.f = NaN; p3.s = NaN;% bisect, and retry end end if p.verbosity > 2 ah = ahandles(p); hold(ah(2),'on'); plot(ah(2),nd*p3.x, p3.f, 'b+'); plot(ah(2),nd*(p3.x+A), p3.f+p3.s*A, 'b-'); drawnow end if wp(p3) || j >= LIMIT, break; end % done? p0 = p1; p1 = p3; % move points back one unit p3.x = p0.x + minCubic(p1.x-p0.x, p1.f-p0.f, p0.s, p1.s, 1); % cubic extrap end while 1 % keep interpolating as long as necessary if isnan(p3.f+p3.s) || isinf(p3.f+p3.s); p2 = p1; break; end % if final extrap failed if p1.f > p3.f, p2 = p3; else p2 = p1; end % make p2 the best so far if wp(p2) > 1 || j >= LIMIT, break; end % done? p2.x = p1.x + minCubic(p3.x-p1.x, p3.f-p1.f, p1.s, p3.s, 0); % cubic interp ok = 0; while ~ok && j < LIMIT; % until function successfully evaluated or j = LIMIT try % try to evaluate objective function j = j+1; [p2.f p2.df] = f(x0+p2.x*d); p2.s = p2.df'*d; ok = 1; if isnan(p2.f+p2.s) || isinf(p2.f+p2.s) error('Objective function returned Inf or NaN',''); end catch % failed to successfully evaluate function if p.verbosity > 1, printf('\n'); warning(lasterr); end % warn or silence p2.x = (p1.x+p2.x)/2; ok = 0; if LIMIT == j; p2 = p1; end end end if p.verbosity > 2 ah = ahandles(p); hold(ah(2),'on'); plot(ah(2),nd*p2.x, p2.f, 'r+'); plot(ah(2),nd*(p2.x+A), p2.f+p2.s*A, 'r'); drawnow end if wp(p2) > -1 && p2.s > 0 || wp(p2) < -1, p3 = p2; else p1 = p2; end % bracket end x = x0+p2.x*d; fx = p2.f; df = p2.df; a = p2.x; % return the value found if p.length < 0, i = i+j; else i = i+1; end % count func evals or line searches if p.verbosity, printf('%s %6i; value %4.6e\r', p.S, i, fx); end if wp(p2) < 2, i = -i; end % indicate faliure if p.verbosity > 2 ah = ahandles(p); hold(ah(1),'on'); hold(ah(2),'on'); if i>0, plot(ah(2),norm(d)*p2.x, fx, 'go'); end plot(ah(1),abs(i), fx, '+'); drawnow; end function z = minCubic(x, df, s0, s1, extr) % minimizer of approximating cubic INT = 0.1; EXT = 5.0; % interpolate and extrapolation limits A = -6*df+3*(s0+s1)*x; B = 3*df-(2*s0+s1)*x; z = -s0*x*x/(B+sqrt(B*B-A*s0*x)); if extr % are we extrapolating? if ~isreal(z) | ~isfinite(z) | z < x | z > x*EXT, z = EXT*x; end % fix bad z z = max(z, (1+INT)*x); % extrapolate by at least INT else % else, we are interpolating if ~isreal(z) | ~isfinite(z) | z < 0 | z > x, z = x/2; end; % fix bad z z = min(max(z, INT*x), (1-INT)*x); % at least INT away from the boundaries end function y = wp(p, SIG, RHO) persistent a b c sig rho; if nargin == 3 % if three arguments, then set up the Wolfe-Powell conditions a = RHO*p.s; b = p.f; c = -SIG*p.s; sig = SIG; rho = RHO; y = 0; else if p.f > a*p.x+b % function value too large? if a > 0, y = -1; else y = -2; end else if p.s < -c, y = 0; elseif p.s > c, y = 1; else y = 2; end % if sig*abs(p.s) > c, a = rho*p.s; b = p.f-a*p.x; c = sig*abs(p.s); end end end function [fx, dfx] = f(varargin) persistent F p; if nargout == 0 p = varargin; if ischar(p{1}), F = str2func(p{1}); else F = p{1}; end else [fx, dfx] = F(rewrap(p{2}, varargin{1}), p{3:end}); dfx = unwrap(dfx); end function v = unwrap(s) % extract num elements of s (any type) into v (vector) v = []; if isnumeric(s) v = s(:); % numeric values are recast to column vector elseif isstruct(s) v = unwrap(struct2cell(orderfields(s))); % alphabetize, conv to cell, recurse elseif iscell(s) % cell array elements are for i = 1:numel(s), v = [v; unwrap(s{i})]; end % handled sequentially end % other types are ignored function [s v] = rewrap(s, v) % map elements of v (vector) onto s (any type) if isnumeric(s) if numel(v) < numel(s) error('The vector for conversion contains too few elements') end s = reshape(v(1:numel(s)), size(s)); % numeric values are reshaped v = v(numel(s)+1:end); % remaining arguments passed on elseif isstruct(s) [s p] = orderfields(s); p(p) = 1:numel(p); % alphabetize, store ordering [t v] = rewrap(struct2cell(s), v); % convert to cell, recurse s = orderfields(cell2struct(t,fieldnames(s),1),p); % conv to struct, reorder elseif iscell(s) for i = 1:numel(s) % cell array elements are handled sequentially [s{i} v] = rewrap(s{i}, v); end end % other types are not processed function printf(varargin) fprintf(varargin{:}); if exist('fflush','builtin') fflush(stdout); end function ah = ahandles(p) persistent fh if isfield(p,'fh') && ~isempty(p.fh) && ishandle(p.fh); fh = p.fh; elseif isempty(fh) || ~ishandle(fh); fh = figure; end ah(1) = subplot(2,1,1,'Parent',fh); ah(2) = subplot(2,1,2,'Parent',fh);
github
UCL-SML/pilco-matlab-master
gSat.m
.m
pilco-matlab-master/util/gSat.m
2,628
utf_8
fef6d775a326be1ea04c570d514a6c10
%% gSat.m % *Summary:* Compute moments of the saturating function % $e*(9*\sin(x(i))+\sin(3*x(i)))/8$, % where $x \sim\mathcal N(m,v)$ and $i$ is a (possibly empty) set of $I$ % indices. The optional scaling factor $e$ is a vector of length $I$. % Optionally, compute derivatives of the moments. % % function [M, S, C, dMdm, dSdm, dCdm, dMdv, dSdv, dCdv] = gSat(m, v, i, e) % % *Input arguments:* % % m mean vector of Gaussian [ d ] % v covariance matrix [ d x d ] % i vector of indices of elements to augment [ I x 1 ] % e (optional) scale vector; default: 1 [ I x 1 ] % % *Output arguments:* % % M output means [ I ] % V output covariance matrix [ I x I ] % C inv(v) times input-output covariance [ d x I ] % dMdm derivatives of M w.r.t m [ I x d ] % dVdm derivatives of V w.r.t m [I*^2 x d ] % dCdm derivatives of C w.r.t m [d*I x d ] % dMdv derivatives of M w.r.t v [ I x d^2] % dVdv derivatives of V w.r.t v [I^2 x d^2] % dCdv derivatives of C w.r.t v [d*I x d^2] % % % % Copyright (C) 2008-2013 by % Marc Deisenroth, Andrew McHutchon, Joe Hall, and Carl Edward Rasmussen. % % Last modified: 2013-03-25 function [M, S, C, dMdm, dSdm, dCdm, dMdv, dSdv, dCdv] = gSat(m, v, i, e) %% Code d = length(m); I = length(i); i = i(:)'; if nargin < 4; e = ones(1, I); end; e = e(:)'; P = [eye(d); 3*eye(d)]; % augment inputs ma = P*m; madm = P; va = P*v*P'; vadv = kron(P,P); va = (va+va')/2; % do the actual augmentation with the right parameters [M2, S2, C2, Mdma, Sdma, Cdma, Mdva, Sdva, Cdva] ... = gSin(ma, va, [i d+i], [9*e e]/8); P = [eye(I) eye(I)]; Q = [eye(d) 3*eye(d)]; M = P*M2; % mean S = P*S2*P'; S = (S+S')/2; % variance C = Q*C2*P'; % inv(v) times input-output cov if nargout > 3 % derivatives if required dMdm = P*Mdma*madm; dMdv = P*Mdva*vadv; dSdm = kron(P,P)*Sdma*madm; dSdv = kron(P,P)*Sdva*vadv; dCdm = kron(P,Q)*Cdma*madm; dCdv = kron(P,Q)*Cdva*vadv; end
github
UCL-SML/pilco-matlab-master
sq_dist.m
.m
pilco-matlab-master/util/sq_dist.m
2,207
utf_8
682c4b378252a4c8eeefa4439c364fc2
%% sq_dist.m % sq_dist - a function to compute a matrix of all pairwise squared distances % between two sets of vectors, stored in the columns of the two matrices, a % (of size D by n) and b (of size D by m). If only a single argument is given % or the second matrix is empty, the missing matrix is taken to be identical % to the first. % % Special functionality: If an optional third matrix argument Q is given, it % must be of size n by m, and in this case a vector of the traces of the % product of Q' and the coordinatewise squared distances is returned. % % NOTE: The program code is written in the C language for efficiency and is % contained in the file sq_dist.c, and should be compiled using matlabs mex % facility. However, this file also contains a (less efficient) matlab % implementation, supplied only as a help to people unfamiliar with mex. If % the C code has been properly compiled and is avaiable, it automatically % takes precendence over the matlab code in this file. % % Usage: C = sq_dist(a, b) % or: C = sq_dist(a) or equiv.: C = sq_dist(a, []) % or: c = sq_dist(a, b, Q) % where the b matrix may be empty. % % where a is of size D by n, b is of size D by m (or empty), C and Q are of % size n by m and c is of size D by 1. % % Copyright (c) 2003, 2004, 2005 and 2006 Carl Edward Rasmussen. 2006-03-09. function C = sq_dist(a, b, Q); %% Code if nargin < 1 | nargin > 3 | nargout > 1 error('Wrong number of arguments.'); end if nargin == 1 | isempty(b) % input arguments are taken to be b = a; % identical if b is missing or empty end [D, n] = size(a); [d, m] = size(b); if d ~= D error('Error: column lengths must agree.'); end if nargin < 3 C = zeros(n,m); for d = 1:D C = C + (repmat(b(d,:), n, 1) - repmat(a(d,:)', 1, m)).^2; end % C = repmat(sum(a.*a)',1,m)+repmat(sum(b.*b),n,1)-2*a'*b could be used to % replace the 3 lines above; it would be faster, but numerically less stable. else if [n m] == size(Q) C = zeros(D,1); for d = 1:D C(d) = sum(sum((repmat(b(d,:), n, 1) - repmat(a(d,:)', 1, m)).^2.*Q)); end else error('Third argument has wrong size.'); end end
github
UCL-SML/pilco-matlab-master
unwrap.m
.m
pilco-matlab-master/util/unwrap.m
902
utf_8
3856da2312d3091678383d3130b7479d
%% unwrap.m % *Summary:* Extract the numerical values from $s$ into the column vector $v$. % The variable $sS can be of any type, including struct and cell array. % Non-numerical elements are ignored. See also the reverse rewrap.m. % % v = unwrap(s) % % *Input arguments:* % % s structure, cell, or numeric values % % % *Output arguments:* % % v structure, cell, or numeric values % % % Copyright (C) 2008-2013 by % Marc Deisenroth, Andrew McHutchon, Joe Hall, and Carl Edward Rasmussen. % % Last modified: 2013-03-25 function v = unwrap(s) %% Code v = []; if isnumeric(s) v = s(:); % numeric values are recast to column vector elseif isstruct(s) v = unwrap(struct2cell(orderfields(s))); % alphabetize, conv to cell, recurse elseif iscell(s) for i = 1:numel(s) % cell array elements are handled sequentially v = [v; unwrap(s{i})]; end end
github
UCL-SML/pilco-matlab-master
trigSquash_old.m
.m
pilco-matlab-master/util/trigSquash_old.m
4,316
utf_8
ea7d2aed20d2f2142502765686cf0a6a
% Augment a Gaussian with e*sin(x(i)), where i is a (possibly % empty) set of I indices. The optional e scaling factor is a vector of length % I. Optionally, compute derivatives of the parameters of the new Gaussian. % % Copyright (C) 2007, 2008 & 2009 by Carl Edward Rasmussen, 2009-07-07. function [m, v, dmda, dmdb, dvda, dvdb] = trigSquash(a, b, i, e) % a is the mean vector of length "d" of a Gaussian distribution % b is the "d" by "d" covariance matrix % i is a vector of length I of indices of elements to augment % e is an optional scale vector of length I (defaults to unity) % % m is a vector of length "D" of means % v is a "D" by "D" covariance matrix % dmda is a "D" by "d" matrix of derivatives of "m" wrt "a" % dmdb is a "D" by "d" by "d" matrix of derivatives of "m" wrt "b" % dvda is a "D" by "D" by "d" matrix of derivatives of "v" wrt "a" % dvdb is a "D" by "D" by "d" by "d" matrix of derivatives of "v" wrt "b" % % where the size "D" is "d+I". d = length(a); I = length(i); D = d+I; if nargin == 3, e = ones(I,1); else e = e(:); end % unit column default ai(1:I,1) = a(i); bi = b(i,i); bii(1:I,1) = diag(bi); % short-hand notation m = zeros(D,1); m(1:d) = a; % first the means m(d+1:end) = e.*exp(-bii/2).*sin(ai); v = zeros(D); v(1:d,1:d) = b; % the covariance v(d+1:end,1:d) = b(i,:).*repmat(e.*exp(-bii/2).*cos(ai),1,d); v(1:d,d+1:end) = v(d+1:end,1:d)'; % symmetric entries for j=1:I for k=1:I if j==k q = e(j)*e(k)*(1-exp(-bii(j)))/2; v(d+j,d+j) = q*(1+exp(-bii(j))*cos(2*ai(j))); else q = e(j)*e(k)*exp(-(bii(j)+bii(k))/2)/2; % for numerical reasons: logq = log(e(j)) + log(e(k)) -(bii(j)+bii(k))/2 - log(2); v(d+j,d+k) = (exp(logq + bi(j,k))-q)*cos(ai(j)-ai(k))... - (exp(logq-bi(j,k))-q)*cos(ai(j)+ai(k)); end end end if nargout > 2 % compute derivatives? dmda = zeros(D,d); dmda(1:d,:) = eye(d); dmda(d+1:end,i) = diag(e.*exp(-bii/2).*cos(ai)); dmdb = zeros(D,d,d); for j=1:I dmdb(d+j,i(j),i(j)) = -m(d+j)/2; end dvda = zeros(D,D,d); for j=1:I z = e(j)*b(:,i(j))*exp(-bii(j)/2); dvda(d+j,1:d,i(j)) = -z'*sin(ai(j)); dvda(1:d,d+j,i(j)) = -z*sin(ai(j)); for k=1:I if j==k z = e(j)*e(k)*(1-exp(-bii(j)))*exp(-bii(j)); dvda(d+j,d+j,i(j)) = -z*sin(2*ai(j)); else q = e(j)*e(k)*exp(-(bii(j)+bii(k))/2)/2; logq = log(e(j)) + log(e(k)) -(bii(j)+bii(k))/2 - log(2); dvda(d+j,d+k,i(j)) = -(exp(logq + bi(j,k))-q)*sin(ai(j)-ai(k)) + ... (exp(logq - bi(j,k))-q)*sin(ai(j)+ai(k)); dvda(d+j,d+k,i(k)) = (exp(logq + bi(j,k))-q)*sin(ai(j)-ai(k)) + ... (exp(logq - bi(j,k))-q)*sin(ai(j)+ai(k)); end end end dvdb = zeros(D,D,d,d); for j=1:d, for k=1:d, dvdb(j,k,j,k) = 0.5; dvdb(j,k,k,j) = dvdb(j,k,k,j) + 0.5; end, end for j=1:I dvdb(d+j,1:d,i(j),i(j)) = -v(d+j,1:d)/2; dvdb(1:d,d+j,i(j),i(j)) = -v(d+j,1:d)'/2; for k=1:I % derivative of trig variance w.r.t. input variance if j==k % trig variance q = e(j)*e(k)*exp(-bii(j))/2; dvdb(d+j,d+j,i(j),i(j)) = q*(1+cos(2*ai(j))*(2*exp(-bii(j))-1)); else % trig-trig covariance terms logq = log(e(j)) + log(e(k)) -(bii(j)+bii(k))/2 - log(2); dvdb(d+j,d+k,i(j),i(k)) = 0.5*((exp(logq+bi(j,k))*cos(ai(j)-ai(k)) + ... exp(logq-bi(j,k))*cos(ai(j)+ai(k)))); dvdb(d+k,d+j,i(j),i(k)) = dvdb(d+j,d+k,i(j),i(k)); dvdb(d+j,d+k,i(j),i(j)) = -v(d+j,d+k)/2; dvdb(d+j,d+k,i(k),i(k)) = -v(d+j,d+k)/2; end end z = e(j)*exp(-bii(j)/2)/2; zz = e(j)*(1-bii(j)/2)*exp(-bii(j)/2); for k = 1:d % derivative of covariance of trig-nontrig w.r.t input variance if k == i(j) dvdb(k,d+j,k,k) = zz*cos(ai(j)); dvdb(d+j,k,k,k) = zz*cos(ai(j)); else dvdb(k,d+j,k,i(j)) = z*cos(ai(j)); dvdb(d+j,k,k,i(j)) = z*cos(ai(j)); dvdb(k,d+j,i(j),k) = z*cos(ai(j)); dvdb(d+j,k,i(j),k) = z*cos(ai(j)); end end end end
github
UCL-SML/pilco-matlab-master
gTrig.m
.m
pilco-matlab-master/util/gTrig.m
4,963
utf_8
997f08390a915af387fa08125f79a454
%% gTrig.m % *Summary:* Compute moments of the saturating function $e*sin(x(i))$ and $ % e*cos(x(i))$, where $x \sim\mathcal N(m,v)$ and $i$ is a (possibly empty) % set of $I$ indices. The optional scaling factor $e$ is a vector of % length $I$. Optionally, compute derivatives of the moments. % % [M, V, C, dMdm, dVdm, dCdm, dMdv, dVdv, dCdv] = gTrig(m, v, i, e) % % *Input arguments:* % % m mean vector of Gaussian [ d ] % v covariance matrix [ d x d ] % i vector of indices of elements to augment [ I x 1 ] % e (optional) scale vector; default: 1 [ I x 1 ] % % *Output arguments:* % % M output means [ 2I ] % V output covariance matrix [ 2I x 2I ] % C inv(v) times input-output covariance [ d x 2I ] % dMdm derivatives of M w.r.t m [ 2I x d ] % dVdm derivatives of V w.r.t m [4II x d ] % dCdm derivatives of C w.r.t m [2dI x d ] % dMdv derivatives of M w.r.t v [ 2I x d^2 ] % dVdv derivatives of V w.r.t v [4II x d^2 ] % dCdv derivatives of C w.r.t v [2dI x d^2 ] % % % % Copyright (C) 2008-2013 by % Marc Deisenroth, Andrew McHutchon, Joe Hall, and Carl Edward Rasmussen. % % Last modified: 2013-03-25 function [M, V, C, dMdm, dVdm, dCdm, dMdv, dVdv, dCdv] = gTrig(m, v, i, e) %% Code d = length(m); I = length(i); Ic = 2*(1:I); Is = Ic-1; if nargin == 3, e = ones(I,1); else e = e(:); end; ee = reshape([e e]',2*I,1); mi(1:I,1) = m(i); vi = v(i,i); vii(1:I,1) = diag(vi); % short-hand notation M(Is,1) = e.*exp(-vii/2).*sin(mi); M(Ic,1) = e.*exp(-vii/2).*cos(mi); % mean lq = -bsxfun(@plus,vii,vii')/2; q = exp(lq); U1 = (exp(lq+vi)-q).*sin(bsxfun(@minus,mi,mi')); U2 = (exp(lq-vi)-q).*sin(bsxfun(@plus,mi,mi')); U3 = (exp(lq+vi)-q).*cos(bsxfun(@minus,mi,mi')); U4 = (exp(lq-vi)-q).*cos(bsxfun(@plus,mi,mi')); V(Is,Is) = U3 - U4; V(Ic,Ic) = U3 + U4; V(Is,Ic) = U1 + U2; V(Ic,Is) = V(Is,Ic)'; V = ee*ee'.*V/2; % variance C = zeros(d,2*I); C(i,Is) = diag(M(Ic)); C(i,Ic) = diag(-M(Is)); % inv(v) * cov if nargout > 3 % compute derivatives? dVdm = zeros(2*I,2*I,d); dCdm = zeros(d,2*I,d); dVdv = zeros(2*I,2*I,d,d); dCdv = zeros(d,2*I,d,d); dMdm = C'; for j = 1:I u = zeros(I,1); u(j) = 1/2; dVdm(Is,Is,i(j)) = e*e'.*(-U1.*bsxfun(@minus,u,u')+U2.*bsxfun(@plus,u,u')); dVdm(Ic,Ic,i(j)) = e*e'.*(-U1.*bsxfun(@minus,u,u')-U2.*bsxfun(@plus,u,u')); dVdm(Is,Ic,i(j)) = e*e'.*(U3.*bsxfun(@minus,u,u') +U4.*bsxfun(@plus,u,u')); dVdm(Ic,Is,i(j)) = dVdm(Is,Ic,i(j))'; dVdv(Is(j),Is(j),i(j),i(j)) = exp(-vii(j)) * ... (1+(2*exp(-vii(j))-1)*cos(2*mi(j)))*e(j)*e(j)/2; dVdv(Ic(j),Ic(j),i(j),i(j)) = exp(-vii(j)) * ... (1-(2*exp(-vii(j))-1)*cos(2*mi(j)))*e(j)*e(j)/2; dVdv(Is(j),Ic(j),i(j),i(j)) = exp(-vii(j)) * ... (1-2*exp(-vii(j)))*sin(2*mi(j))*e(j)*e(j)/2; dVdv(Ic(j),Is(j),i(j),i(j)) = dVdv(Is(j),Ic(j),i(j),i(j)); for k = [1:j-1 j+1:I] dVdv(Is(j),Is(k),i(j),i(k)) = (exp(lq(j,k)+vi(j,k)).*cos(mi(j)-mi(k)) ... + exp(lq(j,k)-vi(j,k)).*cos(mi(j)+mi(k)))*e(j)*e(k)/2; dVdv(Is(j),Is(k),i(j),i(j)) = -V(Is(j),Is(k))/2; dVdv(Is(j),Is(k),i(k),i(k)) = -V(Is(j),Is(k))/2; dVdv(Ic(j),Ic(k),i(j),i(k)) = (exp(lq(j,k)+vi(j,k)).*cos(mi(j)-mi(k)) ... - exp(lq(j,k)-vi(j,k)).*cos(mi(j)+mi(k)))*e(j)*e(k)/2; dVdv(Ic(j),Ic(k),i(j),i(j)) = -V(Ic(j),Ic(k))/2; dVdv(Ic(j),Ic(k),i(k),i(k)) = -V(Ic(j),Ic(k))/2; dVdv(Ic(j),Is(k),i(j),i(k)) = -(exp(lq(j,k)+vi(j,k)).*sin(mi(j)-mi(k)) ... + exp(lq(j,k)-vi(j,k)).*sin(mi(j)+mi(k)))*e(j)*e(k)/2; dVdv(Ic(j),Is(k),i(j),i(j)) = -V(Ic(j),Is(k))/2; dVdv(Ic(j),Is(k),i(k),i(k)) = -V(Ic(j),Is(k))/2; dVdv(Is(j),Ic(k),i(j),i(k)) = (exp(lq(j,k)+vi(j,k)).*sin(mi(j)-mi(k)) ... - exp(lq(j,k)-vi(j,k)).*sin(mi(j)+mi(k)))*e(j)*e(k)/2; dVdv(Is(j),Ic(k),i(j),i(j)) = -V(Is(j),Ic(k))/2; dVdv(Is(j),Ic(k),i(k),i(k)) = -V(Is(j),Ic(k))/2; end dCdm(i(j),Is(j),i(j)) = -M(Is(j)); dCdm(i(j),Ic(j),i(j)) = -M(Ic(j)); dCdv(i(j),Is(j),i(j),i(j)) = -C(i(j),Is(j))/2; dCdv(i(j),Ic(j),i(j),i(j)) = -C(i(j),Ic(j))/2; end dMdv = permute(dCdm,[2 1 3])/2; dMdv = reshape(dMdv,[2*I d*d]); dVdv = reshape(dVdv,[4*I*I d*d]); dVdm = reshape(dVdm,[4*I*I d]); dCdv = reshape(dCdv,[d*2*I d*d]); dCdm = reshape(dCdm,[d*2*I d]); end
github
UCL-SML/pilco-matlab-master
error_ellipse.m
.m
pilco-matlab-master/util/error_ellipse.m
8,229
utf_8
9f67e27c9f6218404167e7eb24c0cf57
%% error_ellipse.m % ERROR_ELLIPSE - plot an error ellipse, or ellipsoid, defining confidence region % ERROR_ELLIPSE(C22) - Given a 2x2 covariance matrix, plot the % associated error ellipse, at the origin. It returns a graphics handle % of the ellipse that was drawn. % % ERROR_ELLIPSE(C33) - Given a 3x3 covariance matrix, plot the % associated error ellipsoid, at the origin, as well as its projections % onto the three axes. Returns a vector of 4 graphics handles, for the % three ellipses (in the X-Y, Y-Z, and Z-X planes, respectively) and for % the ellipsoid. % % ERROR_ELLIPSE(C,MU) - Plot the ellipse, or ellipsoid, centered at MU, % a vector whose length should match that of C (which is 2x2 or 3x3). % % ERROR_ELLIPSE(...,'Property1',Value1,'Name2',Value2,...) sets the % values of specified properties, including: % 'C' - Alternate method of specifying the covariance matrix % 'mu' - Alternate method of specifying the ellipse (-oid) center % 'conf' - A value betwen 0 and 1 specifying the confidence interval. % the default is 0.5 which is the 50% error ellipse. % 'scale' - Allow the plot the be scaled to difference units. % 'style' - A plotting style used to format ellipses. % 'clip' - specifies a clipping radius. Portions of the ellipse, -oid, % outside the radius will not be shown. % % NOTES: C must be positive definite for this function to work properly. % % % by AJ Johnson % http://www.mathworks.de/matlabcentral/fileexchange/4705 function h=error_ellipse(varargin) %% Code default_properties = struct(... 'C', [], ... % The covaraince matrix (required) 'mu', [], ... % Center of ellipse (optional) 'conf', 0.95, ... % Percent confidence/100 'scale', 1, ... % Scale factor, e.g. 1e-3 to plot m as km 'style', '', ... % Plot style 'clip', inf); % Clipping radius if length(varargin) >= 1 & isnumeric(varargin{1}) default_properties.C = varargin{1}; varargin(1) = []; end if length(varargin) >= 1 & isnumeric(varargin{1}) default_properties.mu = varargin{1}; varargin(1) = []; end if length(varargin) >= 1 & isnumeric(varargin{1}) default_properties.conf = varargin{1}; varargin(1) = []; end if length(varargin) >= 1 & isnumeric(varargin{1}) default_properties.scale = varargin{1}; varargin(1) = []; end if length(varargin) >= 1 & ~ischar(varargin{1}) error('Invalid parameter/value pair arguments.') end prop = getopt(default_properties, varargin{:}); C = prop.C; if isempty(prop.mu) mu = zeros(length(C),1); else mu = prop.mu; end conf = prop.conf; scale = prop.scale; style = prop.style; if conf <= 0 | conf >= 1 error('conf parameter must be in range 0 to 1, exclusive') end [r,c] = size(C); if r ~= c | (r ~= 2 & r ~= 3) error(['Don''t know what to do with ',num2str(r),'x',num2str(c),' matrix']) end x0=mu(1); y0=mu(2); % Compute quantile for the desired percentile k = sqrt(qchisq(conf,r)); % r is the number of dimensions (degrees of freedom) hold_state = get(gca,'nextplot'); if r==3 & c==3 z0=mu(3); % Make the matrix has positive eigenvalues - else it's not a valid covariance matrix! if any(eig(C) <=0) error('The covariance matrix must be positive definite (it has non-positive eigenvalues)') end % C is 3x3; extract the 2x2 matricies, and plot the associated error % ellipses. They are drawn in space, around the ellipsoid; it may be % preferable to draw them on the axes. Cxy = C(1:2,1:2); Cyz = C(2:3,2:3); Czx = C([3 1],[3 1]); [x,y,z] = getpoints(Cxy,prop.clip); h1=plot3(x0+k*x,y0+k*y,z0+k*z,prop.style,'linewidth',2);hold on [y,z,x] = getpoints(Cyz,prop.clip); h2=plot3(x0+k*x,y0+k*y,z0+k*z,prop.style,'linewidth',2);hold on [z,x,y] = getpoints(Czx,prop.clip); h3=plot3(x0+k*x,y0+k*y,z0+k*z,prop.style,'linewidth',2);hold on [eigvec,eigval] = eig(C); [X,Y,Z] = ellipsoid(0,0,0,1,1,1); XYZ = [X(:),Y(:),Z(:)]*sqrt(eigval)*eigvec'; X(:) = scale*(k*XYZ(:,1)+x0); Y(:) = scale*(k*XYZ(:,2)+y0); Z(:) = scale*(k*XYZ(:,3)+z0); h4=surf(X,Y,Z); colormap gray alpha(0.3) camlight if nargout h=[h1 h2 h3 h4]; end elseif r==2 & c==2 % Make the matrix has positive eigenvalues - else it's not a valid covariance matrix! if any(eig(C) <=0) error('The covariance matrix must be positive definite (it has non-positive eigenvalues)') end [x,y,z] = getpoints(C,prop.clip); h1=plot(scale*(x0+k*x),scale*(y0+k*y),prop.style,'linewidth',2); set(h1,'zdata',z+1) if nargout h=h1; end else error('C (covaraince matrix) must be specified as a 2x2 or 3x3 matrix)') end %axis equal set(gca,'nextplot',hold_state); %--------------------------------------------------------------- % getpoints - Generate x and y points that define an ellipse, given a 2x2 % covariance matrix, C. z, if requested, is all zeros with same shape as % x and y. function [x,y,z] = getpoints(C,clipping_radius) n=100; % Number of points around ellipse p=0:pi/n:2*pi; % angles around a circle [eigvec,eigval] = eig(C); % Compute eigen-stuff xy = [cos(p'),sin(p')] * sqrt(eigval) * eigvec'; % Transformation x = xy(:,1); y = xy(:,2); z = zeros(size(x)); % Clip data to a bounding radius if nargin >= 2 r = sqrt(sum(xy.^2,2)); % Euclidian distance (distance from center) x(r > clipping_radius) = nan; y(r > clipping_radius) = nan; z(r > clipping_radius) = nan; end %--------------------------------------------------------------- function x=qchisq(P,n) % QCHISQ(P,N) - quantile of the chi-square distribution. if nargin<2 n=1; end s0 = P==0; s1 = P==1; s = P>0 & P<1; x = 0.5*ones(size(P)); x(s0) = -inf; x(s1) = inf; x(~(s0|s1|s))=nan; for ii=1:14 dx = -(pchisq(x(s),n)-P(s))./dchisq(x(s),n); x(s) = x(s)+dx; if all(abs(dx) < 1e-6) break; end end %--------------------------------------------------------------- function F=pchisq(x,n) % PCHISQ(X,N) - Probability function of the chi-square distribution. if nargin<2 n=1; end F=zeros(size(x)); if rem(n,2) == 0 s = x>0; k = 0; for jj = 0:n/2-1; k = k + (x(s)/2).^jj/factorial(jj); end F(s) = 1-exp(-x(s)/2).*k; else for ii=1:numel(x) if x(ii) > 0 F(ii) = quadl(@dchisq,0,x(ii),1e-6,0,n); else F(ii) = 0; end end end %--------------------------------------------------------------- function f=dchisq(x,n) % DCHISQ(X,N) - Density function of the chi-square distribution. if nargin<2 n=1; end f=zeros(size(x)); s = x>=0; f(s) = x(s).^(n/2-1).*exp(-x(s)/2)./(2^(n/2)*gamma(n/2)); %--------------------------------------------------------------- function properties = getopt(properties,varargin) %GETOPT - Process paired optional arguments as 'prop1',val1,'prop2',val2,... % % getopt(properties,varargin) returns a modified properties structure, % given an initial properties structure, and a list of paired arguments. % Each argumnet pair should be of the form property_name,val where % property_name is the name of one of the field in properties, and val is % the value to be assigned to that structure field. % % No validation of the values is performed. % % EXAMPLE: % properties = struct('zoom',1.0,'aspect',1.0,'gamma',1.0,'file',[],'bg',[]); % properties = getopt(properties,'aspect',0.76,'file','mydata.dat') % would return: % properties = % zoom: 1 % aspect: 0.7600 % gamma: 1 % file: 'mydata.dat' % bg: [] % % Typical usage in a function: % properties = getopt(properties,varargin{:}) % Process the properties (optional input arguments) prop_names = fieldnames(properties); TargetField = []; for ii=1:length(varargin) arg = varargin{ii}; if isempty(TargetField) if ~ischar(arg) error('Propery names must be character strings'); end f = find(strcmp(prop_names, arg)); if length(f) == 0 error('%s ',['invalid property ''',arg,'''; must be one of:'],prop_names{:}); end TargetField = arg; else % properties.(TargetField) = arg; % Ver 6.5 and later only properties = setfield(properties, TargetField, arg); % Ver 6.1 friendly TargetField = ''; end end if ~isempty(TargetField) error('Property names and values must be specified in pairs.'); end
github
UCL-SML/pilco-matlab-master
rewrap.m
.m
pilco-matlab-master/util/rewrap.m
1,351
utf_8
af00755de2984f738e21e52712a59fc0
%% rewrap.m % *Summary:* Map the numerical elements in the vector $v$ onto the variables % $s$, which can be of any type. The number of numerical elements must match; % on exit, $v$ should be empty. Non-numerical entries are just copied. % See also the reverse unwrap.m. % % [s v] = rewrap(s, v) % % *Input arguments:* % % s structure, cell, or numeric values % v structure, cell, or numeric values % % % *Output arguments:* % % s structure, cell, or numeric values % v [empty] % % % Copyright (C) 2008-2013 by % Marc Deisenroth, Andrew McHutchon, Joe Hall, and Carl Edward Rasmussen. % % Last modified: 2013-03-25 function [s v] = rewrap(s, v) %% Code if isnumeric(s) if numel(v) < numel(s) error('The vector for conversion contains too few elements') end s = reshape(v(1:numel(s)), size(s)); % numeric values are reshaped v = v(numel(s)+1:end); % remaining arguments passed on elseif isstruct(s) [s p] = orderfields(s); p(p) = 1:numel(p); % alphabetize, store ordering [t v] = rewrap(struct2cell(s), v); % convert to cell, recurse s = orderfields(cell2struct(t,fieldnames(s),1),p); % conv to struct, reorder elseif iscell(s) for i = 1:numel(s) % cell array elements are handled sequentially [s{i} v] = rewrap(s{i}, v); end end
github
UCL-SML/pilco-matlab-master
solve_chol.m
.m
pilco-matlab-master/util/solve_chol.m
1,014
utf_8
675d515fffa67a72cb9cce4cc8c6374e
%% solve_chol.m % solve_chol - solve linear equations from the Cholesky factorization. % Solve A*X = B for X, where A is square, symmetric, positive definite. The % input to the function is R the Cholesky decomposition of A and the matrix B. % Example: X = solve_chol(chol(A),B); % % NOTE: The program code is written in the C language for efficiency and is % contained in the file solve_chol.c, and should be compiled using matlabs mex % facility. However, this file also contains a (less efficient) matlab % implementation, supplied only as a help to people unfamiliar with mex. If % the C code has been properly compiled and is avaiable, it automatically % takes precendence over the matlab code in this file. % % Copyright (c) 2004, 2005, 2006 by Carl Edward Rasmussen. 2006-02-08. %% Code function x = solve_chol(A, B) if nargin ~= 2 | nargout > 1 error('Wrong number of arguments.'); end if size(A,1) ~= size(A,2) | size(A,1) ~= size(B,1) error('Wrong sizes of matrix arguments.'); end x = A\(A'\B);
github
UCL-SML/pilco-matlab-master
gaussian.m
.m
pilco-matlab-master/util/gaussian.m
793
utf_8
bc62e952d89ae7dfe8860f37a4f807b9
%% gaussian.m % *Summary:* Generate n samples from a Gaussian $p(x)=\mathcal N(m,S). % Sampling is based on the Cholesky factorization of the covariance matrix S % % function x = gaussian(m, S, n) % % *Input arguments:* % % m mean of Gaussian [D x 1] % S covariance matrix of Gaussian [D x D] % n (optional) number of samples; default: n=1 % % *Output arguments:* % % x matrix of samples from Gaussian [D x n] % % % Copyright (C) 2008-2013 by % Marc Deisenroth, Andrew McHutchon, Joe Hall, and Carl Edward Rasmussen. % % Last modified: 2013-03-21 function x = gaussian(m, S, n) %% Code if nargin < 3; n = 1; end x = bsxfun(@plus, m(:), chol(S)'*randn(size(S,2),n));
github
UCL-SML/pilco-matlab-master
gSin.m
.m
pilco-matlab-master/util/gSin.m
3,391
utf_8
a002d13d7d48d976738abdba11c9344d
%% gSin.m % *Summary:* Compute moments of the saturating function $e*sin(x(i))$, % where $x \sim\mathcal N(m,v)$ and $i$ is a (possibly empty) set of $I$ % indices. The optional scaling factor $e$ is a vector of length $I$. % Optionally, compute derivatives of the moments. % % function [M, V, C, dMdm, dVdm, dCdm, dMdv, dVdv, dCdv] = gSin(m, v, i, e) % % *Input arguments:* % % m mean vector of Gaussian [ d ] % v covariance matrix [ d x d ] % i vector of indices of elements to augment [ I x 1 ] % e (optional) scale vector; default: 1 [ I x 1 ] % % *Output arguments:* % % M output means [ I ] % V output covariance matrix [ I x I ] % C inv(v) times input-output covariance [ d x I ] % dMdm derivatives of M w.r.t m [ I x d ] % dVdm derivatives of V w.r.t m [I^2 x d ] % dCdm derivatives of C w.r.t m [d*I x d ] % dMdv derivatives of M w.r.t v [ I x d^2] % dVdv derivatives of V w.r.t v [I^2 x d^2] % dCdv derivatives of C w.r.t v [d*I x d^2] % % Copyright (C) 2008-2013 by % Marc Deisenroth, Andrew McHutchon, Joe Hall, and Carl Edward Rasmussen. % % Last modified: 2013-03-25 function [M, V, C, dMdm, dVdm, dCdm, dMdv, dVdv, dCdv] = gSin(m, v, i, e) %% Code d = length(m); I = length(i); if nargin == 3, e = ones(I,1); else e = e(:); end % unit column default mi(1:I,1) = m(i); vi = v(i,i); vii(1:I,1) = diag(vi); % short-hand notation M = e.*exp(-vii/2).*sin(mi); % mean lq = -bsxfun(@plus,vii,vii')/2; q = exp(lq); V = (exp(lq+vi)-q).*cos(bsxfun(@minus,mi,mi')) - ... (exp(lq-vi)-q).*cos(bsxfun(@plus,mi,mi')); V = e*e'.*V/2; % variance C = zeros(d,I); C(i,:) = diag(e.*exp(-vii/2).*cos(mi)); % inv(v) times cov if nargout > 3 % compute derivatives? dVdm = zeros(I,I,d); dCdm = zeros(d,I,d); dVdv = zeros(I,I,d,d); dCdv = zeros(d,I,d,d); dMdm = C'; U1 = -(exp(lq+vi)-q).*sin(bsxfun(@minus,mi,mi')); U2 = (exp(lq-vi)-q).*sin(bsxfun(@plus,mi,mi')); for j = 1:I u = zeros(I,1); u(j) = 1/2; dVdm(:,:,i(j)) = e*e'.*(U1.*bsxfun(@minus,u,u') + U2.*bsxfun(@plus,u,u')); dVdv(j,j,i(j),i(j)) = exp(-vii(j)) * ... (1+(2*exp(-vii(j))-1)*cos(2*mi(j)))*e(j)*e(j)/2; for k = [1:j-1 j+1:I] dVdv(j,k,i(j),i(k)) = (exp(lq(j,k)+vi(j,k)).*cos(mi(j)-mi(k)) + ... exp(lq(j,k)-vi(j,k)).*cos(mi(j)+mi(k)))*e(j)*e(k)/2; dVdv(j,k,i(j),i(j)) = -V(j,k)/2; dVdv(j,k,i(k),i(k)) = -V(j,k)/2; end dCdm(i(j),j,i(j)) = -M(j); dCdv(i(j),j,i(j),i(j)) = -C(i(j),j)/2; end dMdv = permute(dCdm,[2 1 3])/2; dMdv = reshape(dMdv,[I d*d]); dVdv = reshape(dVdv,[I*I d*d]); dVdm = reshape(dVdm,[I*I d]); dCdv = reshape(dCdv,[d*I d*d]); dCdm = reshape(dCdm,[d*I d]); end
github
UCL-SML/pilco-matlab-master
maha.m
.m
pilco-matlab-master/util/maha.m
943
utf_8
78f272e79b5be527d48c9dad4abb8d5d
%% maha.m % *Summary:* Point-wise squared Mahalanobis distance (a-b)*Q*(a-b)'. % Vectors are row-vectors % % function K = maha(a, b, Q) % % *Input arguments:* % % a matrix containing n row vectors [n x D] % b matrix containing n row vectors [n x D] % Q weight matrix. Default: eye(D) [D x D] % % % *Output arguments:* % K point-wise squared distances [n x n] % % Copyright (C) 2008-2013 by % Marc Deisenroth, Andrew McHutchon, Joe Hall, and Carl Edward Rasmussen. % % Last modified: 2013-03-21 function K = maha(a, b, Q) %% Code if nargin == 2 % assume unit Q K = bsxfun(@plus,sum(a.*a,2),sum(b.*b,2)')-2*a*b'; else aQ = a*Q; K = bsxfun(@plus,sum(aQ.*a,2),sum(b*Q.*b,2)')-2*aQ*b'; end
github
UCL-SML/pilco-matlab-master
lossSat.m
.m
pilco-matlab-master/loss/lossSat.m
2,984
utf_8
19c52ddda1502850d6c1cbe4af044594
%% lossSat.m % *Summary:* Compute expectation and variance of a saturating cost % $1 - \exp(-(x-z)^T*W*(x-z)/2)$ % and their derivatives, where x ~ N(m,S), z is a (target state), and W % is a weighting matrix % % function [L, dLdm, dLds, S, dSdm, dSds, C, dCdm, dCds] = lossSat(cost, m, s) % % *Input arguments:* % % cost % .z: target state [D x 1] % .W: weight matrix [D x D] % m mean of input distribution [D x 1] % s covariance matrix of input distribution [D x D] % % % *Output arguments:* % % L expected loss [1 x 1 ] % dLdm derivative of L wrt input mean [1 x D ] % dLds derivative of L wrt input covariance [1 x D^2] % S variance of loss [1 x 1 ] % dSdm derivative of S wrt input mean [1 x D ] % dSds derivative of S wrt input covariance [1 x D^2] % C inv(S) times input-output covariance [D x 1 ] % dCdm derivative of C wrt input mean [D x D ] % dCds derivative of C wrt input covariance [D x D^2] % % Copyright (C) 2008-2013 by % Marc Deisenroth, Andrew McHutchon, Joe Hall, and Carl Edward Rasmussen. % % Last modified: 2013-05-28 % %% High-Level Steps % # Expected cost % # Variance of cost % # inv(s)*cov(x,L) function [L, dLdm, dLds, S, dSdm, dSds, C, dCdm, dCds] = lossSat(cost, m, s) %% Code % some precomputations D = length(m); % get state dimension % set some defaults if necessary if isfield(cost,'W'); W = cost.W; else W = eye(D); end if isfield(cost,'z'); z = cost.z; else z = zeros(D,1); end SW = s*W; iSpW = W/(eye(D)+SW); % 1. Expected cost L = -exp(-(m-z)'*iSpW*(m-z)/2)/sqrt(det(eye(D)+SW)); % in interval [-1,0] % 1a. derivatives of expected cost if nargout > 1 dLdm = -L*(m-z)'*iSpW; % wrt input mean dLds = L*(iSpW*(m-z)*(m-z)'-eye(D))*iSpW/2; % wrt input covariance matrix end % 2. Variance of cost if nargout > 3 i2SpW = W/(eye(D)+2*SW); r2 = exp(-(m-z)'*i2SpW*(m-z))/sqrt(det(eye(D)+2*SW)); S = r2 - L^2; if S < 1e-12; S=0; end % for numerical reasons end % 2a. derivatives of variance of cost if nargout > 4 % wrt input mean dSdm = -2*r2*(m-z)'*i2SpW-2*L*dLdm; % wrt input covariance matrix dSds = r2*(2*i2SpW*(m-z)*(m-z)'-eye(D))*i2SpW-2*L*dLds; end % 3. inv(s)*cov(x,L) if nargout > 6 t = W*z - iSpW*(SW*z+m); C = L*t; dCdm = t*dLdm - L*iSpW; dCds = -L*(bsxfun(@times,iSpW,permute(t,[3,2,1])) + ... bsxfun(@times,permute(iSpW,[1,3,2]),t'))/2; dCds = bsxfun(@times,t,dLds(:)') + reshape(dCds,D,D^2); end L = 1+L; % bring cost to the interval [0,1]
github
UCL-SML/pilco-matlab-master
lossLin.m
.m
pilco-matlab-master/loss/lossLin.m
2,032
utf_8
420a72edfbc56bc050d2edb16c94c45e
%% lossLin.m % *Summary:* Function to compute the expected loss and its derivatives, given an % input distribution, under a linear loss function: L = a^T(x - b). Note, this % loss function can return negative loss. % % [L dLdm dLds S dSdm dSds C dCdm dCds] = lossLin(cost,m,s) % % *Input arguments:* % % cost % .a gradient of linear loss function, [D x 1] % .b targets, the value of x for which there is zero loss [D x 1] % m mean of input distribution [D x 1] % s covariance matrix of input distribution [D x D] % % *Output arguments:* % % L expected loss [1 x 1 ] % dLdm derivative of L wrt input mean [1 x D ] % dLds derivative of L wrt input covariance [1 x D^2] % S variance of loss [1 x 1 ] % dSdm derivative of S wrt input mean [1 x D ] % dSds derivative of S wrt input covariance [1 x D^2] % C inv(S) times input-output covariance [D x 1 ] % dCdm derivative of C wrt input mean [D x D ] % dCds derivative of C wrt input covariance [D x D^2] % % Copyright (C) 2008-2013 by % Marc Deisenroth, Andrew McHutchon, Joe Hall, and Carl Edward Rasmussen. % % Last modified: 2013-03-05 % %% High-Level Steps % # Expected cost % # Variance of cost % # inv(s)* cov(x,L) function [L dLdm dLds S dSdm dSds C dCdm dCds] = lossLin(cost,m,s) %% Code a = cost.a(:); b = cost.b(:); D = length(m); if length(a) ~= D || length(b) ~= D; error('a or b not the same length as m'); end % 1) Mean L = a'*(m - b); dLdm = a'; dLds = zeros(D); % 2) Variance S = a'*s*a; dSdm = zeros(1,D); dSds = a*a'; % 3) inv(s) * input-output covariance cov(x,L) C = a; dCdm = zeros(D); dCds = zeros(D,D^2);
github
UCL-SML/pilco-matlab-master
reward.m
.m
pilco-matlab-master/loss/reward.m
2,084
utf_8
8908699b1c46fed8e1d75d6b2ebb4177
%% reward.m % *Summary:* Compute expectation, variance, and their derivatives of an % exponentiated negative quadratic cost $\exp(-(x-z)'W(x-z)/2)$, % where $x\sim\mathcal N(m,S)$ % % *Input arguments:* % % m: D-by-1 mean of the state distribution % S: D-by-D covariance matrix of the state distribution % z: D-by-1 target state % W: D-by-D weight matrix % % *Output arguments:* % % muR: 1-by-1 expected reward % dmuRdm: 1-by-D derivative of expected reward wrt input mean % dmuRdS: D-by-D derivative of expected reward wrt input covariance matrix % sR: 1-by-1 variance of reward % dsRdm: 1-by-D derivative of variance of reward wrt input mean % dsRdS: D-by-D derivative reward variance wrt input covariance matrix % % Copyright (C) 2008-2013 by % Marc Deisenroth, Andrew McHutchon, Joe Hall, and Carl Edward Rasmussen. % % Last modification: 2013-01-20 % %% High-Level Steps % # Compute expected reward % # Compute the derivatives of the expected reward with respect to the input % distribution (optional) % # Compute variance of reward % # Compute the derivatives of the variance of the reward with % respect to the input distribution (optional) function [muR, dmuRdm, dmuRdS, sR, dsRdm, dsRdS] = reward(m, S, z, W) %% Code % some precomputations D = length(m); % get state dimension SW = S*W; iSpW = W/(eye(D)+SW); % 1. expected reward muR = exp(-(m-z)'*iSpW*(m-z)/2)/sqrt(det(eye(D)+SW)); % 2. derivatives of expected reward if nargout > 1 dmuRdm = -muR*(m-z)'*iSpW; % wrt input mean dmuRdS = muR*(iSpW*(m-z)*(m-z)'-eye(D))*iSpW/2; % wrt input covariance matrix end % 3. reward variance if nargout > 3 i2SpW = W/(eye(D)+2*SW); r2 = exp(-(m-z)'*i2SpW*(m-z))/sqrt(det(eye(D)+2*SW)); sR = r2 - muR^2; if sR < 1e-12; sR=0; end % for numerical reasons end % 4. derivatives of reward variance if nargout > 4 % wrt input mean dsRdm = -2*r2*(m-z)'*i2SpW-2*muR*dmuRdm; % wrt input covariance matrix dsRdS = r2*(2*i2SpW*(m-z)*(m-z)'-eye(D))*i2SpW-2*muR*dmuRdS; end
github
UCL-SML/pilco-matlab-master
lossAdd.m
.m
pilco-matlab-master/loss/lossAdd.m
3,774
utf_8
52c5dfbd0b0cd5caa9c3dd7423fe832e
%% lossAdd.m % *Summary:* Utility function to add a number of loss functions together, each of which % can be using a different loss function and operating on a different part of % the state. % % function [L, dLdm, dLds, S, dSdm, dSds, C, dCdm, dCds] = lossAdd(cost, m, s) % % *Input arguments:* % % cost cost struct % .fcn @lossAdd - called to arrive here % .sub{n} cell array of sub-loss functions to add together % .fcn handle to sub function % .losi indices of variables to be passed to loss function % .< > all fields in sub will be passed onto the sub function % .expl (optional) if present cost.expl*sqrt(S) is added to the loss % % m mean of input distribution [D x 1] % s covariance matrix of input distribution [D x D] % % *Output arguments:* % % L expected loss [1 x 1] % dLdm derivative of L wrt input mean [1 x D] % dLds derivative of L wrt input covariance [1 x D^2] % S variance of loss [1 x 1] % dSdm derivative of S wrt input mean [1 x D] % dSds derivative of S wrt input covariance [1 x D^2] % C inv(S) times input-output covariance [D x 1] % dCdm derivative of C wrt input mean [D x D] % dCds derivative of C wrt input covariance [D x D^2] % % Copyright (C) 2008-2013 by % Marc Deisenroth, Andrew McHutchon, Joe Hall, and Carl Edward Rasmussen. % % Last modified: 2013-03-05 function [L, dLdm, dLds, S, dSdm, dSds, C, dCdm, dCds] = lossAdd(cost, m, s) %% Code % Dimensions and Initializations Nlos = length(cost.sub); D = length(m); L = 0; S = 0; C = zeros(D,1); dLdm = zeros(1,D); dSdm = zeros(1,D); dLds = zeros(D); dSds = zeros(D); dCdm = zeros(D); dCds = zeros(D,D^2); for n = 1:Nlos % Loop over each of the sub-functions costi = cost.sub{n}; i = costi.losi; % slice % Call the sub loss function if nargout < 4 % Just the expected loss & derivs [Li, Ldm, Lds] = costi.fcn(costi, m(i), s(i,i)); L = L + Li; dLdm(i) = dLdm(i) + Ldm; dLds(i,i) = dLds(i,i) + Lds; else % Also loss variance and IO covariance [Li, Ldm, Lds, Si, Sdm, Sds, Ci, Cdm, Cds] = costi.fcn(costi, m(i), s(i,i)); L = L + Li; S = S + Si + Ci'*s(i,:)*C + C'*s(:,i)*Ci; % V(a+b) = V(a)+V(b)+C(a,b)+C(b,a) if nargout > 4 % derivatives dLdm(i) = dLdm(i) + Ldm; dLds(i,i) = dLds(i,i) + Lds; Cis = Ci'*(s(i,:) + s(:,i)'); Cs = C'*(s(:,i) + s(i,:)'); dSdm(i) = dSdm(i) + Sdm + Cs*Cdm; dSdm = dSdm + Cis*dCdm; dSds(i,i) = dSds(i,i) + Sds + reshape(Cs*Cds,length(i),length(i)); dSds = dSds + reshape(Cis*dCds,D,D); dSds(i,:) = dSds(i,:) + Ci*C'; dSds(:,i) = dSds(:,i) + C*Ci'; end % Input - Output covariance update C(i) = C(i) + Ci; % must be after S and its derivatives ii = sub2ind2(D,i,i); dCdm(i,i) = dCdm(i,i) + Cdm; % must be after dSdm & dSds dCds(i,ii) = dCds(i,ii) + Cds; end end % Exploration if required if isfield(cost,'expl') && nargout > 3 && cost.expl ~= 0 L = L + cost.expl*sqrt(S); dLdm = dLdm + cost.expl*0.5/sqrt(S)*dSdm; dLds = dLds + cost.expl*0.5/sqrt(S)*dSds; end function idx = sub2ind2(D,i,j) % D = #rows, i = row subscript, j = column subscript i = i(:); j = j(:)'; idx = reshape(bsxfun(@plus,D*(j-1),i),1,[]);
github
UCL-SML/pilco-matlab-master
lossHinge.m
.m
pilco-matlab-master/loss/lossHinge.m
3,596
utf_8
8065572dbe7ba938d78649a31e3aa0b1
%% lossHinge.m % *Summary:* Function to compute the moments and derivatives of the loss of a % Gaussian distributed point under a double hinge loss function. The loss % function has slope -/+a and corners b1 and b2. The function also calculates % derivatives of the loss w.r.t. the state distribution. % % Graph: % \ / % \ / % \ / % \_____________/ % b1 b2 % % To use a single hinge b1 or b2 can be set to -Inf or +Inf respectively. % % Note, this function is only analytic for 1D inputs. To apply this loss % function to multiple variables, use the lossAdd function. % % % function [L dLdm dLds S dSdm dSds C dCdm dCds dLdb] = lossHinge(cost, m, s) % % % *Input arguments:* % % cost % .fcn @lossHinge - called to get here % .a slope of loss function % .b corner points of loss function [1 x 2 ] % m input mean [D x 1 ] % S input covariance matrix [D x D ] % % *Output arguments:* % % L expected loss [1 x 1 ] % dLdm derivative of L wrt input mean [1 x D ] % dLds derivative of L wrt input covariance [1 x D^2] % S variance of loss [1 x 1 ] % dSdm derivative of S wrt input mean [1 x D ] % dSds derivative of S wrt input covariance [1 x D^2] % C inv(S) times input-output covariance [D x 1 ] % dCdm derivative of C wrt input mean [D x D ] % dCds derivative of C wrt input covariance [D x D^2] % % Copyright (C) 2008-2013 by % Marc Deisenroth, Andrew McHutchon, Joe Hall, and Carl Edward Rasmussen. % % Last modified: 2013-03-06 % %% High-Level Steps % # Expected cost % # Variance of cost % # inv(s)* cov(x,L) function [L dLdm dLds S dSdm dSds C dCdm dCds dLdb] = lossHinge(cost, m, s) %% Code D = length(m); if D > 1; error(['lossHinge only defined for 1D inputs, use lossAdd to '... 'concatenate multiple 1D loss functions']); end a = cost.a; b = cost.b(:)' - m(:)'; I = ~isinf(b); % centralize eb = exp(-b.^2/2/s); erfb = erf(b/sqrt(2*s)); c = sqrt(s/pi/2); % 1. Expected Loss % int_{-inf}^{b1-m} -a*(x-b1+m)*N(0,S) + int_{b2-m}^inf a*(x-b2+m)*N(0,S) L = a*(b/2.*erfb + c*eb + b.*[1,-1]/2); L = sum(L(I)); if nargout > 1 % Derivative w.r.t. m dLdb = a/2*(erfb + [1,-1]); dLdm = sum(dLdb(I)*-1); % Derivative w.r.t. S dc = 1/(2*sqrt(2*pi*s)); dLds = a*sum(eb)*dc; end % 2. Variance of Loss if nargout > 3 S = a^2*((b.^2+s).*(1+[1,-1].*erfb)/2 + [1,-1].*b*c.*eb); S = sum(S(I)) - L^2; erfbdm = -sqrt(2/pi/s)*eb; erfbds = -b.*eb/sqrt(2*pi*s^3); dSdm = a^2*(-b.*(1+[1,-1].*erfb) + (b.^2+s).*[1,-1].*erfbdm/2 + ... [1,-1]*c.*eb.*(-1+b.^2/s)); dSdm = sum(dSdm(I)) - 2*L*dLdm; dSds = a^2/2*((1+[1,-1].*erfb) + (b.^2+s).*[1,-1].*erfbds + ... [2,-2].*b*dc.*eb + [1,-1].*b.^3/s^2*c.*eb); dSds = sum(dSds(I)) - 2*L*dLds; end % 3. inv(s)* covariance between input and cost if nargout > 6 C = a*([-1 1] - erfb)/2; C = sum(C); dCdm = -a/2*sum(erfbdm); dCds = -a/2*sum(erfbds(I)); end
github
UCL-SML/pilco-matlab-master
lossQuad.m
.m
pilco-matlab-master/loss/lossQuad.m
2,562
utf_8
d196478052135d8a9bd1201fdcdd8fa7
%% lossQuad.m % *Summary:* Compute expectation and variance of a quadratic cost % $(x-z)'*W*(x-z)$ % and their derivatives, where $x \sim N(m,S)$ % % % function [L, dLdm, dLds, S, dSdm, dSds, C, dCdm, dCds] = lossQuad(cost, m, S) % % % % *Input arguments:* % % cost % .z: target state [D x 1] % .W: weight matrix [D x D] % m mean of input distribution [D x 1] % s covariance matrix of input distribution [D x D] % % % *Output arguments:* % % L expected loss [1 x 1 ] % dLdm derivative of L wrt input mean [1 x D ] % dLds derivative of L wrt input covariance [1 x D^2] % S variance of loss [1 x 1 ] % dSdm derivative of S wrt input mean [1 x D ] % dSds derivative of S wrt input covariance [1 x D^2] % C inv(S) times input-output covariance [D x 1 ] % dCdm derivative of C wrt input mean [D x D ] % dCds derivative of C wrt input covariance [D x D^2] % % Copyright (C) 2008-2013 by % Marc Deisenroth, Andrew McHutchon, Joe Hall, and Carl Edward Rasmussen. % % Last modified: 2013-05-30 % %% High-Level Steps % # Expected cost % # Variance of cost % # inv(s)* cov(x,L) function [L, dLdm, dLds, S, dSdm, dSds, C, dCdm, dCds] = lossQuad(cost, m, S) %% Code D = length(m); % get state dimension % set some defaults if necessary if isfield(cost,'W'); W = cost.W; else W = eye(D); end if isfield(cost,'z'); z = cost.z; else z = zeros(D,1); end % 1. expected cost L = S(:)'*W(:) + (z-m)'*W*(z-m); % 1a. derivatives of expected cost if nargout > 1 dLdm = 2*(m-z)'*W; % wrt input mean dLds = W'; % wrt input covariance matrix end % 2. variance of cost if nargout > 3 S = trace(W*S*(W + W')*S) + (z-m)'*(W + W')*S*(W + W')*(z-m); if S < 1e-12; S = 0; end % for numerical reasons end % 2a. derivatives of variance of cost if nargout > 4 % wrt input mean dSdm = -(2*(W+W')*S*(W+W)*(z-m))'; % wrt input covariance matrix dSds = W'*S'*(W + W')'+(W + W')'*S'*W' + (W + W')*(z-m)*((W + W')*(z-m))'; end % 3. inv(s) times IO covariance with derivatives if nargout > 6 C = 2*W*(m-z); dCdm = 2*W; dCds = zeros(D,D^2); end
github
UCL-SML/pilco-matlab-master
congp.m
.m
pilco-matlab-master/control/congp.m
3,929
utf_8
8a137598e0f056778e7c3ebeb2981c4a
%% congp.m % *Summary:* Implements the mean-of-GP policy (equivalent to a regularized RBF % network. Compute mean, variance and input-output covariance of % the control $u$ using a mean-of-GP policy function, when the input $x$ is % Gaussian. The GP is parameterized using a pseudo training set size N. % Optionally, compute partial derivatives wrt the input parameters. % % This version sets the signal variance to 1, the noise to 0.01 and their % respective lengthscales to zero. This results in only the lengthscales, % inputs, and outputs being trained. % % % function [M, S, C, dMdm, dSdm, dCdm, dMds, dSds, dCds, dMdp, dSdp, dCdp] ... % = congp(policy, m, s) % % % *Input arguments:* % % policy policy (struct) % .p parameters that are modified during training % .hyp GP-log hyperparameters (Ph = (d+2)*D) [ Ph ] % .inputs policy pseudo inputs [ N x d ] % .targets policy pseudo targets [ N x D ] % m mean of state distribution [ d x 1 ] % s covariance matrix of state distribution [ d x d ] % % % *Output arguments:* % % M mean of the predicted control [ D x 1 ] % S covariance of predicted control [ D x D ] % C inv(s)*covariance between input and control [ d x D ] % dMdm deriv. of mean control wrt mean of state [ D x d ] % dSdm deriv. of control variance wrt mean of state [D*D x d ] % dCdm deriv. of covariance wrt mean of state [d*D x d ] % dMds deriv. of mean control wrt variance [ D x d*d] % dSds deriv. of control variance wrt variance [D*D x d*d] % dCds deriv. of covariance wrt variance [d*D x d*d] % dMdp deriv. of mean control wrt GP hyper-parameters [ D x P ] % dSdp deriv. of control variance wrt GP hyper-parameters [D*D x P ] % dCdp deriv. of covariance wrt GP hyper-parameters [d*D x P ] % % where P = (d+2)*D + n*(d+D) is the total number of policy parameters. % % Copyright (C) 2008-2013 by % Marc Deisenroth, Andrew McHutchon, Joe Hall, and Carl Edward Rasmussen. % % Last modified: 2013-01-24 % %% High-Level Steps % # Extract policy parameters from policy structure % # Compute predicted control u inv(s)*covariance between input and control % # Set derivatives of non-free parameters to zero % # Merge derivatives function [M, S, C, dMdm, dSdm, dCdm, dMds, dSds, dCds, dMdp, dSdp, dCdp] ... = congp(policy, m, s) %% Code % 1. Extract policy parameters policy.hyp = policy.p.hyp; policy.inputs = policy.p.inputs; policy.targets = policy.p.targets; % fix policy signal and the noise variance % (avoids some potential numerical problems) policy.hyp(end-1,:) = log(1); % set signal variance to 1 policy.hyp(end,:) = log(0.01); % set noise standard dev to 0.01 % 2. Compute predicted control u inv(s)*covariance between input and control if nargout < 4 % if no derivatives are required [M, S, C] = gp2(policy, m, s); else % else compute derivatives too [M, S, C, dMdm, dSdm, dCdm, dMds, dSds, dCds, dMdi, dSdi, dCdi, dMdt, ... dSdt, dCdt, dMdh, dSdh, dCdh] = gp2d(policy, m, s); % 3. Set derivatives of non-free parameters to zero: signal and noise variance d = size(policy.inputs,2); d2 = size(policy.hyp,1); dimU = size(policy.targets,2); sidx = bsxfun(@plus,(d+1:d2)',(0:dimU-1)*d2); dMdh(:,sidx(:)) = 0; dSdh(:,sidx(:)) = 0; dCdh(:,sidx(:)) = 0; % 4. Merge derivatives dMdp = [dMdh dMdi dMdt]; dSdp = [dSdh dSdi dSdt]; dCdp = [dCdh dCdi dCdt]; end
github
UCL-SML/pilco-matlab-master
conCat.m
.m
pilco-matlab-master/control/conCat.m
4,305
utf_8
e7135e1b0710f40b0ac1151ee1a6d88d
%% concat.m % *Summary:* Compute a control signal $u$ from a state distribution % $x\sim\mathcal N(x|m,s)$. Here, the predicted control distribution % and its derivatives are computed by concatenating a controller "con" with % a saturation function "sat", such as gSat.m. % % function [M, S, C, dMdm, dSdm, dCdm, dMds, dSds, dCds, dMdp, dSdp, dCdp] ... % = conCat(con, sat, policy, m, s) % % Example call: conCat(@congp, @gSat, policy, m, s) % % *Input arguments:* % % con function handle (controller) % sat function handle (squashing function) % policy policy structure % .maxU maximum amplitude of control signal (after squashing) % m mean of input distribution [D x 1] % s covariance of input distribution [D x D] % % *Output arguments:* % % M control mean [E x 1] % S control covariance [E x E] % C inv(s)*cov(x,u) [D x E] % dMdm deriv. of expected control wrt input mean [E x D] % dSdm deriv. of control covariance wrt input mean [E*E x D] % dCdm deriv. of C wrt input mean [D*E x D] % dMds deriv. of expected control wrt input covariance [E x D*D] % dSds deriv. of control covariance wrt input covariance [E*E x D*D] % dCds deriv. of C wrt input covariance [D*E x D*D] % dMdp deriv. of expected control wrt policy parameters [E x P] % dSdp deriv. of control covariance wrt policy parameters [E*E x P] % dCdp deriv. of C wrt policy parameters [D*E x P] % % where P is the total number of policy parameters % % % Copyright (C) 2008-2013 by % Marc Deisenroth, Andrew McHutchon, Joe Hall, and Carl Edward Rasmussen. % % Last modified: 2012-07-03 % %% High-Level Steps % # Compute unsquashed control signal % # Compute squashed control signal function [M, S, C, dMdm, dSdm, dCdm, dMds, dSds, dCds, dMdp, dSdp, dCdp] ... = conCat(con, sat, policy, m, s) %% Code maxU=policy.maxU; % amplitude limit of control signal E=length(maxU); % dimension of control signal D=length(m); % dimension of input % pre-compute some indices F=D+E; j=D+1:F; i=1:D; % initialize M and S M = zeros(F,1); M(i) = m; S = zeros(F); S(i,i) = s; if nargout < 4 % without derivatives [M(j), S(j,j), Q] = con(policy, m, s); % compute unsquashed control signal v q = S(i,i)*Q; S(i,j) = q; S(j,i) = q'; % compute joint covariance S=cov(x,v) [M, S, R] = sat(M, S, j, maxU); % compute squashed control signal u C = [eye(D) Q]*R; % inv(s)*cov(x,u) else % with derivatives Mdm = zeros(F,D); Sdm = zeros(F*F,D); Mdm(1:D,1:D) = eye(D); Mds = zeros(F,D*D); Sds = kron(Mdm,Mdm); X = reshape(1:F*F,[F F]); XT = X'; % vectorized indices I=0*X;I(j,j)=1; jj=X(I==1)'; I=0*X;I(i,j)=1;ij=X(I==1)'; ji=XT(I==1)'; % 1. Unsquashed controller -------------------------------------------------- [M(j), S(j,j), Q, Mdm(j,:), Sdm(jj,:), dQdm, Mds(j,:), ... Sds(jj,:), dQds, Mdp, Sdp, dQdp] = con(policy, m, s); q = S(i,i)*Q; S(i,j) = q; S(j,i) = q'; % compute joint covariance S=cov(x,v) % update the derivatives SS = kron(eye(E),S(i,i)); QQ = kron(Q',eye(D)); Sdm(ij,:) = SS*dQdm; Sdm(ji,:) = Sdm(ij,:); Sds(ij,:) = SS*dQds + QQ; Sds(ji,:) = Sds(ij,:); % 2. Apply Saturation ------------------------------------------------------- [M, S, R, MdM, SdM, RdM, MdS, SdS, RdS] = sat(M, S, j, maxU); % apply chain-rule to compute derivatives after concatenation dMdm = MdM*Mdm + MdS*Sdm; dMds = MdM*Mds + MdS*Sds; dSdm = SdM*Mdm + SdS*Sdm; dSds = SdM*Mds + SdS*Sds; dRdm = RdM*Mdm + RdS*Sdm; dRds = RdM*Mds + RdS*Sds; dMdp = MdM(:,j)*Mdp + MdS(:,jj)*Sdp; dSdp = SdM(:,j)*Mdp + SdS(:,jj)*Sdp; dRdp = RdM(:,j)*Mdp + RdS(:,jj)*Sdp; C = [eye(D) Q]*R; % inv(s)*cov(x,u) % update the derivatives RR = kron(R(j,:)',eye(D)); QQ = kron(eye(E),[eye(D) Q]); dCdm = QQ*dRdm + RR*dQdm; dCds = QQ*dRds + RR*dQds; dCdp = QQ*dRdp + RR*dQdp; end
github
UCL-SML/pilco-matlab-master
conlin.m
.m
pilco-matlab-master/control/conlin.m
3,409
utf_8
3c0856129195fa4c0ec010e933b345f9
%% conlin.m % *Summary:* Affine controller $u = Wx + b$ with input dimension D and % control dimension E. % Compute mean and covariance of the control distribution $p(u)$ from a % Gaussian distributed input $x\sim\mathcal N(x|m,s)$. % Moreover, the $s^{-1}cov(x,u)$ is computed. % % % function [M, S, V, dMdm, dSdm, dVdm, dMds, dSds, dVds, dMdp, dSdp, dVdp] ... % = conlin(policy, m, s) % % % *Input arguments:* % % policy policy structure % .p parameters that are modified during training % .w linear weights [ E x D ] % .b biases/offset [ E ] % m mean of state distribution [ D ] % s covariance matrix of state distribution [ D x D ] % % *Output arguments:* % % M mean of predicted control [ E ] % S variance of predicted control [ E x E ] % C inv(s) times input-output covariance [ D x E ] % dMdm deriv. of mean control wrt input mean [ E x D ] % dSdm deriv. of control covariance wrt input mean [E*E x D ] % dCdm deriv. of C wrt input mean [D*E x D ] % dMds deriv. of mean control wrt input covariance [ E x D*D] % dSds deriv. of control covariance wrt input covariance [E*E x D*D] % dCds deriv. of C wrt input covariance [D*E x D*D] % dMdp deriv. of mean control wrt policy parameters [ E x P ] % dSdp deriv. of control covariance wrt policy parameters [E*E x P ] % dCdp deriv. of C wrt policy parameters [D*E x P ] % % where P = (D+1)*E is the total number of policy parameters % % Copyright (C) 2008-2013 by % Marc Deisenroth, Andrew McHutchon, Joe Hall, and Carl Edward Rasmussen. % % Last modified: 2012-07-03 % %% High-Level Steps % # Extract policy parameters from policy structure % # Predict control signal % # Compute derivatives if required % function [M, S, V, dMdm, dSdm, dVdm, dMds, dSds, dVds, dMdp, dSdp, dVdp] ... = conlin(policy, m, s) %% Code % 1. Extract policy parameters from policy structure w = policy.p.w; % weight matrix b = policy.p.b; % bias/offset [E D] = size(w); % dim of control and state % 2. Predict control signal M = w*m + b; % mean S = w*s*w'; S = (S+S')/2; % covariance V = w'; % inv(s)*input-output covariance % 3. Compute derivatives if required if nargout > 3 dMdm = w; dSdm = zeros(E*E,D); dVdm = zeros(D*E,D); dMds = zeros(E,D*D); dSds = kron(w,w); dVds = zeros(D*E,D*D); X=reshape(1:D*D,[D D]); XT=X'; dSds=(dSds+dSds(:,XT(:)))/2; % symmetrize X=reshape(1:E*E,[E E]); XT=X'; dSds=(dSds+dSds(XT(:),:))/2; wTdw =reshape(permute(reshape(eye(E*D),[E D E D]),[2 1 3 4]),[E*D E*D]); dMdp = [eye(E) kron(m',eye(E))]; dSdp = [zeros(E*E,E) kron(eye(E),w*s)*wTdw + kron(w*s,eye(E))]; dSdp = (dSdp + dSdp(XT(:),:))/2; % symmetrize dVdp = [zeros(D*E,E) wTdw]; end
github
UCL-SML/pilco-matlab-master
propagated.m
.m
pilco-matlab-master/base/propagated.m
6,815
utf_8
e9669f64759cea3c9fcef4e9f7e6ded3
%% propagated.m % *Summary:* Propagate the state distribution one time step forward % with derivatives % % function [Mnext, Snext, dMdm, dSdm, dMds, dSds, dMdp, dSdp] = ... % propagated(m, s, plant, dynmodel, policy) % % *Input arguments:* % % m mean of the state distribution at time t [D x 1] % s covariance of the state distribution at time t [D x D] % plant plant structure % dynmodel dynamics model structure % policy policy structure % % *Output arguments:* % % Mnext predicted mean at time t+1 [E x 1] % Snext predicted covariance at time t+1 [E x E] % dMdm output mean wrt input mean [E x D] % dMds output mean wrt input covariance matrix [E x D*D] % dSdm output covariance matrix wrt input mean [E*E x D ] % dSds output cov wrt input cov [E*E x D*D] % dMdp output mean wrt policy parameters [E x P] % dSdp output covariance matrix wrt policy parameters [E*E x P] % % where P is the number of policy parameters. % % Copyright (C) 2008-2013 by % Marc Deisenroth, Andrew McHutchon, Joe Hall, Henrik Ohlsson, % and Carl Edward Rasmussen. % % Last modified: 2016-07-19 % %% High-Level Steps % # Augment state distribution with trigonometric functions % # Compute distribution of the control signal % # Compute dynamics-GP prediction % # Compute distribution of the next state % function [Mnext, Snext, dMdm, dSdm, dMds, dSds, dMdp, dSdp] = ... propagated(m, s, plant, dynmodel, policy) %% Code if nargout <= 2 % just predict, no derivatives [Mnext, Snext] = propagate(m, s, plant, dynmodel, policy); return end angi = plant.angi; poli = plant.poli; dyni = plant.dyni; difi = plant.difi; D0 = length(m); % size of the input mean D1 = D0 + 2*length(angi); % length after mapping all angles to sin/cos D2 = D1 + length(policy.maxU); % length after computing control signal D3 = D2 + D0; % length after predicting M = zeros(D3,1); M(1:D0) = m; S = zeros(D3); S(1:D0,1:D0) = s; % init M and S Mdm = [eye(D0); zeros(D3-D0,D0)]; Sdm = zeros(D3*D3,D0); Mds = zeros(D3,D0*D0); Sds = kron(Mdm,Mdm); X = reshape(1:D3*D3,[D3 D3]); XT = X'; Sds = (Sds + Sds(XT(:),:))/2; X = reshape(1:D0*D0,[D0 D0]); XT = X'; Sds = (Sds + Sds(:,XT(:)))/2; % 1) Augment state distribution with trigonometric functions ------------------ i = 1:D0; j = 1:D0; k = D0+1:D1; [M(k) S(k,k) C mdm sdm Cdm mds sds Cds] = gTrig(M(i), S(i,i), angi); [S Mdm Mds Sdm Sds] = ... fillIn(S,C,mdm,sdm,Cdm,mds,sds,Cds,Mdm,Sdm,Mds,Sds,[ ],[ ],[ ],i,j,k,D3); %sn2 = exp(2*dynmodel.hyp(end,:)); sn2(difi) = sn2(difi)/2; mm=zeros(D1,1); mm(i)=M(i); ss(i,i)=S(i,i);%+diag(sn2); [mm(k), ss(k,k) C] = gTrig(mm(i), ss(i,i), angi); % noisy state measurement q = ss(j,i)*C; ss(j,k) = q; ss(k,j) = q'; % 2) Compute distribution of the control signal ------------------------------- i = poli; j = 1:D1; k = D1+1:D2; [M(k) S(k,k) C mdm sdm Cdm mds sds Cds Mdp Sdp Cdp] = ... policy.fcn(policy, mm(i), ss(i,i)); [S Mdm Mds Sdm Sds Mdp Sdp] = ... fillIn(S,C,mdm,sdm,Cdm,mds,sds,Cds,Mdm,Sdm,Mds,Sds,Mdp,Sdp,Cdp,i,j,k,D3); % 3) Compute distribution of the change in state ------------------------------ ii = [dyni D1+1:D2]; j = 1:D2; if isfield(dynmodel,'sub'), Nf = length(dynmodel.sub); else Nf = 1; end for n=1:Nf % potentially multiple dynamics models [dyn i k] = sliceModel(dynmodel,n,ii,D1,D2,D3); j = setdiff(j,k); [M(k) S(k,k) C mdm sdm Cdm mds sds Cds] = dyn.fcn(dyn, M(i), S(i,i)); [S Mdm Mds Sdm Sds Mdp Sdp] = ... fillIn(S,C,mdm,sdm,Cdm,mds,sds,Cds,Mdm,Sdm,Mds,Sds,Mdp,Sdp,[ ],i,j,k,D3); j = [j k]; % update 'previous' state vector end % 4) Compute distribution of the next state ----------------------------------- P = [zeros(D0,D2) eye(D0)]; P(difi,difi) = eye(length(difi)); P = sparse( P); Mnext = P*M; Snext = P*S*P'; Snext = (Snext+Snext')/2; PP = kron(P,P); dMdm = P*Mdm; dMds = P*Mds; dMdp = P*Mdp; dSdm = PP*Sdm; dSds = PP*Sds; dSdp = PP*Sdp; X = reshape(1:D0*D0,[D0 D0]); XT = X'; % symmetrize dS dSdm = (dSdm + dSdm(XT(:),:))/2; dMds = (dMds + dMds(:,XT(:)))/2; dSds = (dSds + dSds(XT(:),:))/2; dSds = (dSds + dSds(:,XT(:)))/2; dSdp = (dSdp + dSdp(XT(:),:))/2; % A1) Separate multiple dynamics models --------------------------------------- function [dyn i k] = sliceModel(dynmodel,n,ii,D1,D2,D3) % separate sub-dynamics if isfield(dynmodel,'sub') dyn = dynmodel.sub{n}; do = dyn.dyno; D = length(ii)+D1-D2; if isfield(dyn,'dyni'), di=dyn.dyni; else di=[]; end if isfield(dyn,'dynu'), du=dyn.dynu; else du=[]; end if isfield(dyn,'dynj'), dj=dyn.dynj; else dj=[]; end i = [ii(di) D1+du D2+dj]; k = D2+do; dyn.inputs = [dynmodel.inputs(:,[di D+du]) dynmodel.target(:,dj)]; % inputs dyn.target = dynmodel.target(:,do); % targets else dyn = dynmodel; k = D2+1:D3; i = ii; end % A2) Apply chain rule and fill out cross covariance terms -------------------- function [S Mdm Mds Sdm Sds Mdp Sdp] = ... fillIn(S,C,mdm,sdm,Cdm,mds,sds,Cds,Mdm,Sdm,Mds,Sds,Mdp,Sdp,dCdp,i,j,k,D) if isempty(k), return; end X = reshape(1:D*D,[D D]); XT = X'; % vectorized indices I=0*X; I(i,i)=1; ii=X(I==1)'; I=0*X; I(k,k)=1; kk=X(I==1)'; I=0*X; I(j,i)=1; ji=X(I==1)'; I=0*X; I(j,k)=1; jk=X(I==1)'; kj=XT(I==1)'; Mdm(k,:) = mdm*Mdm(i,:) + mds*Sdm(ii,:); % chainrule Mds(k,:) = mdm*Mds(i,:) + mds*Sds(ii,:); Sdm(kk,:) = sdm*Mdm(i,:) + sds*Sdm(ii,:); Sds(kk,:) = sdm*Mds(i,:) + sds*Sds(ii,:); dCdm = Cdm*Mdm(i,:) + Cds*Sdm(ii,:); dCds = Cdm*Mds(i,:) + Cds*Sds(ii,:); if isempty(dCdp) && nargout > 5 Mdp(k,:) = mdm*Mdp(i,:) + mds*Sdp(ii,:); Sdp(kk,:) = sdm*Mdp(i,:) + sds*Sdp(ii,:); dCdp = Cdm*Mdp(i,:) + Cds*Sdp(ii,:); elseif nargout > 5 aa = length(k); bb = aa^2; cc = numel(C); mdp = zeros(D,size(Mdp,2)); sdp = zeros(D*D,size(Mdp,2)); mdp(k,:) = reshape(Mdp,aa,[]); Mdp = mdp; sdp(kk,:) = reshape(Sdp,bb,[]); Sdp = sdp; Cdp = reshape(dCdp,cc,[]); dCdp = Cdp; end q = S(j,i)*C; S(j,k) = q; S(k,j) = q'; % off-diagonal SS = kron(eye(length(k)),S(j,i)); CC = kron(C',eye(length(j))); Sdm(jk,:) = SS*dCdm + CC*Sdm(ji,:); Sdm(kj,:) = Sdm(jk,:); Sds(jk,:) = SS*dCds + CC*Sds(ji,:); Sds(kj,:) = Sds(jk,:); if nargout > 5 Sdp(jk,:) = SS*dCdp + CC*Sdp(ji,:); Sdp(kj,:) = Sdp(jk,:); end
github
UCL-SML/pilco-matlab-master
predcost.m
.m
pilco-matlab-master/base/predcost.m
1,226
utf_8
33b93e42bfaaba81a29a0106348021c5
%% predcost.m % *Summary:* Compute trajectory of expected costs for a given set of % state distributions % % inputs: % m0 mean of states, D-by-1 or D-by-K for multiple means % S covariance matrix of state distributions % dynmodel (struct) for dynamics model (GP) % plant (struct) of system parameters % policy (struct) for policy to be implemented % cost (struct) of cost function parameters % H length of optimization horizon % % outputs: % L expected cumulative (discounted) cost % s standard deviation of cost % % Copyright (C) 2008-2013 by % Marc Deisenroth, Andrew McHutchon, Joe Hall, and Carl Edward Rasmussen. % % Last modified: 2012-01-12 % %% High-Level Steps % # Predict successor state distribution % # Predict corresponding cost distribution function [L, s] = predcost(m0, S, dynmodel, plant, policy, cost, H) %% Code L = zeros(size(m0,2),H); s = zeros(size(m0,2),H); for k = 1:size(m0,2); m = m0(:,k); for t = 1:H [m, S] = plant.prop(m, S, plant, dynmodel, policy); % get next state [L(k,t), d1, d2, v] = cost.fcn(cost, m, S); % compute cost s(k,t) = sqrt(v); end end L = mean(L,1); s = mean(s,1);
github
UCL-SML/pilco-matlab-master
propagate.m
.m
pilco-matlab-master/base/propagate.m
3,751
utf_8
981110574e60d83f95424a9b9489c04d
%% propagate.m % *Summary:* Propagate the state distribution one time step forward. % % [Mnext, Snext] = propagate(m, s, plant, dynmodel, policy) % % *Input arguments:* % % m mean of the state distribution at time t [D x 1] % s covariance of the state distribution at time t [D x D] % plant plant structure % dynmodel dynamics model structure % policy policy structure % % *Output arguments:* % % Mnext mean of the successor state at time t+1 [E x 1] % Snext covariance of the successor state at time t+1 [E x E] % % % Copyright (C) 2008-2013 by % Marc Deisenroth, Andrew McHutchon, Joe Hall, Henrik Ohlsson, % and Carl Edward Rasmussen. % % Last modified: 2016-07-19 % %% High-Level Steps % # Augment state distribution with trigonometric functions % # Compute distribution of the control signal % # Compute dynamics-GP prediction % # Compute distribution of the next state % function [Mnext, Snext] = propagate(m, s, plant, dynmodel, policy) %% Code % extract important indices from structures angi = plant.angi; % angular indices poli = plant.poli; % policy indices dyni = plant.dyni; % dynamics-model indices difi = plant.difi; % state indices where the model was trained on differences D0 = length(m); % size of the input mean D1 = D0 + 2*length(angi); % length after mapping all angles to sin/cos D2 = D1 + length(policy.maxU); % length after computing control signal D3 = D2 + D0; % length after predicting M = zeros(D3,1); M(1:D0) = m; S = zeros(D3); S(1:D0,1:D0) = s; % init M and S % 1) Augment state distribution with trigonometric functions ------------------ i = 1:D0; j = 1:D0; k = D0+1:D1; [M(k), S(k,k) C] = gTrig(M(i), S(i,i), angi); q = S(j,i)*C; S(j,k) = q; S(k,j) = q'; %sn2 = exp(2*dynmodel.hyp(end,:)); sn2(difi) = sn2(difi)/2; mm=zeros(D1,1); mm(i)=M(i); ss(i,i)=S(i,i); %+diag(sn2); [mm(k), ss(k,k) C] = gTrig(mm(i), ss(i,i), angi); % noisy state measurement q = ss(j,i)*C; ss(j,k) = q; ss(k,j) = q'; % 2) Compute distribution of the control signal ------------------------------- i = poli; j = 1:D1; k = D1+1:D2; [M(k) S(k,k) C] = policy.fcn(policy, mm(i), ss(i,i)); q = S(j,i)*C; S(j,k) = q; S(k,j) = q'; % 3) Compute dynamics-GP prediction ------------------------------ ii = [dyni D1+1:D2]; j = 1:D2; if isfield(dynmodel,'sub'), Nf = length(dynmodel.sub); else Nf = 1; end for n=1:Nf % potentially multiple dynamics models [dyn i k] = sliceModel(dynmodel,n,ii,D1,D2,D3); j = setdiff(j,k); [M(k), S(k,k), C] = dyn.fcn(dyn, M(i), S(i,i)); q = S(j,i)*C; S(j,k) = q; S(k,j) = q'; j = [j k]; % update 'previous' state vector end % 4) Compute distribution of the next state ----------------------------------- P = [zeros(D0,D2) eye(D0)]; P(difi,difi) = eye(length(difi)); Mnext = P*M; Snext = P*S*P'; Snext = (Snext+Snext')/2; function [dyn i k] = sliceModel(dynmodel,n,ii,D1,D2,D3) % separate sub-dynamics % A1) Separate multiple dynamics models --------------------------------------- if isfield(dynmodel,'sub') dyn = dynmodel.sub{n}; do = dyn.dyno; D = length(ii)+D1-D2; if isfield(dyn,'dyni'), di=dyn.dyni; else di=[]; end if isfield(dyn,'dynu'), du=dyn.dynu; else du=[]; end if isfield(dyn,'dynj'), dj=dyn.dynj; else dj=[]; end i = [ii(di) D1+du D2+dj]; k = D2+do; dyn.inputs = [dynmodel.inputs(:,[di D+du]) dynmodel.target(:,dj)]; % inputs dyn.target = dynmodel.target(:,do); % targets else dyn = dynmodel; k = D2+1:D3; i = ii; end
github
UCL-SML/pilco-matlab-master
calcCost.m
.m
pilco-matlab-master/base/calcCost.m
1,329
utf_8
3f9d3c6f6845a8b673f95345f81c56b9
%% calcCost.m % *Summary:* Function to calculate the incurred cost and its standard deviation, % given a sequence of predicted state distributions and the cost struct % % [L sL] = calcCost(cost, M, S) % % *Input arguments:* % % cost cost structure % M mean vectors of state trajectory (D-by-H matrix) % S covariance matrices at each time step (D-by-D-by-H) % % *Output arguments:* % % L expected incurred cost of state trajectory % sL standard deviation of incurred cost % % % Copyright (C) 2008-2013 by % Marc Deisenroth, Andrew McHutchon, Joe Hall, and Carl Edward Rasmussen. % % Last modified: 2013-01-23 % %% High-Level Steps % # Augment state distribution with trigonometric functions % # Compute distribution of the control signal % # Compute dynamics-GP prediction % # Compute distribution of the next state % function [L sL] = calcCost(cost, M, S) %% Code H = size(M,2); % horizon length L = zeros(1,H); SL = zeros(1,H); % for each time step, compute the expected cost and its variance for h = 1:H [L(h),d1,d2,SL(h)] = cost.fcn(cost, M(:,h), S(:,:,h)); end sL = sqrt(SL); % standard deviation
github
UCL-SML/pilco-matlab-master
simulate.m
.m
pilco-matlab-master/base/simulate.m
3,877
utf_8
2dfb96f96725ecbb27b0ec86d2aedc63
%% simulate.m % *Summary:* Simulate dynamics using a given control scheme. % % function next = simulate(x0, f, plant) % % *Input arguments:* % % x0 start state (with additional control states if required) % f the control setpoint for this time step % plant plant structure % .dt time discretization % .dynamics system function % .ctrl function defining control implementation % @zoh - zero-order-hold control (ZOH) % @foh - first-order-hold control (FOH) % with optional rise time 0 < plant.tau <= dt % @lag - lagged control with time constant 0 < plant.tau % .delay continuous-time delay, in range [0 dt) % % *Output arguments:* % % next successor state (with additional control states if required) % % % Copyright (C) 2008-2013 by % Marc Deisenroth, Andrew McHutchon, Joe Hall, and Carl Edward Rasmussen. % % Last modification: 2012-06-30 % %% High-Level Steps % For each time step % # Set up the control function % # Simulate the dynamics (by calling ODE45) % # Update control part of the state function next = simulate(x0, f, plant) %% Code OPTIONS = odeset('RelTol', 1e-12, 'AbsTol', 1e-12); % accuracy of ode45 x0 = x0(:); f = f(:); nU = length(f); dt = plant.dt; dynamics = plant.dynamics; if isfield(plant,'delay'), delay = plant.delay; else delay = 0; end if isfield(plant,'tau'), tau = plant.tau; else tau = dt; end par.dt = dt; par.delay = delay; par.tau = tau; % 1. Set up control function ------------------------------------------------ % f{t} = control setpoint over time t to d+dt (determined by policy) % u{t} = control currently being applied at time t con = functions(plant.ctrl); con = con.function; if (strcmp(con,'zoh') && delay==0) % U = [f{t}] x0s = x0;U = f; id = 0; elseif strcmp(con,'zoh') || ... % U = [u{t} f{t}] (strcmp(con,'foh') && tau+delay<=dt) || (strcmp(con,'lag') && delay==0) x0s = x0(1:end-nU); U = [x0(end-nU+1:end) f]; id = 1; else % U = [f{t-1} u{t} f{t}] x0s=x0(1:end-2*nU); U=[reshape( x0(end-2*nU+1:end), [nU 2]) f]; id = 2; end ctrlfcn = str2func(con); u0 = cell(1,nU); % create control function for j = 1:nU, u0{j} = @(t)ctrlfcn(U(j,:),t,par); end % 2. Simulate dynamics ------------------------------------------------------ [T y] = ode45(dynamics, [0 dt/2 dt], x0s, OPTIONS, u0{:}); x1 = y(3,:)'; % next state % 3. Update control part of the state --------------------------------------- udt = zeros(nU,1); for j=1:nU, udt(j) = u0{j}(dt); end if id==0, next = x1; % return augmented state elseif id==1, next = [x1; udt]; else next = [x1; f; udt]; end function u = zoh(f, t, par) % **************************** zero-order hold d = par.delay; if d==0 u = f; else e = d/100; t0=t-(d-e/2); if t<d-e/2, u=f(1); elseif t<d+e/2, u=(1-t0/e)*f(1) + t0/e*f(2); % prevents ODE stiffness else u=f(2); end end function u = foh(f, t, par) % *************************** first-order hold d = par.delay; tau = par.tau; dt = par.dt; if tau + d < dt t0=t-d; if t<d, u=f(1); elseif t<tau+d, u=(1-t0/tau)*f(1) + t0/tau*f(2); else u=f(2); end else bit = d-(dt-tau); if t<bit, u=(1-t/bit)*f(2) + t/tau*f(1); elseif t<d, u=f(1); else t0=t+d; u=(1-t0/tau)*f(1) + t0/tau*f(3); end end function u = lag(f, t, par) % **************************** first-order lag d = par.delay; tau = par.tau; if d==0 u = f(1) + (f(2)-f(1))*exp(-t/tau); else bit = f(2) + (f(1)-f(2))*exp(-d/tau); if t<d, u = f(2) + (f(1)-f(2))*exp(-t/tau); else u = bit + (f(3)-bit )*exp(-t/tau); end end
github
UCL-SML/pilco-matlab-master
pred.m
.m
pilco-matlab-master/base/pred.m
1,166
utf_8
542ef9cd484a7b32fbcd49e6771eae0e
%% pred.m % *Summary:* Compute predictive (marginal) distributions of a trajecory % % [M S] = pred(policy, plant, dynmodel, m, s, H) % % *Input arguments:* % % policy policy structure % plant plant structure % dynmodel dynamics model structure % m D-by-1 mean of the initial state distribution % s D-by-D covariance of the initial state distribution % H length of prediction horizon % % *Output arguments:* % % M D-by-(H+1) sequence of predicted mean vectors % S D-by-D-(H+1) sequence of predicted covariance % matrices % % Copyright (C) 2008-2013 by % Marc Deisenroth, Andrew McHutchon, Joe Hall, and Carl Edward Rasmussen. % % Last modified: 2013-01-23 % %% High-Level Steps % # Predict successor state distribution function [M S] = pred(policy, plant, dynmodel, m, s, H) %% Code D = length(m); S = zeros(D,D,H+1); M = zeros(D,H+1); M(:,1) = m; S(:,:,1) = s; for i = 1:H [m s] = plant.prop(m, s, plant, dynmodel, policy); M(:,i+1) = m(end-D+1:end); S(:,:,i+1) = s(end-D+1:end,end-D+1:end); end
github
UCL-SML/pilco-matlab-master
value.m
.m
pilco-matlab-master/base/value.m
2,645
utf_8
bce8a1d93f7a603513a4b3820ac4e5a7
%% value.m % *Summary:* Compute expected (discounted) cumulative cost for a given (set of) initial % state distributions % % function [J, dJdp] = value(p, m0, S0, dynmodel, policy, plant, cost, H) % % *Input arguments:* % % p policy parameters chosen by minimize % policy policy structure % .fcn function which implements the policy % .p parameters passed to the policy % m0 matrix (D by k) of initial state means % S0 covariance matrix (D by D) for initial state % dynmodel dynamics model structure % plant plant structure % cost cost function structure % .fcn function handle to the cost % .gamma discount factor % H length of prediction horizon % % *Output arguments:* % % J expected cumulative (discounted) cost % dJdp (optional) derivative of J wrt the policy parameters % % Copyright (C) 2008-2013 by % Marc Deisenroth, Andrew McHutchon, Joe Hall, and Carl Edward Rasmussen. % % Last modification: 2013-03-21 % %% High-Level Steps % # Compute distribution of next state % # Compute corresponding expected immediate cost (discounted) % # At end of prediction horizon: sum all immediate costs up function [J, dJdp] = value(p, m0, S0, dynmodel, policy, plant, cost, H) %% Code policy.p = p; % overwrite policy.p with new parameters from minimize p = unwrap(policy.p); dp = 0*p; m = m0; S = S0; L = zeros(1,H); if nargout <= 1 % no derivatives required for t = 1:H % for all time steps in horizon [m, S] = plant.prop(m, S, plant, dynmodel, policy); % get next state L(t) = cost.gamma^t.*cost.fcn(cost, m, S); % expected discounted cost end else % otherwise, get derivatives dmOdp = zeros([size(m0,1), length(p)]); dSOdp = zeros([size(m0,1)*size(m0,1), length(p)]); for t = 1:H % for all time steps in horizon [m, S, dmdmO, dSdmO, dmdSO, dSdSO, dmdp, dSdp] = ... plant.prop(m, S, plant, dynmodel, policy); % get next state dmdp = dmdmO*dmOdp + dmdSO*dSOdp + dmdp; dSdp = dSdmO*dmOdp + dSdSO*dSOdp + dSdp; [L(t), dLdm, dLdS] = cost.fcn(cost, m, S); % predictive cost L(t) = cost.gamma^t*L(t); % discount dp = dp + cost.gamma^t*( dLdm(:)'*dmdp + dLdS(:)'*dSdp )'; dmOdp = dmdp; dSOdp = dSdp; % bookkeeping end end J = sum(L); dJdp = rewrap(policy.p, dp);
github
UCL-SML/pilco-matlab-master
rollout.m
.m
pilco-matlab-master/base/rollout.m
4,299
utf_8
b1d2fdc6eb88a4e15beaa61e61a33041
%% rollout.m % *Summary:* Generate a state trajectory using an ODE solver (and any additional % dynamics) from a particular initial state by applying either a particular % policy or random actions. % % function [x y L latent] = rollout(start, policy, H, plant, cost) % % *Input arguments:* % % start vector containing initial states (without controls) [nX x 1] % policy policy structure % .fcn policy function % .p parameter structure (if empty: use random actions) % .maxU vector of control input saturation values [nU x 1] % H rollout horizon in steps % plant the dynamical system structure % .subplant (opt) additional discrete-time dynamics % .augment (opt) augment state using a known mapping % .constraint (opt) stop rollout if violated % .poli indices for states passed to the policy % .dyno indices for states passed to cost % .odei indices for states passed to the ode solver % .subi (opt) indices for states passed to subplant function % .augi (opt) indices for states passed to augment function % cost cost structure % % *Output arguments:* % % x matrix of observed states [H x nX+nU] % y matrix of corresponding observed successor states [H x nX ] % L cost incurred at each time step [ 1 x H ] % latent matrix of latent states [H+1 x nX ] % % Copyright (C) 2008-2013 by % Marc Deisenroth, Andrew McHutchon, Joe Hall, and Carl Edward Rasmussen. % % Last modification: 2013-05-21 % %% High-Level Steps % % # Compute control signal $u$ from state $x$: % either apply policy or random actions % # Simulate the true dynamics for one time step using the current pair $(x,u)$ % # Check whether any constraints are violated (stop if true) % # Apply random noise to the successor state % # Compute cost (optional) % # Repeat until end of horizon function [x y L latent] = rollout(start, policy, H, plant, cost) %% Code if isfield(plant,'augment'), augi = plant.augi; % sort out indices! else plant.augment = inline('[]'); augi = []; end if isfield(plant,'subplant'), subi = plant.subi; else plant.subplant = inline('[]',1); subi = []; end odei = plant.odei; poli = plant.poli; dyno = plant.dyno; angi = plant.angi; simi = sort([odei subi]); nX = length(simi)+length(augi); nU = length(policy.maxU); nA = length(angi); state(simi) = start; state(augi) = plant.augment(state); % initializations x = zeros(H+1, nX+2*nA); x(1,simi) = start' + randn(size(simi))*chol(plant.noise); x(1,augi) = plant.augment(x(1,:)); u = zeros(H, nU); latent = zeros(H+1, size(state,2)+nU); y = zeros(H, nX); L = zeros(1, H); next = zeros(1,length(simi)); for i = 1:H % --------------------------------------------- generate trajectory s = x(i,dyno)'; sa = gTrig(s, zeros(length(s)), angi); s = [s; sa]; x(i,end-2*nA+1:end) = s(end-2*nA+1:end); % 1. Apply policy ... or random actions -------------------------------------- if isfield(policy, 'fcn') u(i,:) = policy.fcn(policy,s(poli),zeros(length(poli))); else u(i,:) = policy.maxU.*(2*rand(1,nU)-1); end latent(i,:) = [state u(i,:)]; % latent state % 2. Simulate dynamics ------------------------------------------------------- next(odei) = simulate(state(odei), u(i,:), plant); next(subi) = plant.subplant(state, u(i,:)); % 3. Stop rollout if constraints violated ------------------------------------ if isfield(plant,'constraint') && plant.constraint(next(odei)) H = i-1; fprintf('state constraints violated...\n'); break; end % 4. Augment state and randomize --------------------------------------------- state(simi) = next(simi); state(augi) = plant.augment(state); x(i+1,simi) = state(simi) + randn(size(simi))*chol(plant.noise); x(i+1,augi) = plant.augment(x(i+1,:)); % 5. Compute Cost ------------------------------------------------------------ if nargout > 2 L(i) = cost.fcn(cost,state(dyno)',zeros(length(dyno))); end end y = x(2:H+1,1:nX); x = [x(1:H,:) u(1:H,:)]; latent(H+1, 1:nX) = state; latent = latent(1:H+1,:); L = L(1,1:H);
github
UCL-SML/pilco-matlab-master
valueT.m
.m
pilco-matlab-master/test/valueT.m
1,378
utf_8
3adc202d8e07edc1ea870c160bfe7451
%% valueT.m % *Summary:* Test derivatives of the propagate function, which computes the % mean and the variance of the successor state distribution, assuming that the % current state is Gaussian distributed with mean m and covariance matrix % s. % % [d dy dh] = valueT(p, delta, m, s, dynmodel, policy, plant, cost, H) % % % *Input arguments:* % % p policy parameters (can be a structure) % .<> fields that contain the policy parameters (nothing else) % m mean of the input distribution % s covariance of the input distribution % dynmodel GP dynamics model (structure) % policy policy structure % plant plant structure % cost cost structure % H prediction horizon % delta (optional) finite difference parameter. Default: 1e-4 % % % *Output arguments:* % % dd relative error of analytical vs. finite difference gradient % dy analytical gradient % dh finite difference gradient % % Copyright (C) 2008-2013 by % Marc Deisenroth, Andrew McHutchon, Joe Hall, and Carl Edward Rasmussen. % % Last modified: 2013-03-21 function [d dy dh] = valueT(p, m, s, dynmodel, policy, plant, cost, H, delta) %% Code if nargin < 9; delta = 1e-4; end if nargin < 8; H = 4; end % call checkgrad directly [d dy dh] = checkgrad('value',p,delta,m,s,dynmodel,policy,plant,cost,H);
github
UCL-SML/pilco-matlab-master
lossT.m
.m
pilco-matlab-master/test/lossT.m
4,104
utf_8
1d3ad31b497f7aa08f0bfb60ed4af10b
%% lossT.m % *Summary:* Test derivatives of cost functions. It is assumed that % the cost function computes (at least) the mean and the variance of the % cost for a Gaussian distributed input $x\sim\mathcal N(m,s)$ % % % function [dd dy dh] = lossT(deriv, policy, m, s, delta) % % % *Input arguments:* % % deriv desired derivative. options: % (i) 'dMdm' - derivative of the mean of the predicted cost % wrt the mean of the input distribution % (ii) 'dMds' - derivative of the mean of the predicted cost % wrt the variance of the input distribution % (iii) 'dSdm' - derivative of the variance of the predicted cost % wrt the mean of the input distribution % (iv) 'dSds' - derivative of the variance of the predicted cost % wrt the variance of the input distribution % (v) 'dCdm' - derivative of inv(s)*(covariance of the input and the % predicted cost) wrt the mean of the input distribution % (vi) 'dCds' - derivative of inv(s)*(covariance of the input and the % predicted cost) wrt the variance of the input distribution % cost cost structure % .fcn function handle to cost % .<> other fields that are passed on to the cost % m mean of the input distribution % s covariance of the input distribution % delta (optional) finite difference parameter. Default: 1e-4 % % % *Output arguments:* % % dd relative error of analytical vs. finite difference gradient % dy analytical gradient % dh finite difference gradient % % Copyright (C) 2008-2013 by % Marc Deisenroth, Andrew McHutchon, Joe Hall, and Carl Edward Rasmussen. % % Last modified: 2013-05-30 function [d dy dh] = lossT(deriv, cost, m, S, delta) %% Code % create a default test if no input arguments are given if nargin == 0; D = 4; m = randn(4,1); S = randn(4); S = S*S'; cost.z = randn(4,1); W = randn(4); W = W*W'; cost.W = W; cost.fcn = @lossQuad; deriv = 'dLdm'; end D = length(m); if nargout < 5; delta = 1e-4; end % check derivatives switch deriv case {'dLdm', 'dMdm'} [d dy dh] = checkgrad(@losstest01, m, delta, cost, S); case {'dLds', 'dMds'} [d dy dh] = checkgrad(@losstest02, S(tril(ones(D))==1), delta, cost, m); case 'dSdm' [d dy dh] = checkgrad(@losstest03, m, delta, cost, S); case 'dSds' [d dy dh] = checkgrad(@losstest04, S(tril(ones(D))==1), delta, cost, m); case {'dCdm', 'dVdm'} [d dy dh] = checkgrad(@losstest05, m, delta, cost, S); case {'dCds', 'dVds'} [d dy dh] = checkgrad(@losstest06, S(tril(ones(D))==1), delta, cost, m); end %% function [f, df] = losstest01(m, cost, S) % dLdm [L dLdm] = cost.fcn(cost, m, S); f = L; df = dLdm; function [f, df] = losstest02(s, cost, m) % dLds d = length(m); ss(tril(ones(d))==1) = s; ss = reshape(ss,d,d); ss = ss + ss' - diag(diag(ss)); [L dLdm dLds] = cost.fcn(cost, m, ss); f = L; df = dLds; df = 2*df-diag(diag(df)); df = df(tril(ones(d))==1); function [f, df] = losstest03(m, cost, S) % dSdm [L dLdm dLds S dSdm] = cost.fcn(cost, m, S); f = S; df = dSdm; function [f, df] = losstest04(s, cost, m) % dSds d = length(m); ss(tril(ones(d))==1) = s; ss = reshape(ss,d,d); ss = ss + ss' - diag(diag(ss)); [L dLdm dLds S dSdm dSds] = cost.fcn(cost, m, ss); f = S; df = dSds; df = 2*df-diag(diag(df)); df = df(tril(ones(d))==1); function [f, df] = losstest05(m, cost, S) % dCdm [L dLdm dLds S dSdm dSds C dCdm] = cost.fcn(cost, m, S); f = C; df = dCdm; function [f, df] = losstest06(s, cost, m) % dCds d = length(m); ss(tril(ones(d))==1) = s; ss = reshape(ss,d,d); ss = ss + ss' - diag(diag(ss)); [L dLdm dLds S dSdm dSds C dCdm dCds] = cost.fcn(cost, m, ss); f = C; dCds = reshape(dCds,d,d,d); df = zeros(d,d*(d+1)/2); for i=1:d; dCdsi = squeeze(dCds(i,:,:)); dCdsi = dCdsi+dCdsi'-diag(diag(dCdsi)); df(i,:) = dCdsi(tril(ones(d))==1); end;
github
UCL-SML/pilco-matlab-master
conT.m
.m
pilco-matlab-master/test/conT.m
6,499
utf_8
ed7e152cffd95ed992cd6686223561e1
%% conT.m % *Summary:* Test derivatives of controller functions. It is assumed that % the controller function computes the mean and the variance of the % control signal for a Gaussian distributed input $x\sim\mathcal N(m,s)$ % % % function [dd dy dh] = conT(deriv, policy, m, s, delta) % % % *Input arguments:* % % deriv desired derivative. options: % (i) 'dMdm' - derivative of the mean of the predicted control % wrt the mean of the input distribution % (ii) 'dMds' - derivative of the mean of the predicted control % wrt the variance of the input distribution % (iii) 'dMdp' - derivative of the mean of the predicted control % wrt the controller parameters % (iv) 'dSdm' - derivative of the variance of the predicted control % wrt the mean of the input distribution % (v) 'dSds' - derivative of the variance of the predicted control % wrt the variance of the input distribution % (vi) 'dSdp' - derivative of the variance of the predicted control % wrt the controller parameters % (vii) 'dCdm' - derivative of inv(s)*(covariance of the input and the % predicted control) wrt the mean of the input distribution % (viii) 'dCds' - derivative of inv(s)*(covariance of the input and the % predicted control) wrt the variance of the input distribution % (ix) 'dCdp' - derivative of inv(s)*(covariance of the input and the % predicted control) wrt the controller parameters % policy policy structure % .fcn function handle to policy % .<> other fields that are passed on to the policy % m mean of the input distribution % s covariance of the input distribution % delta (optional) finite difference parameter. Default: 1e-4 % % % *Output arguments:* % % dd relative error of analytical vs. finite difference gradient % dy analytical gradient % dh finite difference gradient % % Copyright (C) 2008-2013 by % Marc Deisenroth, Andrew McHutchon, Joe Hall, and Carl Edward Rasmussen. % % Last modified: 2013-05-30 function [dd dy dh] = conT(deriv, policy, m, s, delta) %% Code if nargin < 5; delta = 1e-4; end % default value % if no input arguments, create random policy parameters and check derivatives if nargin == 0 D = 2; d = 3; policy.w = randn(D,d); policy.b = randn(D,1); m = randn(d,1); s = randn(d); s = s*s'; policy.maxU = '2 3'; policy.fcn = @(policy, m, s)conCat(@conLin, @gSat, policy, m, s); end D = length(policy.maxU); d = length(m); switch deriv case 'dMdm' [dd dy dh] = checkgrad(@conT0, m, delta, policy, s); case 'dSdm' [dd dy dh] = checkgrad(@conT1, m, delta, policy, s); case 'dCdm' [dd dy dh] = checkgrad(@conT2, m, delta, policy, s); case 'dMds' [dd dy dh] = checkgrad(@conT3, s(tril(ones(d))==1), delta, policy, m); case 'dSds' [dd dy dh] = checkgrad(@conT4, s(tril(ones(d))==1), delta, policy, m); case 'dCds' [dd dy dh] = checkgrad(@conT5, s(tril(ones(d))==1), delta, policy, m); case 'dMdp' [dd dy dh] = checkgrad(@conT6, policy.p, delta, policy, m, s); case 'dSdp' [dd dy dh] = checkgrad(@conT7, policy.p, delta, policy, m, s); case 'dCdp' [dd dy dh] = checkgrad(@conT8, policy.p, delta, policy, m, s); end function [f, df] = conT0(m, policy, s) % dMdm if nargout < 2 M = policy.fcn(policy, m, s); else [M, S, C, dMdm] = policy.fcn(policy, m, s); df = dMdm; end f = M; function [f, df] = conT1(m, policy, s) % dSdm if nargout < 2 [M, S] = policy.fcn(policy, m, s); else [M, S, C, dMdm, dSdm] = policy.fcn(policy, m, s); df = dSdm; end f = S; function [f, df] = conT2(m, policy, s) % dCdm if nargout < 2 [M, S, C] = policy.fcn(policy, m, s); else [M, S, C, dMdm, dSdm, dCdm] = policy.fcn(policy, m, s); df = dCdm; end f = C; function [f, df] = conT3(s, policy, m) % dMds d = length(m); v(tril(ones(d))==1) = s; s = reshape(v,d,d); s = s+s'-diag(diag(s)); if nargout < 2 M = policy.fcn(policy, m, s); else [M, S, C, dMdm, dSdm, dCdm, dMds] = policy.fcn(policy, m, s); dd = length(M); dMds = reshape(dMds,dd,d,d); df = zeros(dd,d*(d+1)/2); for i=1:dd; dMdsi(:,:) = dMds(i,:,:); dMdsi = dMdsi + dMdsi'-diag(diag(dMdsi)); df(i,:) = dMdsi(tril(ones(d))==1); end end f = M; function [f, df] = conT4(s, policy, m) % dSds d = length(m); v(tril(ones(d))==1) = s; s = reshape(v,d,d); s = s+s'-diag(diag(s)); if nargout < 2 [M, S] = policy.fcn(policy, m, s); else [M, S, C, dMdm, dSdm, dCdm, dMds, dSds] = policy.fcn(policy, m, s); dd = length(M); dSds = reshape(dSds,dd,dd,d,d); df = zeros(dd,dd,d*(d+1)/2); for i=1:dd; for j=1:dd dSdsi(:,:) = dSds(i,j,:,:); dSdsi = dSdsi+dSdsi'-diag(diag(dSdsi)); df(i,j,:) = dSdsi(tril(ones(d))==1); end; end end f = S; function [f, df] = conT5(s, policy, m) % dCds d = length(m); v(tril(ones(d))==1) = s; s = reshape(v,d,d); s = s+s'-diag(diag(s)); if nargout < 2 [M, S, C] = policy.fcn(policy, m, s); else [M, S, C, dMdm, dSdm, dCdm, dMds, dSds, dCds] = policy.fcn(policy, m, s); dd = length(M); dCds = reshape(dCds,d,dd,d,d); df = zeros(d,dd,d*(d+1)/2); for i=1:d; for j=1:dd dCdsi = squeeze(dCds(i,j,:,:)); dCdsi = dCdsi+dCdsi'-diag(diag(dCdsi)); df(i,j,:) = dCdsi(tril(ones(d))==1); end; end end f = C; function [f, df] = conT6(p, policy, m, s) % dMdp policy.p = p; if nargout < 2 M = policy.fcn(policy, m, s); else [M, S, C, dMdm, dSdm, dCdm, dMds, dSds, dCds, dMdp] = policy.fcn(policy, m, s); df = dMdp; end f = M; function [f, df] = conT7(p, policy, m, s) policy.p = p; if nargout < 2 [M, S] = policy.fcn(policy, m, s); else [M, S, C, dMdm, dSdm, dCdm, dMds, dSds, dCds, dMdp, dSdp] = policy.fcn(policy, m, s); df = dSdp; end f = S; function [f, df] = conT8(p, policy, m, s) policy.p = p; if nargout < 2 [M, S, C] = policy.fcn(policy, m, s); else [M, S, C, dMdm, dSdm, dCdm, dMds, dSds, dCds, dMdp, dSdp, dCdp] = ... policy.fcn(policy, m, s); df = dCdp; end f = C;
github
UCL-SML/pilco-matlab-master
gTrigT.m
.m
pilco-matlab-master/test/gTrigT.m
4,317
utf_8
903d6b160be13bf92b4b1a5231164f10
%% gTrigT.m % *Summary:* Test the gTrig function, which computes (at least) the mean and % the variance of the transformed variable for a Gaussian distributed input % $x\sim\mathcal N(m,v)$. Check the outputs using Monte Carlo, and the % derivatives using finite differences. % % % function gTrigT(m, v, i, e) % % % *Input arguments:* % % m mean vector of Gaussian [ d ] % v covariance matrix [ d x d ] % i vector of indices of elements to augment [ I x 1 ] % e (optional) scale vector; default: 1 [ I x 1 ] % % % Copyright (C) 2008-2013 by % Marc Deisenroth, Andrew McHutchon, Joe Hall, and Carl Edward Rasmussen. % % Last modified: 2013-03-25 function gTrigT(m, v, i, e) %% Code % create a default test if no input arguments are given if ~nargin D = 4; m = randn(D,1); v = randn(D); v = v*v'+eye(D); i = [2; 4]; I = 2*length(i); e = exp(randn(size(i))); else D = length(m); end n = 1e6; % Monte Carlo sample size delta = 1e-4; % for finite difference approx x = bsxfun(@plus, m, chol(v)'*randn(D,n)); y = bsxfun(@times, [e; e], [sin(x(i,:)); cos(x(i,:))]); y = y(reshape(1:I,I/2,2)',:); % reorder rows [M, V, C] = gTrig(m, v, i, e); Q = cov([x' y']); Qv = Q(D+1:end,D+1:end); Qc = v\Q(1:D,D+1:end); disp(['mean: gTrig Monte Carlo']) disp([M mean(y,2)]); disp([' ']); disp(['var: gTrig Monte Carlo']) disp([V(:) Qv(:)]); disp([' ']); disp(['cov: gTrig Monte Carlo']) disp([C(:) Qc(:)]); disp(' '); disp('dMdm') for j = 1:I checkgrad(@gTrigT0, m, delta, v, i, e, j); disp(['this was element # ' num2str(j) '/' num2str(I)]); end disp(' '); disp('dVdm') for j = 1:I*I checkgrad(@gTrigT1, m, delta, v, i, e, j); disp(['this was element # ' num2str(j) '/' num2str(I*I)]); end disp(' '); disp('dCdm') for j = 1:I*D checkgrad(@gTrigT2, m, delta, v, i, e, j); disp(['this was element # ' num2str(j) '/' num2str(I*D)]); end disp(' '); disp('dMdv') for j = 1:I checkgrad(@gTrigT3, v(tril(ones(length(v)))==1), delta, m, i, e, j); disp(['this was element # ' num2str(j) '/' num2str(I)]); end disp(' '); disp('dVdv') for j = 1:I*I checkgrad(@gTrigT4, v(tril(ones(length(v)))==1), delta, m, i, e, j); disp(['this was element # ' num2str(j) '/' num2str(I*I)]); end disp(' '); disp('dCdv') for j = 1:I*D checkgrad(@gTrigT5, v(tril(ones(length(v)))==1), delta, m, i, e, j); disp(['this was element # ' num2str(j) '/' num2str(I*D)]); end function [f, df] = gTrigT0(m, v, i, e, j) [M, V, C, dMdm] = gTrig(m, v, i, e); f = M(j); df = dMdm(j,:); function [f, df] = gTrigT1(m, v, i, e, j) [M, V, C, dMdm, dVdm] = gTrig(m, v, i, e); dVdm = reshape(dVdm,[size(V) length(m)]); dd = length(M); p = fix((j+dd-1)/dd); q = j-(p-1)*dd; f = V(p,q); df = squeeze(dVdm(p,q,:)); function [f, df] = gTrigT2(m, v, i, e, j) [M, V, C, dMdm, dVdm, dCdm] = gTrig(m, v, i, e); dCdm = reshape(dCdm,[size(C) length(m)]); dd = length(M); p = fix((j+dd-1)/dd); q = j-(p-1)*dd; f = C(p,q); df = squeeze(dCdm(p,q,:)); function [f, df] = gTrigT3(v, m, i, e, j) d = length(m); vv(tril(ones(d))==1) = v; vv = reshape(vv,d,d); vv = vv + vv' - diag(diag(vv)); [M, V, C, dMdm, dVdm, dCdm, dMdv] = gTrig(m, vv, i, e); dMdv = reshape(dMdv,[length(M) size(v)]); f = M(j); df = squeeze(dMdv(j,:,:)); df = df+df'-diag(diag(df)); df = df(tril(ones(d))==1); function [f, df] = gTrigT4(v, m, i, e, j) d = length(m); vv(tril(ones(d))==1) = v; vv = reshape(vv,d,d); vv = vv + vv' - diag(diag(vv)); [M, V, C, dMdm, dVdm, dCdm, dMdv, dVdv] = gTrig(m, vv, i, e); dVdv = reshape(dVdv,[size(V) size(v)]); dd = length(M); p = fix((j+dd-1)/dd); q = j-(p-1)*dd; f = V(p,q); df = squeeze(dVdv(p,q,:,:)); df = df+df'-diag(diag(df)); df = df(tril(ones(d))==1); function [f, df] = gTrigT5(v, m, i, e, j) d = length(m); vv(tril(ones(d))==1) = v; vv = reshape(vv,d,d); vv = vv + vv' - diag(diag(vv)); [M, V, C, dMdm, dVdm, dCdm, dMdv, dVdv, dCdv] = gTrig(m, vv, i, e); dCdv = reshape(dCdv,[size(C) size(v)]); dd = length(M); p = fix((j+dd-1)/dd); q = j-(p-1)*dd; f = C(p,q); df = squeeze(dCdv(p,q,:,:)); df = df+df'-diag(diag(df)); df = df(tril(ones(d))==1);
github
UCL-SML/pilco-matlab-master
checkgrad.m
.m
pilco-matlab-master/test/checkgrad.m
2,523
utf_8
2f83ec025d217dd2aa54a4df46e074c0
%% checkgrad.m % *Summary:* checkgrad checks the derivatives in a function, by comparing them % to finite differences approximations. The partial derivatives and the % approximation are printed and the norm of the difference divided by the % norm of the sum is returned as an indication of accuracy. % % function [d dy dh] = checkgrad(f, X, e, varargin) % % % *Input arguments:* % % f function handle to function that needs to be checked. % The function f should be of the type [fX, dfX] = f(X, varargin) % where fX is the function value and dfX is the gradient of fX % with respect to the parameters X % X parameters (can be a vector or a struct) % e small perturbation used for finite differences (1e-4 is good) % varargin other arguments that are passed on to the function f % % % *Output arguments:* % % d relative error of analytical vs. finite difference gradient % dy analytical gradient % dh finite difference gradient % % % Copyright (C) 2008-2013 by % Marc Deisenroth, Andrew McHutchon, Joe Hall, and Carl Edward Rasmussen. % % Last modified: 2013-03-21 % %% High-Level Steps % # Analytical gradient % # Numerical gradient via finite differences % # Relative error function [d dy dh] = checkgrad(f, X, e, varargin) %% Code % 1. Analytical gradient Z = unwrap(X); NZ = length(Z); % number of input variables [y dy] = feval(f, X, varargin{:}); % get the partial derivatives dy [D E] = size(y); y = y(:); Ny = length(y); % number of output variables if iscell(dy) || isstruct(dy); dy = unwrap(dy); end; dy = reshape(dy,Ny,NZ); % 2. Finite difference approximation dh = zeros(Ny,NZ); for j = 1:NZ dx = zeros(length(Z),1); dx(j) = dx(j) + e; % perturb a single dimension y2 = feval(f, rewrap(X,Z+dx), varargin{:}); y1 = feval(f, rewrap(X,Z-dx), varargin{:}); dh(:,j) = (y2(:) - y1(:))/(2*e); end % 3. Compute error % norm of diff divided by norm of sum d = sqrt(sum((dh-dy).^2,2)./sum((dh+dy).^2,2)); small = max(abs([dy dh]),[],2) < 1e-5; % small derivatives are poorly tested ... d(d > 1e-3 & small) = NaN; % ... by finite differences d = reshape(d,D,E); disp(' Analytic Numerical'); for i=1:Ny; disp([dy(i,:)' dh(i,:)']); % print the two vectors fprintf('d = %e\n\n',d(i)) end if Ny > 1; disp('For all outputs, d = '); disp(d); end; fprintf('\n');
github
UCL-SML/pilco-matlab-master
propagateT.m
.m
pilco-matlab-master/test/propagateT.m
6,891
utf_8
d716216e47aca62720d858232988f61b
%% propagateT.m % *Summary:* Test derivatives of the propagate function, which computes the % mean and the variance of the successor state distribution, assuming that the % current state is Gaussian distributed with mean m and covariance matrix % s. % % [dd dy dh] = propagateT(deriv, plant, dynmodel, policy, m, s, delta) % % % *Input arguments:* % % deriv desired derivative. options: % (i) 'dMdm' - derivative of the mean of the predicted state % wrt the mean of the input distribution % (ii) 'dMds' - derivative of the mean of the predicted state % wrt the variance of the input distribution % (iii) 'dMdp' - derivative of the mean of the predicted state % wrt the controller parameters % (iv) 'dSdm' - derivative of the variance of the predicted state % wrt the mean of the input distribution % (v) 'dSds' - derivative of the variance of the predicted state % wrt the variance of the input distribution % (vi) 'dSdp' - derivative of the variance of the predicted state % wrt the controller parameters % (vii) 'dCdm' - derivative of the inv(s)*(covariance of the input and % the predicted state) wrt the mean of the input distribution % (viii) 'dCds' - derivative of the inv(s)*(covariance of the input and % the predicted state) wrt the variance of the input distribution % (ix) 'dCdp' - derivative of the inv(s)*(covariance of the input and % the predicted state) wrt the controller parameters % plant plant structure % .poli state indices: policy inputs % .dyno state indices: predicted variables % .dyni state indices: inputs to ODE solver % .difi state indices that are learned via differences % .angi state indices: angles % .poli state indices: policy inputs % .prop function handle to function responsible for state % propagation. Here: @propagated % dynmodel GP dynamics model (structure) % .hyp log-hyper parameters % .inputs training inputs % .targets training targets % policy policy structure % .maxU maximum amplitude of control % .fcn function handle to policy % .p struct of policy parameters % .p.<> policy-specific parameters are stored here % m mean of the input distribution % s covariance of the input distribution % delta (optional) finite difference parameter. Default: 1e-4 % % % *Output arguments:* % % dd relative error of analytical vs. finite difference gradient % dy analytical gradient % dh finite difference gradient % % Copyright (C) 2008-2013 by % Marc Deisenroth, Andrew McHutchon, Joe Hall, and Carl Edward Rasmussen. % % Last modified: 2013-03-21 function [dd dy dh] = propagateT(deriv, plant, dynmodel, policy, m, s, delta) %% Code if nargin < 2, randn('seed',24) nn = 10; E = 4; F = 3; m = randn(D,1); s = randn(D); s = s*s'; % Plant ---------------------------------------------------------------- plant.poli = 1:E; plant.dyno = 1:E; plant.dyni = 1:E; plant.difi = 1:E; plant.angi = []; plant.prop = @propagated; % Policy --------------------------------------------------------------- policy.p.w = randn(F,E); policy.p.b = randn(F,1); policy.fcn = @(policy,m,s)conCat(@conlin,@gSat,policy,m,s); policy.maxU = 20*ones(1,F); % Dynamics ------------------------------------------------------------- dynmodel.hyp = zeros(1,E); dynmodel.inputs = randn(nn,E+F); dynmodel.targets = randn(nn,E); end if nargin < 7; delta = 1e-4; end D = length(m); switch deriv case 'dMdm' [dd dy dh] = checkgrad(@propagateT0, m, delta, plant, dynmodel, policy, s); case 'dSdm' [dd dy dh] = checkgrad(@propagateT1, m, delta, plant, dynmodel, policy, s); case 'dMds' [dd dy dh] = checkgrad(@propagateT2, s(tril(ones(D))==1), delta, plant, ... dynmodel, policy, m); case 'dSds' [dd dy dh] = checkgrad(@propagateT3, s(tril(ones(D))==1), delta, plant, ... dynmodel, policy, m); case 'dMdp' p = unwrap(policy.p); [dd dy dh] = checkgrad(@propagateT4, p, delta, plant, dynmodel, policy, m, s); case 'dSdp' p = unwrap(policy.p); [dd dy dh] = checkgrad(@propagateT5, p, delta, plant, dynmodel, policy, m, s); end function [f, df] = propagateT0(m, plant, dynmodel, policy, s) % dMdm if nargout == 1 M = plant.prop(m, s, plant, dynmodel, policy); else [M, S, dMdm] = plant.prop(m, s, plant, dynmodel, policy); df = permute(dMdm,[1,3,2]); end f = M; function [f, df] = propagateT1(m, plant, dynmodel, policy, s) % dSdm if nargout == 1 [M, S] = plant.prop(m, s, plant, dynmodel, policy); else [M, S, dMdm, dSdm] = plant.prop(m, s, plant, dynmodel, policy); dd = length(M); df = reshape(dSdm,dd,dd,[]); end f = S; function [f, df] = propagateT2(s, plant, dynmodel, policy, m) % dMds d = length(m); ss(tril(ones(d))==1) = s; ss = reshape(ss,d,d); ss = ss + ss' - diag(diag(ss)); if nargout == 1 M = plant.prop(m, ss, plant, dynmodel, policy); else [M, S, dMdm, dSdm, dMds] = plant.prop(m, ss, plant, dynmodel, policy); dd = length(M); dMds = reshape(dMds,dd,d,d); df = zeros(dd,1,d*(d+1)/2); for i=1:dd; dMdsi(:,:) = dMds(i,:,:); dMdsi = dMdsi + dMdsi'-diag(diag(dMdsi)); df(i,:) = dMdsi(tril(ones(d))==1); end end f = M; function [f, df] = propagateT3(s, plant, dynmodel, policy, m) % dSds d = length(m); ss(tril(ones(d))==1) = s; ss = reshape(ss,d,d); ss = ss + ss' - diag(diag(ss)); if nargout == 1 [M, S] = plant.prop(m, ss, plant, dynmodel, policy); else [M, S, dMdm, dSdm, dMds, dSds] = ... plant.prop(m, ss, plant, dynmodel, policy); dd = length(M); dSds = reshape(dSds,dd,dd,d,d); df = zeros(dd,dd,d*(d+1)/2); for i=1:dd; for j=1:dd dSdsi(:,:) = dSds(i,j,:,:); dSdsi = dSdsi+dSdsi'-diag(diag(dSdsi)); df(i,j,:) = dSdsi(tril(ones(d))==1); end; end end f = S; function [f, df] = propagateT4(p, plant, dynmodel, policy, m, s) % dMdp policy.p = rewrap(policy.p, p); if nargout == 1 M = plant.prop(m, s, plant, dynmodel, policy); else [M, S, dMdm, dSdm, dMds, dSds, dMdp] = plant.prop(m, s, plant, dynmodel, policy); df = dMdp; end f = M; function [f, df] = propagateT5(p, plant, dynmodel, policy, m, s) % dSdp policy.p = rewrap(policy.p, p); if nargout == 1 [M, S] = plant.prop(m, s, plant, dynmodel, policy); else [M, S, dMdm, dSdm, dMds, dSds, dMdp, dSdp] = ... plant.prop(m, s, plant, dynmodel, policy); df = dSdp; end f = S;
github
UCL-SML/pilco-matlab-master
gSinSatT.m
.m
pilco-matlab-master/test/gSinSatT.m
4,434
utf_8
1aaa7fdf4505735d6c5f4dc9e5936884
%% gSinSatT.m % *Summary:* Test the gSin and gSat functions. % Check the predictions using Monte Carlo and the derivatives by % finite differences. % % % function gSinSatT(fcn, m, v, i, e) % % % *Input arguments:* % % fcn 'gSin' or 'gSat' % m mean of input distribution [D x 1] % v covariance matrix of input distribution [D x D] % i vector of indices of elements to augment [I x 1] % e (optional) scaling vector; default: 1 [I x 1] % % % Copyright (C) 2008-2013 by % Marc Deisenroth, Andrew McHutchon, Joe Hall, and Carl Edward Rasmussen. % % Last modified: 2013-03-21 function gSinSatT(fcn, m, v, i, e) %% Code if nargin < 2 D = 4; m = randn(D,1); v = randn(D); v = v*v'+eye(D); i = [1;2; 4]; I = length(i); e = exp(randn(size(i))); else D = length(m); end n = 1e6; % monte Carlo sample size delta = 1e-4; % for finite difference approx x = bsxfun(@plus, m, chol(v)'*randn(D,n)); switch func2str(fcn) case 'gSin', y = bsxfun(@times, e, sin(x(i,:))); case 'gSat', y = bsxfun(@times, e, 9*sin(x(i,:))/8+sin(3*x(i,:))/8); otherwise, error('Can only handle gSin and gSat') end [M, V, C] = fcn(m, v, i, e); Q = cov([x' y']); Qv = Q(D+1:end,D+1:end); Qc = v\Q(1:D,D+1:end); disp(['mean: ', func2str(fcn), ' Monte Carlo']) disp([M mean(y,2)]); disp([' ']); disp(['var: ', func2str(fcn), ' Monte Carlo']) disp([V(:) Qv(:)]); disp([' ']); disp(['cov: ', func2str(fcn), ' Monte Carlo']) disp([C(:) Qc(:)]); disp(' '); disp('dMdm') for j = 1:I d = checkgrad(@gSinT0, m, delta, v, i, e, j, fcn); disp(['this was element # ' num2str(j) '/' num2str(I)]); if d > 1e-6; keyboard; end end disp(' '); disp('dVdm') for j = 1:I*I d = checkgrad(@gSinT1, m, delta, v, i, e, j, fcn); disp(['this was element # ' num2str(j) '/' num2str(I*I)]); if d > 1e-6; keyboard; end end disp(' '); disp('dCdm') for j = 1:I*D d= checkgrad(@gSinT2, m, delta, v, i, e, j, fcn); disp(['this was element # ' num2str(j) '/' num2str(I*D)]); if d > 1e-6; keyboard; end end disp(' '); disp('dMdv') for j = 1:I d = checkgrad(@gSinT3, v(tril(ones(length(v)))==1), delta, m, i, e, j, fcn); disp(['this was element # ' num2str(j) '/' num2str(I)]); if d > 1e-6; keyboard; end end disp(' '); disp('dVdv') for j = 1:I*I d = checkgrad(@gSinT4, v(tril(ones(length(v)))==1), delta, m, i, e, j, fcn); disp(['this was element # ' num2str(j) '/' num2str(I*I)]); if d > 1e-6; keyboard; end end disp(' '); disp('dCdv') for j = 1:I*D d = checkgrad(@gSinT5, v(tril(ones(length(v)))==1), delta, m, i, e, j, fcn); disp(['this was element # ' num2str(j) '/' num2str(I*D)]); if d > 1e-6; keyboard; end end function [f, df] = gSinT0(m, v, i, e, j, fcn) [M, V, C, dMdm] = fcn(m, v, i, e); f = M(j); df = dMdm(j,:); function [f, df] = gSinT1(m, v, i, e, j, fcn) [M, V, C, dMdm, dVdm] = fcn(m, v, i, e); dVdm = reshape(dVdm,[size(V) length(m)]); dd = length(M); p = fix((j+dd-1)/dd); q = j-(p-1)*dd; f = V(p,q); df = squeeze(dVdm(p,q,:)); function [f, df] = gSinT2(m, v, i, e, j, fcn) [M, V, C, dMdm, dVdm, dCdm] = fcn(m, v, i, e); dCdm = reshape(dCdm,[size(C) length(m)]); dd = length(M); p = fix((j+dd-1)/dd); q = j-(p-1)*dd; f = C(p,q); df = squeeze(dCdm(p,q,:)); function [f, df] = gSinT3(v, m, i, e, j, fcn) d = length(m); vv(tril(ones(d))==1) = v; vv = reshape(vv,d,d); vv = vv + vv' - diag(diag(vv)); [M, V, C, dMdm, dVdm, dCdm, dMdv] = fcn(m, vv, i, e); dMdv = reshape(dMdv,[length(M) size(vv)]); f = M(j); df = squeeze(dMdv(j,:,:)); df = df+df'-diag(diag(df)); df = df(tril(ones(d))==1); function [f, df] = gSinT4(v, m, i, e, j, fcn) d = length(m); vv(tril(ones(d))==1) = v; vv = reshape(vv,d,d); vv = vv + vv' - diag(diag(vv)); [M, V, C, dMdm, dVdm, dCdm, dMdv, dVdv] = fcn(m, vv, i, e); dVdv = reshape(dVdv,[size(V) size(vv)]); dd = length(M); p = fix((j+dd-1)/dd); q = j-(p-1)*dd; f = V(p,q); df = squeeze(dVdv(p,q,:,:)); df = df+df'-diag(diag(df)); df = df(tril(ones(d))==1); function [f, df] = gSinT5(v, m, i, e, j, fcn) d = length(m); vv(tril(ones(d))==1) = v; vv = reshape(vv,d,d); vv = vv + vv' - diag(diag(vv)); [M, V, C, dMdm, dVdm, dCdm, dMdv, dVdv, dCdv] = fcn(m, vv, i, e); dCdv = reshape(dCdv,[size(C) size(vv)]); dd = length(M); p = fix((j+dd-1)/dd); q = j-(p-1)*dd; f = C(p,q); df = squeeze(dCdv(p,q,:,:)); df = df+df'-diag(diag(df)); df = df(tril(ones(d))==1);
github
UCL-SML/pilco-matlab-master
gpT.m
.m
pilco-matlab-master/test/gpT.m
6,610
utf_8
f6bfd962ef044e7a89f5209e24aa9617
%% gpT.m % *Summary:* Test derivatives of gp*-family of functions. It is assumed that % the gp* function computes the mean and the variance of a GP prediction % for a Gaussian distributed input $x\sim\mathcal N(m,s)$. % The GP-family of functions is located in <rootDir>/gp and is called gp*.m % % % function [dd dy dh] = gpT(deriv, gp, m, s, delta) % % % *Input arguments:* % % deriv desired derivative. options: % (i) 'dMdm' - derivative of the mean of the GP prediction % wrt the mean of the input distribution % (ii) 'dMds' - derivative of the mean of the GP prediction % wrt the variance of the input distribution % (iii) 'dMdp' - derivative of the mean of the GP prediction % wrt the GP parameters % (iv) 'dSdm' - derivative of the variance of the GP prediction % wrt the mean of the input distribution % (v) 'dSds' - derivative of the variance of the GP prediction % wrt the variance of the input distribution % (vi) 'dSdp' - derivative of the variance of the GP prediction % wrt the GP parameters % (vii) 'dVdm' - derivative of inv(s)*(covariance of the input and the % GP prediction) wrt the mean of the input distribution % (viii) 'dVds' - derivative of inv(s)*(covariance of the input and the % GP prediction) wrt the variance of the input distribution % (ix) 'dVdp' - derivative of inv(s)*(covariance of the input and the % GP prediction) wrt the GP parameters % gp GP structure % .fcn function handle to the GP function used for predictions at % uncertain inputs % .<> other fields that are passed on to the GP function % m mean of the input distribution % s covariance of the input distribution % delta (optional) finite difference parameter. Default: 1e-4 % % % *Output arguments:* % % dd relative error of analytical vs. finite difference gradient % dy analytical gradient % dh finite difference gradient % % Copyright (C) 2008-2013 by % Marc Deisenroth, Andrew McHutchon, Joe Hall, and Carl Edward Rasmussen. % % Last modified: 2013-06-07 function [dd dy dh] = gpT(deriv, gp, m, s, delta) %% Code % set up a default training set and input distribution if not passed in if nargin < 2 nn = 1000; np = 100; D = 5; E = 4; % input and predictive dimensions gp.fcn = @gp0d; gp.hyp = [randn(D+1,E); zeros(1,E)]; gp.inputs = randn(nn,D); gp.targets = randn(nn,E); gp.induce = randn(np,D,E); end if nargin < 3 % no input distribution specified if isfield(gp, 'p') % if gp is a policy, extract targets/inputs gp.inputs = gp.p.inputs; gp.targets = gp.p.targets; end D = size(gp.inputs, 2); m = randn(D,1); s = randn(D); s = s*s'; end if nargin < 5; delta = 1e-4; end D = length(m); % input size % check derivatives switch deriv case 'dMdm' [dd dy dh] = checkgrad(@gpT0, m, delta, gp, s); case 'dSdm' [dd dy dh] = checkgrad(@gpT1, m, delta, gp, s); case 'dVdm' [dd dy dh] = checkgrad(@gpT2, m, delta, gp, s); case 'dMds' [dd dy dh] = checkgrad(@gpT3, s(tril(ones(D))==1), delta, gp, m); case 'dSds' [dd dy dh] = checkgrad(@gpT4, s(tril(ones(D))==1), delta, gp, m); case 'dVds' [dd dy dh] = checkgrad(@gpT5, s(tril(ones(D))==1), delta, gp, m); case 'dMdp' p = unwrap(gp); [dd dy dh] = checkgrad(@gpT6, p, delta, gp, m, s) ; case 'dSdp' p = unwrap(gp); [dd dy dh] = checkgrad(@gpT7, p, delta, gp, m, s) ; case 'dVdp' p = unwrap(gp); [dd dy dh] = checkgrad(@gpT8, p, delta, gp, m, s) ; end function [f, df] = gpT0(m, gp, s) % dMdm if nargout == 1 M = gp.fcn(gp, m, s); else [M, S, V, dMdm] = gp.fcn(gp, m, s); df = dMdm; end f = M; function [f, df] = gpT1(m, gp, s) % dSdm if nargout == 1 [M, S] = gp.fcn(gp, m, s); else [M, S, V, dMdm, dSdm] = gp.fcn(gp, m, s); df = dSdm; end f = S; function [f, df] = gpT2(m, gp, s) % dVdm if nargout == 1 [M, S, V] = gp.fcn(gp, m, s); else [M, S, V, dMdm, dSdm, dVdm] = gp.fcn(gp, m, s); df = dVdm; end f = V; function [f, df] = gpT3(s, gp, m) % dMds d = length(m); v(tril(ones(d))==1) = s; s = reshape(v,d,d); s = s+s'-diag(diag(s)); if nargout == 1 M = gp.fcn(gp, m, s); else [M, S, V, dMdm, dSdm, dVdm, dMds] = gp.fcn(gp, m, s); dd = length(M); dMds = reshape(dMds,dd,d,d); df = zeros(dd,d*(d+1)/2); for i=1:dd; dMdsi(:,:) = dMds(i,:,:); dMdsi = dMdsi + dMdsi'-diag(diag(dMdsi)); df(i,:) = dMdsi(tril(ones(d))==1); end end f = M; function [f, df] = gpT4(s, gp, m) % dSds d = length(m); v(tril(ones(d))==1) = s; s = reshape(v,d,d); s = s+s'-diag(diag(s)); if nargout == 1 [M, S] = gp.fcn(gp, m, s); else [M, S, C, dMdm, dSdm, dCdm, dMds, dSds] = gp.fcn(gp, m, s); dd = length(M); dSds = reshape(dSds,dd,dd,d,d); df = zeros(dd,dd,d*(d+1)/2); for i=1:dd; for j=1:dd dSdsi(:,:) = dSds(i,j,:,:); dSdsi = dSdsi+dSdsi'-diag(diag(dSdsi)); df(i,j,:) = dSdsi(tril(ones(d))==1); end; end end f = S; function [f, df] = gpT5(s, gp, m) % dVds d = length(m); v(tril(ones(d))==1) = s; s = reshape(v,d,d); s = s+s'-diag(diag(s)); if nargout == 1 [M, S, V] = gp.fcn(gp, m, s); else [M, S, V, dMdm, dSdm, dVdm, dMds, dSds, dVds] = gp.fcn(gp, m, s); dd = length(M); dVds = reshape(dVds,d,dd,d,d); df = zeros(d,dd,d*(d+1)/2); for i=1:d; for j=1:dd dCdsi = squeeze(dVds(i,j,:,:)); dCdsi = dCdsi+dCdsi'-diag(diag(dCdsi)); df(i,j,:) = dCdsi(tril(ones(d))==1); end; end end f = V; function [f, df] = gpT6(p, gp, m, s) % dMdp gp = rewrap(gp, p); if nargout == 1 M = gp.fcn(gp, m, s); else [M, S, V, dMdm, dSdm, dVdm, dMds, dSds, dVds, dMdp] = ... gp.fcn(gp, m, s); df = dMdp; end f = M; function [f, df] = gpT7(p, gp, m, s) % dSdp gp = rewrap(gp, p); if nargout == 1 [M, S] = gp.fcn(gp, m, s); else [M, S, V, dMdm, dSdm, dVdm, dMds, dSds, dVds, dMdp, dSdp] = ... gp.fcn(gp, m, s); df = dSdp; end f = S; function [f, df] = gpT8(p, gp, m, s) gp = rewrap(gp, p); if nargout == 1 [M, S, V] = gp.fcn(gp, m, s); else [M, S, V, dMdm, dSdm, dVdm, dMds, dSds, dVds, dMdp, dSdp, dVdp] = ... gp.fcn(gp, m, s); df = dVdp; end f = V;
github
iuriivoitenko/simpleMANET-master
ini2struct.m
.m
simpleMANET-master/functions/ini2struct.m
3,371
utf_8
3ca01220c3135789fd6a8393f0dd9233
% Copyright (c) 2014, freeb % Copyright (c) 2008, Andriy Nych % Copyright (c) 2009-2010, Evgeny Prilepin aka Iroln % All rights reserved. % % Redistribution and use in source and binary forms, with or without % modification, are permitted provided that the following conditions are % met: % % * Redistributions of source code must retain the above copyright % notice, this list of conditions and the following disclaimer. % * Redistributions in binary form must reproduce the above copyright % notice, this list of conditions and the following disclaimer in % the documentation and/or other materials provided with the distribution % * Neither the name of the nor the names % of its contributors may be used to endorse or promote products derived % from this software without specific prior written permission. % % THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" % AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE % ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE % LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR % CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF % SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS % INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN % CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) % ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE % POSSIBILITY OF SUCH DAMAGE. function Struct = ini2struct(FileName) % Parses .ini file % Returns a structure with section names and keys as fields. % % Based on init2struct.m by Andriy Nych % 2014/02/01 f = fopen(FileName,'r'); % open file while ~feof(f) % and read until it ends s = strtrim(fgetl(f)); % remove leading/trailing spaces if isempty(s) || s(1)==';' || s(1)=='#' % skip empty & comments lines continue end if s(1)=='[' % section header Section = genvarname(strtok(s(2:end), ']')); Struct.(Section) = []; % create field continue end [Key,Val] = strtok(s, '='); % Key = Value ; comment Val = strtrim(Val(2:end)); % remove spaces after = if isempty(Val) || Val(1)==';' || Val(1)=='#' % empty entry Val = []; elseif Val(1)=='"' % double-quoted string Val = strtok(Val, '"'); elseif Val(1)=='''' % single-quoted string Val = strtok(Val, ''''); else Val = strtok(Val, ';'); % remove inline comment Val = strtok(Val, '#'); % remove inline comment Val = strtrim(Val); % remove spaces before comment [val, status] = str2num(Val); %#ok<ST2NM> if status, Val = val; end % convert string to number(s) end if ~exist('Section', 'var') % No section found before Struct.(genvarname(Key)) = Val; else % Section found before, fill it Struct.(Section).(genvarname(Key)) = Val; end end fclose(f);
github
DeepCognition/Segmentation-Demo-master
classification_demo.m
.m
Segmentation-Demo-master/matlab/demo/classification_demo.m
5,412
utf_8
8f46deabe6cde287c4759f3bc8b7f819
function [scores, maxlabel] = classification_demo(im, use_gpu) % [scores, maxlabel] = classification_demo(im, use_gpu) % % Image classification demo using BVLC CaffeNet. % % IMPORTANT: before you run this demo, you should download BVLC CaffeNet % from Model Zoo (http://caffe.berkeleyvision.org/model_zoo.html) % % **************************************************************************** % For detailed documentation and usage on Caffe's Matlab interface, please % refer to Caffe Interface Tutorial at % http://caffe.berkeleyvision.org/tutorial/interfaces.html#matlab % **************************************************************************** % % input % im color image as uint8 HxWx3 % use_gpu 1 to use the GPU, 0 to use the CPU % % output % scores 1000-dimensional ILSVRC score vector % maxlabel the label of the highest score % % You may need to do the following before you start matlab: % $ export LD_LIBRARY_PATH=/opt/intel/mkl/lib/intel64:/usr/local/cuda-5.5/lib64 % $ export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libstdc++.so.6 % Or the equivalent based on where things are installed on your system % % Usage: % im = imread('../../examples/images/cat.jpg'); % scores = classification_demo(im, 1); % [score, class] = max(scores); % Five things to be aware of: % caffe uses row-major order % matlab uses column-major order % caffe uses BGR color channel order % matlab uses RGB color channel order % images need to have the data mean subtracted % Data coming in from matlab needs to be in the order % [width, height, channels, images] % where width is the fastest dimension. % Here is the rough matlab for putting image data into the correct % format in W x H x C with BGR channels: % % permute channels from RGB to BGR % im_data = im(:, :, [3, 2, 1]); % % flip width and height to make width the fastest dimension % im_data = permute(im_data, [2, 1, 3]); % % convert from uint8 to single % im_data = single(im_data); % % reshape to a fixed size (e.g., 227x227). % im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear'); % % subtract mean_data (already in W x H x C with BGR channels) % im_data = im_data - mean_data; % If you have multiple images, cat them with cat(4, ...) % Add caffe/matlab to you Matlab search PATH to use matcaffe if exist('../+caffe', 'dir') addpath('..'); else error('Please run this demo from caffe/matlab/demo'); end % Set caffe mode if exist('use_gpu', 'var') && use_gpu caffe.set_mode_gpu(); gpu_id = 0; % we will use the first gpu in this demo caffe.set_device(gpu_id); else caffe.set_mode_cpu(); end % Initialize the network using BVLC CaffeNet for image classification % Weights (parameter) file needs to be downloaded from Model Zoo. model_dir = '../../models/bvlc_reference_caffenet/'; net_model = [model_dir 'deploy.prototxt']; net_weights = [model_dir 'bvlc_reference_caffenet.caffemodel']; phase = 'test'; % run with phase test (so that dropout isn't applied) if ~exist(net_weights, 'file') error('Please download CaffeNet from Model Zoo before you run this demo'); end % Initialize a network net = caffe.Net(net_model, net_weights, phase); if nargin < 1 % For demo purposes we will use the cat image fprintf('using caffe/examples/images/cat.jpg as input image\n'); im = imread('../../examples/images/cat.jpg'); end % prepare oversampled input % input_data is Height x Width x Channel x Num tic; input_data = {prepare_image(im)}; toc; % do forward pass to get scores % scores are now Channels x Num, where Channels == 1000 tic; % The net forward function. It takes in a cell array of N-D arrays % (where N == 4 here) containing data of input blob(s) and outputs a cell % array containing data from output blob(s) scores = net.forward(input_data); toc; scores = scores{1}; scores = mean(scores, 2); % take average scores over 10 crops [~, maxlabel] = max(scores); % call caffe.reset_all() to reset caffe caffe.reset_all(); % ------------------------------------------------------------------------ function crops_data = prepare_image(im) % ------------------------------------------------------------------------ % caffe/matlab/+caffe/imagenet/ilsvrc_2012_mean.mat contains mean_data that % is already in W x H x C with BGR channels d = load('../+caffe/imagenet/ilsvrc_2012_mean.mat'); mean_data = d.mean_data; IMAGE_DIM = 256; CROPPED_DIM = 227; % Convert an image returned by Matlab's imread to im_data in caffe's data % format: W x H x C with BGR channels im_data = im(:, :, [3, 2, 1]); % permute channels from RGB to BGR im_data = permute(im_data, [2, 1, 3]); % flip width and height im_data = single(im_data); % convert from uint8 to single im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear'); % resize im_data im_data = im_data - mean_data; % subtract mean_data (already in W x H x C, BGR) % oversample (4 corners, center, and their x-axis flips) crops_data = zeros(CROPPED_DIM, CROPPED_DIM, 3, 10, 'single'); indices = [0 IMAGE_DIM-CROPPED_DIM] + 1; n = 1; for i = indices for j = indices crops_data(:, :, :, n) = im_data(i:i+CROPPED_DIM-1, j:j+CROPPED_DIM-1, :); crops_data(:, :, :, n+5) = crops_data(end:-1:1, :, :, n); n = n + 1; end end center = floor(indices(2) / 2) + 1; crops_data(:,:,:,5) = ... im_data(center:center+CROPPED_DIM-1,center:center+CROPPED_DIM-1,:); crops_data(:,:,:,10) = crops_data(end:-1:1, :, :, 5);
github
DeepCognition/Segmentation-Demo-master
MyVOCevalseg.m
.m
Segmentation-Demo-master/matlab/my_script/MyVOCevalseg.m
4,625
utf_8
128c24319d520c2576168d1cf17e068f
%VOCEVALSEG Evaluates a set of segmentation results. % VOCEVALSEG(VOCopts,ID); prints out the per class and overall % segmentation accuracies. Accuracies are given using the intersection/union % metric: % true positives / (true positives + false positives + false negatives) % % [ACCURACIES,AVACC,CONF] = VOCEVALSEG(VOCopts,ID) returns the per class % percentage ACCURACIES, the average accuracy AVACC and the confusion % matrix CONF. % % [ACCURACIES,AVACC,CONF,RAWCOUNTS] = VOCEVALSEG(VOCopts,ID) also returns % the unnormalised confusion matrix, which contains raw pixel counts. function [accuracies,avacc,conf,rawcounts] = MyVOCevalseg(VOCopts,id) % image test set [gtids,t]=textread(sprintf(VOCopts.seg.imgsetpath,VOCopts.testset),'%s %d'); % number of labels = number of classes plus one for the background num = VOCopts.nclasses+1; confcounts = zeros(num); count=0; num_missing_img = 0; tic; for i=1:length(gtids) % display progress if toc>1 fprintf('test confusion: %d/%d\n',i,length(gtids)); drawnow; tic; end imname = gtids{i}; % ground truth label file gtfile = sprintf(VOCopts.seg.clsimgpath,imname); [gtim,map] = imread(gtfile); gtim = double(gtim); % results file resfile = sprintf(VOCopts.seg.clsrespath,id,VOCopts.testset,imname); try [resim,map] = imread(resfile); catch err num_missing_img = num_missing_img + 1; %fprintf(1, 'Fail to read %s\n', resfile); continue; end resim = double(resim); % Check validity of results image maxlabel = max(resim(:)); if (maxlabel>VOCopts.nclasses), error('Results image ''%s'' has out of range value %d (the value should be <= %d)',imname,maxlabel,VOCopts.nclasses); end szgtim = size(gtim); szresim = size(resim); if any(szgtim~=szresim) error('Results image ''%s'' is the wrong size, was %d x %d, should be %d x %d.',imname,szresim(1),szresim(2),szgtim(1),szgtim(2)); end %pixel locations to include in computation locs = gtim<255; % joint histogram sumim = 1+gtim+resim*num; hs = histc(sumim(locs),1:num*num); count = count + numel(find(locs)); confcounts(:) = confcounts(:) + hs(:); end if (num_missing_img > 0) fprintf(1, 'WARNING: There are %d missing results!\n', num_missing_img); end % confusion matrix - first index is true label, second is inferred label %conf = zeros(num); conf = 100*confcounts./repmat(1E-20+sum(confcounts,2),[1 size(confcounts,2)]); rawcounts = confcounts; % Pixel Accuracy overall_acc = 100*sum(diag(confcounts)) / sum(confcounts(:)); fprintf('Percentage of pixels correctly labelled overall: %6.3f%%\n',overall_acc); % Class Accuracy class_acc = zeros(1, num); class_count = 0; fprintf('Accuracy for each class (pixel accuracy)\n'); for i = 1 : num denom = sum(confcounts(i, :)); if (denom == 0) denom = 1; end class_acc(i) = 100 * confcounts(i, i) / denom; if i == 1 clname = 'background'; else clname = VOCopts.classes{i-1}; end if ~strcmp(clname, 'void') class_count = class_count + 1; fprintf(' %14s: %6.3f%%\n', clname, class_acc(i)); end end fprintf('-------------------------\n'); avg_class_acc = sum(class_acc) / class_count; fprintf('Mean Class Accuracy: %6.3f%%\n', avg_class_acc); % Pixel IOU accuracies = zeros(VOCopts.nclasses,1); fprintf('Accuracy for each class (intersection/union measure)\n'); real_class_count = 0; for j=1:num gtj=sum(confcounts(j,:)); resj=sum(confcounts(:,j)); gtjresj=confcounts(j,j); % The accuracy is: true positive / (true positive + false positive + false negative) % which is equivalent to the following percentage: denom = (gtj+resj-gtjresj); if denom == 0 denom = 1; end accuracies(j)=100*gtjresj/denom; clname = 'background'; if (j>1), clname = VOCopts.classes{j-1};end; if ~strcmp(clname, 'void') real_class_count = real_class_count + 1; else if denom ~= 1 fprintf(1, 'WARNING: this void class has denom = %d\n', denom); end end if ~strcmp(clname, 'void') fprintf(' %14s: %6.3f%%\n',clname,accuracies(j)); end end %accuracies = accuracies(1:end); %avacc = mean(accuracies); avacc = sum(accuracies) / real_class_count; fprintf('-------------------------\n'); fprintf('Average accuracy: %6.3f%%\n',avacc);
github
DeepCognition/Segmentation-Demo-master
MyVOCevalsegBoundary.m
.m
Segmentation-Demo-master/matlab/my_script/MyVOCevalsegBoundary.m
4,415
utf_8
1b648714e61bafba7c08a8ce5824b105
%VOCEVALSEG Evaluates a set of segmentation results. % VOCEVALSEG(VOCopts,ID); prints out the per class and overall % segmentation accuracies. Accuracies are given using the intersection/union % metric: % true positives / (true positives + false positives + false negatives) % % [ACCURACIES,AVACC,CONF] = VOCEVALSEG(VOCopts,ID) returns the per class % percentage ACCURACIES, the average accuracy AVACC and the confusion % matrix CONF. % % [ACCURACIES,AVACC,CONF,RAWCOUNTS] = VOCEVALSEG(VOCopts,ID) also returns % the unnormalised confusion matrix, which contains raw pixel counts. function [accuracies,avacc,conf,rawcounts, overall_acc, avg_class_acc] = MyVOCevalsegBoundary(VOCopts, id, w) % get structural element st_w = 2*w + 1; se = strel('square', st_w); % image test set fn = sprintf(VOCopts.seg.imgsetpath,VOCopts.testset); fid = fopen(fn, 'r'); gtids = textscan(fid, '%s'); gtids = gtids{1}; fclose(fid); %[gtids,t]=textread(sprintf(VOCopts.seg.imgsetpath,VOCopts.testset),'%s %d'); % number of labels = number of classes plus one for the background num = VOCopts.nclasses+1; confcounts = zeros(num); count=0; tic; for i=1:length(gtids) % display progress if toc>1 fprintf('test confusion: %d/%d\n',i,length(gtids)); drawnow; tic; end imname = gtids{i}; % ground truth label file gtfile = sprintf(VOCopts.seg.clsimgpath,imname); [gtim,map] = imread(gtfile); gtim = double(gtim); % results file resfile = sprintf(VOCopts.seg.clsrespath,id,VOCopts.testset,imname); try [resim,map] = imread(resfile); catch err fprintf(1, 'Fail to read %s\n', resfile); continue; end resim = double(resim); % Check validity of results image maxlabel = max(resim(:)); if (maxlabel>VOCopts.nclasses), error('Results image ''%s'' has out of range value %d (the value should be <= %d)',imname,maxlabel,VOCopts.nclasses); end szgtim = size(gtim); szresim = size(resim); if any(szgtim~=szresim) error('Results image ''%s'' is the wrong size, was %d x %d, should be %d x %d.',imname,szresim(1),szresim(2),szgtim(1),szgtim(2)); end % dilate gt binary_gt = gtim == 255; dilate_gt = imdilate(binary_gt, se); target_gt = dilate_gt & (gtim~=255); %pixel locations to include in computation locs = target_gt; %locs = gtim<255; % joint histogram sumim = 1+gtim+resim*num; hs = histc(sumim(locs),1:num*num); count = count + numel(find(locs)); confcounts(:) = confcounts(:) + hs(:); end % confusion matrix - first index is true label, second is inferred label %conf = zeros(num); conf = 100*confcounts./repmat(1E-20+sum(confcounts,2),[1 size(confcounts,2)]); rawcounts = confcounts; % Pixel Accuracy overall_acc = 100*sum(diag(confcounts)) / sum(confcounts(:)); fprintf('Percentage of pixels correctly labelled overall: %6.3f%%\n',overall_acc); % Class Accuracy class_acc = zeros(1, num); class_count = 0; fprintf('Accuracy for each class (pixel accuracy)\n'); for i = 1 : num denom = sum(confcounts(i, :)); if (denom == 0) denom = 1; else class_count = class_count + 1; end class_acc(i) = 100 * confcounts(i, i) / denom; if i == 1 clname = 'background'; else clname = VOCopts.classes{i-1}; end fprintf(' %14s: %6.3f%%\n', clname, class_acc(i)); end fprintf('-------------------------\n'); avg_class_acc = sum(class_acc) / class_count; fprintf('Mean Class Accuracy: %6.3f%%\n', avg_class_acc); % Pixel IOU accuracies = zeros(VOCopts.nclasses,1); fprintf('Accuracy for each class (intersection/union measure)\n'); for j=1:num gtj=sum(confcounts(j,:)); resj=sum(confcounts(:,j)); gtjresj=confcounts(j,j); % The accuracy is: true positive / (true positive + false positive + false negative) % which is equivalent to the following percentage: accuracies(j)=100*gtjresj/(gtj+resj-gtjresj); clname = 'background'; if (j>1), clname = VOCopts.classes{j-1};end; fprintf(' %14s: %6.3f%%\n',clname,accuracies(j)); end accuracies = accuracies(1:end); avacc = mean(accuracies); fprintf('-------------------------\n'); fprintf('Average accuracy: %6.3f%%\n',avacc);
github
wangsuyuan/Imageprocesingtoobox-master
LocalWeightedMeanTransformation2D.m
.m
Imageprocesingtoobox-master/+geotrans/LocalWeightedMeanTransformation2D.m
9,665
utf_8
fb03604c551b06668ad51f81b45db77c
%images.geotrans.LocalWeightedMeanTransformation2D 2-D Local Weighted Mean Geometric Transformation % % An images.geotrans.LocalWeightedMeanTransformation2D object encapsulates a 2-D local weighted mean geometric transformation. % % images.geotrans.LocalWeightedMeanTransformation2D properties: % Dimensionality - Dimensionality of geometric transformation % % images.geotrans.LocalWeightedMeanTransformation2D methods: % LocalWeightedMeanTransformation2D - Construct images.geotrans.LocalWeightedMeanTransformation2D object % outputLimits - Find output spatial limits given input spatial limits % transformPointsInverse - Apply inverse 2-D geometric transformation to points % % Example 1 % --------- % % Fit a local weighted mean transformation to a set of fixed and moving % % control points that are actually related by a global second degree % % polynomial transformation across the entire plane. % x = [10, 12, 17, 14, 7, 10]; % y = [8, 2, 6, 10, 20, 4]; % % a = [1 2 3 4 5 6]; % b = [2.3 3 4 5 6 7.5]; % % u = a(1) + a(2).*x + a(3).*y + a(4) .*x.*y + a(5).*x.^2 + a(6).*y.^2; % v = b(1) + b(2).*x + b(3).*y + b(4) .*x.*y + b(5).*x.^2 + b(6).*y.^2; % % movingPoints = [u',v']; % fixedPoints = [x',y']; % % % Fit local weighted mean transformation to points. % tformLocalWeightedMean = images.geotrans.LocalWeightedMeanTransformation2D(movingPoints,fixedPoints,6); % % % Verify the fit of our LocalWeightedMeanTransformation2D object at the control % % points. % movingPointsComputed = transformPointsInverse(tformLocalWeightedMean,fixedPoints); % % errorInFit = hypot(movingPointsComputed(:,1)-movingPoints(:,1),... % movingPointsComputed(:,2)-movingPoints(:,2)) % % See also AFFINE2D, IMWARP % Copyright 2012-2013 The MathWorks, Inc. classdef LocalWeightedMeanTransformation2D < images.geotrans.internal.GeometricTransformation properties (Access = private) State uvPoints xyPoints Degree N NumericPrecision end methods function self = LocalWeightedMeanTransformation2D(uv,xy,N) %LocalWeightedMeanTransformation2D Construct images.geotrans.LocalWeightedMeanTransformation2D object % % tform = images.geotrans.LocalWeightedMeanTransformation2D(movingPoints,fixedPoints,N) % constructs an images.geotrans.LocalWeightedMeanTransformation2D object % given Mx2 matrices movingPoints, and fixedPoints which % define matched control points in the moving and fixed % images, respectively. The local weighted mean % transformation creates a mapping, by inferring a polynomial % at each control point using neighboring control points. The % mapping at any location depends on a weighted average of % these polynomials. The N closest points are used to infer a % second degree polynomial transformation for each control % point pair. N can be as small as 6, but making N small % risks generating ill-conditioned polynomials. self.Dimensionality = 2; self.Degree = 2; M = size(xy,1); K = (self.Degree+1)*(self.Degree+2)/2; validateControlPoints(uv,xy,N); self.NumericPrecision = 'double'; if ~isa(uv,'double') || ~isa(xy,'double') % Underlying tformlocalmex module requires that properties % are computed in double. uv = double(uv); xy = double(xy); self.NumericPrecision = 'single'; end self.uvPoints = uv; self.xyPoints = xy; self.N = N; x = xy(:,1); y = xy(:,2); u = uv(:,1); v = uv(:,2); T = zeros(K,2,M); radii = zeros(M,1); for icp = 1:M % find N closest points distcp = sqrt( (x-x(icp)).^2 + (y-y(icp)).^2 ); [dist_sorted,indx] = sort(distcp); radii(icp) = dist_sorted(N); neighbors = indx(1:N); neighbors = sort(neighbors); xcp = x(neighbors); ycp = y(neighbors); ucp = u(neighbors); vcp = v(neighbors); % set up matrix equation for second degree polynomial. X = [ones(N,1), xcp, ycp, xcp.*ycp, xcp.^2, ycp.^2]; if rank(X)>=K % u = X*A, v = X*B, solve for A and B: A = X\ucp; B = X\vcp; T(:,:,icp) = [A B]; else error(message('images:geotrans:requiredNonCollinearPoints', K, 'polynomial')) end end % State is a struct that we use to package up data to pass to % the MEX module that computes the inverse transformation. self.State = struct('LWMTData',[],'ControlPoints',[],'RadiiOfInfluence',[]); self.State.LWMTData = T; self.State.ControlPoints = xy; self.State.RadiiOfInfluence = radii; end function varargout = transformPointsInverse(self,varargin) %transformPointsInverse Apply inverse geometric transformation % % [u,v] = transformPointsInverse(tform,x,y) % applies the inverse transformation of tform to the input 2-D % point arrays x,y and outputs the point arrays u,v. The % input point arrays x and y must be of the same size. % % U = transformPointsInverse(tform,X) % applies the inverse transformation of tform to the input % Nx2 point matrix X and outputs the Nx2 point matrix U. % transformPointsFoward maps the point X(k,:) to the point % U(k,:). if numel(varargin) > 1 x = varargin{1}; y = varargin{2}; validateattributes(x,{'single','double'},{'real','nonsparse'},... 'transformPointsInverse','X'); validateattributes(y,{'single','double'},{'real','nonsparse'},... 'transformPointsInverse','Y'); if ~isequal(size(x),size(y)) error(message('images:geotrans:transformPointsSizeMismatch','transformPointsInverse','X','Y')); end inputPointDims = size(x); x = reshape(x,numel(x),1); y = reshape(y,numel(y),1); X = [x,y]; U = images.geotrans.internal.inv_lwm(self.State,double(X)); % If class was constructed from single control points or if % points passed to transformPointsInverse are single, % return single to emulate MATLAB Math casting rules. if isa(X,'single') || strcmp(self.NumericPrecision,'single') U = single(U); end varargout{1} = reshape(U(:,1),inputPointDims); varargout{2} = reshape(U(:,2), inputPointDims); else X = varargin{1}; validateattributes(X,{'single','double'},{'real','nonsparse','2d'},... 'transformPointsInverse','X'); if ~isequal(size(X,2),2) error(message('images:geotrans:transformPointsPackedMatrixInvalidSize',... 'transformPointsInverse','X')); end U = images.geotrans.internal.inv_lwm(self.State,double(X)); % If class was constructed from single control points or if % points passed to transformPointsInverse are single, % return single to emulate MATLAB Math casting rules. if isa(X,'single') || strcmp(self.NumericPrecision,'single') U = single(U); end varargout{1} = U; end end end % saveobj and loadobj are implemented to ensure compatibility across % releases even if architecture of geometric transformation classes % changes. methods (Hidden) function S = saveobj(self) S = struct('uvPoints',self.uvPoints,'xyPoints',self.xyPoints,'N',self.N); end end methods (Static, Hidden) function self = loadobj(S) self = images.geotrans.LocalWeightedMeanTransformation2D(S.uvPoints,S.xyPoints,S.N); end end end function validateControlPoints(xy,uv,N) images.geotrans.internal.validateControlPoints(uv,xy); validateattributes(N,{'numeric'},{'real','nonsparse','scalar'},... 'LocalWeightedMeanTransformation2D','N'); if N < 6 error(message('images:geotrans:LWMSecondDegreePolynomialRequires6Points')); end if N > size(xy,1) error(message('images:geotrans:LWMNGreaterThanNumPoints')); end end
github
wangsuyuan/Imageprocesingtoobox-master
PiecewiseLinearTransformation2D.m
.m
Imageprocesingtoobox-master/+geotrans/PiecewiseLinearTransformation2D.m
12,449
utf_8
d20232ab7aabeb3674c5ce7ca9145ace
%images.geotrans.PiecewiseLinearTransformation2D 2-D Piecewise Linear Geometric Transformation % % An images.geotrans.PiecewiseLinearTransformation2D object encapsulates a 2-D piecewise linear geometric transformation. % % images.geotrans.PiecewiseLinearTransformation2D properties: % Dimensionality - Dimensionality of geometric transformation % % images.geotrans.PiecewiseLinearTransformation2D methods: % PiecewiseLinearTransformation2D - Construct images.geotrans.PiecewiseLinearTransformation2D object % outputLimits - Find output spatial limits given input spatial limits % transformPointsInverse - Apply inverse 2-D geometric transformation to points % % Example 1 % --------- % % Fit a piecewise linear transformation to a set of fixed and moving % % control points that are actually related by a single global affine2d % % transformation across the domain. % theta = 10; % tformAffine = affine2d([cosd(theta) -sind(theta) 0; sind(theta) cosd(theta) 0; 0 0 1]); % % % Arbitrarily choose 6 pairs of control points. % fixedPoints = [10 20; 10 5; 2 3; 0 5; -5 3; -10 -20]; % % % Apply forward geometric transformation to map fixed points to obtain % % effect of fixed and moving points that are related by some geometric % % transformation. % movingPoints = transformPointsForward(tformAffine,fixedPoints); % % % Estimate piecewise linear transformation that maps movingPoints to fixedPoints. % tformPiecewiseLinear = images.geotrans.PiecewiseLinearTransformation2D(movingPoints,fixedPoints); % % % Verify the fit of our PiecewiseLinearTransformation2D object at the control % % points. % movingPointsComputed = transformPointsInverse(tformPiecewiseLinear,fixedPoints); % % errorInFit = hypot(movingPointsComputed(:,1)-movingPoints(:,1),... % movingPointsComputed(:,2)-movingPoints(:,2)) % % See also AFFINE2D, IMWARP % Copyright 2012-2013 The MathWorks, Inc. classdef PiecewiseLinearTransformation2D < images.geotrans.internal.GeometricTransformation methods function self = PiecewiseLinearTransformation2D(uv,xy) %PiecewiseLinearTransformation2D Construct images.geotrans.PiecewiseLinearTransformation2D object % % tform = images.geotrans.PiecewiseLinearTransformation2D(movingPoints,fixedPoints) % constructs an images.geotrans.PiecewiseLinearTransformation2D object % given Mx2 matrices movingPoints, and fixedPoints which % define matched control points in the moving and fixed % images, respectively. % Define required property from base class self.Dimensionality = 2; images.geotrans.internal.validateControlPoints(uv,xy); % MEX module currently requires that computation is done in % double self.NumericPrecision = 'double'; if ~isa(uv,'double') || ~isa(xy,'double') uv = double(uv); xy = double(xy); self.NumericPrecision = 'single'; end self.UVVertices = uv; self.XYVertices = xy; x = xy(:,1); y = xy(:,2); tri = delaunay(x,y); ntri = size(tri,1); % Require 4 points (2 triangles). minRequiredPoints = 4; if (ntri<2) error(message('images:geotrans:requiredNonCollinearPoints', minRequiredPoints, 'piecewise linear')); end % Find all inside-out triangles bad_triangles = FindInsideOut(xy,uv,tri); if ~isempty(bad_triangles) [xy,uv,tri,ntri] = eliminateFoldOverTriangles(self,bad_triangles,xy,uv,tri); end % calculate reverse mapping for each triangle T = zeros(3,2,ntri); for itri = 1:ntri X = [ xy( tri(itri,:), : ) ones(3,1)]; U = uv( tri(itri,:), : ); if (rank(X) >= 3) T(:,:,itri) = X\U; else error(message('images:geotrans:requiredNonCollinearPoints', minRequiredPoints, 'piecewise linear')); end end % Create TriangleGraph which is a sparse connectivity matrix nxy = size(xy,1); S = sparse( repmat((1:ntri)',1,3), tri, 1, ntri, nxy); % Create OnHull to be 1 for ControlPoints on convex hull, 0 for % interior points. hull_indices = convhull(x,y); self.State = struct('Triangles',[],... 'ControlPoints',[],... 'OnHull',[],... 'ConvexHullVertices',[],... 'TriangleGraph',[],... 'PiecewiseLinearTData',[]); self.State.OnHull = zeros(size(x)); self.State.OnHull(hull_indices) = 1; self.State.Triangles = tri; self.State.ControlPoints = xy; self.State.ConvexHullVertices = hull_indices; self.State.TriangleGraph = S; self.State.PiecewiseLinearTData = T; end function varargout = transformPointsInverse(self,varargin) %transformPointsInverse Apply inverse geometric transformation % % [u,v] = transformPointsInverse(tform,x,y) % applies the inverse transformation of tform to the input 2-D % point arrays x,y and outputs the point arrays u,v. The % input point arrays x and y must be of the same size. % % U = transformPointsInverse(tform,X) % applies the inverse transformation of tform to the input % Nx2 point matrix X and outputs the Nx2 point matrix U. % transformPointsFoward maps the point X(k,:) to the point % U(k,:). if numel(varargin) > 1 x = varargin{1}; y = varargin{2}; validateattributes(x,{'single','double'},{'real','nonsparse'},... 'transformPointsInverse','X'); validateattributes(y,{'single','double'},{'real','nonsparse'},... 'transformPointsInverse','Y'); if ~isequal(size(x),size(y)) error(message('images:geotrans:transformPointsSizeMismatch','transformPointsInverse','X','Y')); end inputPointDims = size(x); x = reshape(x,numel(x),1); y = reshape(y,numel(y),1); X = [x,y]; U = images.geotrans.internal.inv_piecewiselinear(self.State,double(X)); % If class was constructed from single control points or if % points passed to transformPointsInverse are single, % return single to emulate MATLAB Math casting rules. if isa(X,'single') || strcmp(self.NumericPrecision,'single') U = single(U); end varargout{1} = reshape(U(:,1),inputPointDims); varargout{2} = reshape(U(:,2), inputPointDims); else X = varargin{1}; validateattributes(X,{'single','double'},{'real','nonsparse','2d'},... 'transformPointsInverse','X'); if ~isequal(size(X,2),2) error(message('images:geotrans:transformPointsPackedMatrixInvalidSize',... 'transformPointsInverse','X')); end U = images.geotrans.internal.inv_piecewiselinear(self.State,double(X)); % If class was constructed from single control points or if % points passed to transformPointsInverse are single, % return single to emulate MATLAB Math casting rules. if isa(X,'single') || strcmp(self.NumericPrecision,'single') U = single(U); end varargout{1} = U; end end end properties (Access = 'private') State BadXYVertices BadUVVertices XYVertices UVVertices NumericPrecision end methods (Access = 'private') function [xy,uv,tri,ntri] = eliminateFoldOverTriangles(self,bad_triangles,xy,uv,tri) x = xy(:,1); y = xy(:,2); % find bad_vertices, eliminate bad_vertices num_bad_triangles = length(bad_triangles); bad_vertices = zeros(num_bad_triangles,1); for i = 1:num_bad_triangles bad_vertices(i) = FindBadVertex(x,y,tri(bad_triangles(i),:)); end bad_vertices = unique(bad_vertices); num_bad_vertices = length(bad_vertices); % Cache bad vertices that were eliminated self.BadXYVertices = xy(bad_vertices,:); self.BadUVVertices = uv(bad_vertices,:); xy(bad_vertices,:) = []; % eliminate bad ones uv(bad_vertices,:) = []; nvert = size(xy,1); % Cache good vertices self.XYVertices = xy; self.UVVertices = uv; minRequiredPoints = 4; if (nvert < minRequiredPoints) error(message('images:geotrans:deletedPointsNowInsufficientControlPoints', num_bad_vertices, nvert, minRequiredPoints, 'piecewise linear')) end x = xy(:,1); y = xy(:,2); tri = delaunay(x,y); ntri = size(tri,1); % Error if we cannot produce a valid piecewise linear correspondence % after the second triangulation. more_bad_triangles = FindInsideOut(xy,uv,tri); if ~isempty(more_bad_triangles) error(message('images:geotrans:foldoverTrianglesRemain', num_bad_vertices)) end % Warn to report about triangles and how many points were eliminated warning(message('images:geotrans:foldoverTriangles', sprintf( '%d ', bad_triangles ), sprintf( '%d ', bad_vertices ))) end end % saveobj and loadobj are implemented to ensure compatibility across % releases even if architecture of geometric transformation classes % changes. methods (Hidden) function S = saveobj(self) S = struct('uvPoints',self.UVVertices,'xyPoints',self.XYVertices); end end methods (Static, Hidden) function self = loadobj(S) self = images.geotrans.PiecewiseLinearTransformation2D(S.uvPoints,S.xyPoints); end end end function index = FindInsideOut(xy,uv,tri) % look for inside-out triangles using line integrals x = xy(:,1); y = xy(:,2); u = uv(:,1); v = uv(:,2); p = size(tri,1); xx = reshape(x(tri),p,3)'; yy = reshape(y(tri),p,3)'; xysum = sum( (xx([2 3 1],:) - xx).* (yy([2 3 1],:) + yy), 1 ); uu = reshape(u(tri),p,3)'; vv = reshape(v(tri),p,3)'; uvsum = sum( (uu([2 3 1],:) - uu).* (vv([2 3 1],:) + vv), 1 ); index = find(xysum.*uvsum<0); end function vertex = FindBadVertex(x,y,vertices) % Get middle vertex of triangle where "middle" means the largest angle, % which will have the smallest cosine. vx = x(vertices)'; vy = y(vertices)'; abc = [ vx - vx([3 1 2]); vy - vy([3 1 2]) ]; a = abc(:,1); b = abc(:,2); c = abc(:,3); % find cosine of angle between 2 vectors vcos(1) = get_cos(-a, b); vcos(2) = get_cos(-b, c); vcos(3) = get_cos( a,-c); [~, index] = min(vcos); vertex = vertices(index); end %------------------------------- % Function get_cos % function vcos = get_cos(a,b) mag_a = hypot(a(1),a(2)); mag_b = hypot(b(1),b(2)); vcos = dot(a,b) / (mag_a*mag_b); end
github
wangsuyuan/Imageprocesingtoobox-master
iradon.m
.m
Imageprocesingtoobox-master/@gpuArray/iradon.m
12,101
utf_8
8bb1ec9847c30edc4795f7a6f6060c30
function [img,H] = iradon(varargin) %IRADON Inverse Radon transform. % I = iradon(R,THETA) reconstructs the image I from projection data in % the 2-D gpuArray R. The columns of R are parallel beam projection % data. IRADON assumes that the center of rotation is the center point of % the projections, which is defined as ceil(size(R,1)/2). % % THETA describes the angles (in degrees) at which the projections were % taken. It can be either a vector (or gpuArray vector) containing the % angles or a scalar specifying D_theta, the incremental angle between % projections. If THETA is a vector, it must contain angles with equal % spacing between them. If THETA is a scalar specifying D_theta, the % projections are taken at angles THETA = m * D_theta; m = % 0,1,2,...,size(R,2)-1. If the input is the empty matrix ([]), D_theta % defaults to 180/size(R,2). % % IRADON uses the filtered backprojection algorithm to perform the inverse % Radon transform. The filter is designed directly in the frequency % domain and then multiplied by the FFT of the projections. The % projections are zero-padded to a power of 2 before filtering to prevent % spatial domain aliasing and to speed up the FFT. % % I = IRADON(R,THETA,INTERPOLATION,FILTER,FREQUENCY_SCALING,OUTPUT_SIZE) % specifies parameters to use in the inverse Radon transform. You can % specify any combination of the last four arguments. IRADON uses default % values for any of these arguments that you omit. % % INTERPOLATION specifies the type of interpolation to use in the % backprojection. The default is linear interpolation. Available methods % are: % % 'nearest' - nearest neighbor interpolation % 'linear' - linear interpolation (default) % % FILTER specifies the filter to use for frequency domain filtering. % FILTER is a string that specifies any of the following standard filters: % % 'Ram-Lak' The cropped Ram-Lak or ramp filter (default). The % frequency response of this filter is |f|. Because this % filter is sensitive to noise in the projections, one of % the filters listed below may be preferable. % 'Shepp-Logan' The Shepp-Logan filter multiplies the Ram-Lak filter by % a sinc function. % 'Cosine' The cosine filter multiplies the Ram-Lak filter by a % cosine function. % 'Hamming' The Hamming filter multiplies the Ram-Lak filter by a % Hamming window. % 'Hann' The Hann filter multiplies the Ram-Lak filter by a % Hann window. % 'none' No filtering is performed. % % FREQUENCY_SCALING is a scalar in the range (0,1] that modifies the % filter by rescaling its frequency axis. The default is 1. If % FREQUENCY_SCALING is less than 1, the filter is compressed to fit into % the frequency range [0,FREQUENCY_SCALING], in normalized frequencies; % all frequencies above FREQUENCY_SCALING are set to 0. % % OUTPUT_SIZE is a scalar that specifies the number of rows and columns in % the reconstructed image. If OUTPUT_SIZE is not specified, the size is % determined from the length of the projections: % % OUTPUT_SIZE = 2*floor(size(R,1)/(2*sqrt(2))) % % If you specify OUTPUT_SIZE, IRADON reconstructs a smaller or larger % portion of the image, but does not change the scaling of the data. % % If the projections were calculated with the RADON function, the % reconstructed image may not be the same size as the original image. % % [I,H] = iradon(...) returns the frequency response of the filter in the % vector H. % % Class Support % ------------- % R can be a gpuArray of underlying class double or single. All other % numeric input arguments must be double or gpuArray of underlying class % double. I has the same class as R. H is a gpuArray of underlying class % double. % % Notes % ----- % The GPU implementation of this function supports only nearest neighbor % and linear interpolation methods for the backprojection. % % Examples % -------- % Compare filtered and unfiltered backprojection. % % P = gpuArray(phantom(128)); % R = radon(P,0:179); % I1 = iradon(R,0:179); % I2 = iradon(R,0:179,'linear','none'); % subplot(1,3,1), imshow(P), title('Original') % subplot(1,3,2), imshow(I1), title('Filtered backprojection') % subplot(1,3,3), imshow(I2,[]), title('Unfiltered backprojection') % % Compute the backprojection of a single projection vector. The IRADON % syntax does not allow you to do this directly, because if THETA is a % scalar it is treated as an increment. You can accomplish the task by % passing in two copies of the projection vector and then dividing the % result by 2. % % P = gpuArray(phantom(128)); % R = radon(P,0:179); % r45 = R(:,46); % I = iradon([r45 r45], [45 45])/2; % imshow(I, []) % title('Backprojection from the 45-degree projection') % % See also FAN2PARA, FANBEAM, IFANBEAM, PARA2FAN, PHANTOM, % GPUARRAY/RADON,GPUARRAY. % Copyright 2013 The MathWorks, Inc. % References: % A. C. Kak, Malcolm Slaney, "Principles of Computerized Tomographic % Imaging", IEEE Press 1988. narginchk(2,6); %Dispatch to CPU if needed. if ~isa(varargin{1},'gpuArray') varargin = gatherIfNecessary(varargin{:}); [img,H] = iradon(varargin{:}); return; end [p,theta,filter,d,interp,N] = parse_inputs(varargin{:}); [p,H] = filterProjections(p, filter, d); % Zero pad the projections to size 1+2*ceil(N/sqrt(2)) if this % quantity is greater than the length of the projections imgDiag = 2*ceil(N/sqrt(2))+1; % largest distance through image. if size(p,1) < imgDiag rz = imgDiag - size(p,1); % how many rows of zeros top = gpuArray.zeros(ceil(rz/2),size(p,2)); bot = gpuArray.zeros(floor(rz/2),size(p,2)); p = [top; p; bot]; end % Backprojection switch interp case 'nearest neighbor' img = iradongpumex(N, theta, p, false); case 'linear' img = iradongpumex(N, theta, p, true); end %====================================================================== function [p,H] = filterProjections(p, filter, d) % Design the filter len = size(p,1); H = designFilter(filter, len, d); if strcmpi(filter, 'none') return; end % faster to put padding directly into FFT below % p(length(H),1)=0; % Zero pad projections % In the code below, I continuously reuse the array p so as to % save memory. This makes it harder to read, but the comments % explain what is going on. p = fft(p,length(H)); % p holds fft of projections % for i = 1:size(p,2) % p(:,i) = p(:,i).*H; % frequency domain filtering % end p = bsxfun(@times, p, H); % faster than for-loop p = ifft(p,'symmetric'); % p = p(1:len,:) % MCOS overload issue so directly form subsref p = subsref(p,substruct('()', {1:len ':'})); %---------------------------------------------------------------------- %====================================================================== function filt = designFilter(filter, len, d) % Returns the Fourier Transform of the filter which will be % used to filter the projections % % INPUT ARGS: filter - either the string specifying the filter % len - the length of the projections % d - the fraction of frequencies below the nyquist % which we want to pass % % OUTPUT ARGS: filt - the filter to use on the projections order = max(64,2^nextpow2(2*len)); if strcmpi(filter, 'none') filt = ones(1, order); return; end % First create a bandlimited ramp filter (Eqn. 61 Chapter 3, Kak and % Slaney) - go up to the next highest power of 2. n = 0:(order/2); % 'order' is always even. filtImpResp = zeros(1,(order/2)+1); % 'filtImpResp' is the bandlimited ramp's impulse response (values for even n are 0) filtImpResp(1) = 1/4; % Set the DC term filtImpResp(2:2:end) = -1./((pi*n(2:2:end)).^2); % Set the values for odd n filtImpResp = [filtImpResp filtImpResp(end-1:-1:2)]; filt = 2*real(fft(filtImpResp)); filt = filt(1:(order/2)+1); w = 2*pi*(0:size(filt,2)-1)/order; % frequency axis up to Nyquist switch filter case 'ram-lak' % Do nothing case 'shepp-logan' % be careful not to divide by 0: filt(2:end) = filt(2:end) .* (sin(w(2:end)/(2*d))./(w(2:end)/(2*d))); case 'cosine' filt(2:end) = filt(2:end) .* cos(w(2:end)/(2*d)); case 'hamming' filt(2:end) = filt(2:end) .* (.54 + .46 * cos(w(2:end)/d)); case 'hann' filt(2:end) = filt(2:end) .*(1+cos(w(2:end)./d)) / 2; otherwise error(message('images:iradon:invalidFilter')) end filt(w>pi*d) = 0; % Crop the frequency response filt = [filt' ; filt(end-1:-1:2)']; % Symmetry of the filter %---------------------------------------------------------------------- %====================================================================== function [p,theta,filter,d,interp,N] = parse_inputs(varargin) % Parse the input arguments and retun things % % Inputs: varargin - Cell array containing all of the actual inputs % % Outputs: p - Projection data % theta - the angles at which the projections were taken % filter - string specifying filter or the actual filter % d - a scalar specifying normalized freq. at which to crop % the frequency response of the filter % interp - the type of interpolation to use % N - The size of the reconstructed image p = varargin{1}; theta = gather(varargin{2}); hValidateAttributes(p,{'single','double'},{'real','2d'},... mfilename,'R',1); validateattributes (theta,{'double'},{'real','nonsparse'},... mfilename,'theta',2); % Convert to radians theta = pi*theta/180; % Default values N = 0; % Size of the reconstructed image d = 1; % Defaults to no cropping of filters frequency response filter = 'ram-lak'; % The ramp filter is the default interp = 'linear'; % default interpolation is linear interp_strings = {'nearest neighbor', 'linear'}; filter_strings = {'ram-lak','shepp-logan','cosine','hamming', 'hann', 'none'}; string_args = [interp_strings filter_strings]; for i=3:nargin arg = gather(varargin{i}); if ischar(arg) str = validatestring(arg,string_args,mfilename,'interpolation or filter'); idx = find(strcmp(str,string_args),1,'first'); if idx <= numel(interp_strings) % interpolation method interp = string_args{idx}; else %if (idx > numel(interp_strings)) && (idx <= numel(string_args)) % filter type filter = string_args{idx}; end elseif numel(arg)==1 if arg <=1 % frequency scale validateattributes(arg,{'numeric','logical'},... {'positive','real','nonsparse'},... mfilename,'frequency_scaling'); d = arg; else % output size validateattributes(arg,{'numeric'},... {'real','finite','nonsparse','integer'},... mfilename,'output_size'); N = arg; end else error(message('images:iradon:invalidInputParameters')) end end % If the user didn't specify the size of the reconstruction, so % deduce it from the length of projections if N==0 N = 2*floor( size(p,1)/(2*sqrt(2)) ); % This doesn't always jive with RADON end % for empty theta, choose an intelligent default delta-theta if isempty(theta) theta = pi / size(p,2); % TODO convert to degrees end % If the user passed in delta-theta, build the vector of theta values if numel(theta)==1 theta = (0:(size(p,2)-1))* theta; % TODO radian conversion end if length(theta) ~= size(p,2) error(message('images:iradon:thetaNotMatchingProjectionNumber')) end %----------------------------------------------------------------------
github
wangsuyuan/Imageprocesingtoobox-master
corr2.m
.m
Imageprocesingtoobox-master/@gpuArray/corr2.m
2,249
utf_8
697b0fa98d14ca82f9891dd9fee48123
function r = corr2(varargin) %CORR2 2-D correlation coefficient. % R = CORR2(A,B) computes the correlation coefficient between A % and B, where A and B are 2-D gpuArrays of the same size. % % Class Support % ------------- % A and B must be real, 2-D gpuArrays. If either one of A or B is not a % gpuArray, it must be numeric or logical and non-sparse. Any data not % already on the GPU is moved to GPU memory. R is a scalar double % gpuArray. % % Example % ------- % I = gpuArray(imread('pout.tif')); % J = stdfilt(I); % R = corr2(I,J) % % See also CORRCOEF, GPUARRAY/STD2, GPUARRAY. % Copyright 2013 The MathWorks, Inc. [a,b] = ParseInputs(varargin{:}); ma = sum(sum(a,'double')); mb = sum(sum(b,'double')); np = numel(a); [ab,aa,bb] = arrayfun(@findDotProducts,a,b); r = sum(sum(ab))/sqrt(sum(sum(aa))*sum(sum(bb))); function [ab_ij,aa_ij,bb_ij] = findDotProducts(a_ij,b_ij) %Nested function to compute (a-mean2(a)).*(b-mean2(b)), %(a-mean2(a))^2 and (b-mean2l(b))^2 element-wise. a_ij = double(a_ij) - ma/np; b_ij = double(b_ij) - mb/np; ab_ij = a_ij*b_ij; aa_ij = a_ij*a_ij; bb_ij = b_ij*b_ij; end end %-------------------------------------------------------- function [A,B] = ParseInputs(varargin) narginchk(2,2); A = varargin{1}; B = varargin{2}; if isa(A,'gpuArray') hValidateAttributes(A,... {'logical','uint8','int8','uint16','int16','uint32','int32','single','double'},... {'real','2d'},mfilename,'A',1); else % GPU implementation does not support sparse matrices. validateattributes(A, {'logical' 'numeric'},... {'real','2d','nonsparse'}, mfilename, 'A', 1); end if isa(B,'gpuArray') hValidateAttributes(B,... {'logical','uint8','int8','uint16','int16','uint32','int32','single','double'},... {'real','2d'},mfilename,'B',2); else % GPU implementation does not support sparse matrices. validateattributes(B, {'logical' 'numeric'},... {'real','2d','nonsparse'}, mfilename, 'B', 2); end if any(size(A)~=size(B)) error(message('images:corr2:notSameSize')) end end
github
wangsuyuan/Imageprocesingtoobox-master
padarray.m
.m
Imageprocesingtoobox-master/@gpuArray/padarray.m
3,889
utf_8
81f12ae408cd7788076ab6e2de0efe89
function b = padarray(varargin) %PADARRAY Pad array. % B = PADARRAY(A,PADSIZE) pads gpuArray A with PADSIZE(k) number of zeros % along the k-th dimension of A. PADSIZE should be a vector of % nonnegative integers. % % B = PADARRAY(A,PADSIZE,PADVAL) pads gpuArray A with PADVAL (a scalar) % instead of with zeros. % % B = PADARRAY(A,PADSIZE,PADVAL,DIRECTION) pads gpuArray A in the % direction specified by the string DIRECTION. DIRECTION can be one of % the following strings. % % String values for DIRECTION % 'pre' Pads before the first array element along each % dimension . % 'post' Pads after the last array element along each % dimension. % 'both' Pads before the first array element and after the % last array element along each dimension. % % By default, DIRECTION is 'both'. % % B = PADARRAY(A,PADSIZE,METHOD,DIRECTION) pads gpuArray A using the % specified METHOD. METHOD can be one of these strings: % % String values for METHOD % 'circular' Pads with circular repetition of elements. % 'replicate' Repeats border elements of A. % 'symmetric' Pads array with mirror reflections of itself. % % Class Support % ------------- % When padding with a constant value, A can be numeric or logical. % When padding using the 'circular', 'replicate', or 'symmetric' % methods, A can be of any class. B is of the same class as A. % % Example % ------- % Add three elements of padding to the beginning of a vector. The % padding elements contain mirror copies of the array. % % b = padarray([1 2 3 4],3,'symmetric','pre') % % Add three elements of padding to the end of the first dimension of % the array and two elements of padding to the end of the second % dimension. Use the value of the last array element as the padding % value. % % B = padarray([1 2; 3 4],[3 2],'replicate','post') % % Add three elements of padding to each dimension of a % three-dimensional array. Each pad element contains the value 0. % % A = [1 2; 3 4]; % B = [5 6; 7 8]; % C = cat(3,A,B) % D = padarray(C,[3 3],0,'both') % % See also CIRCSHIFT, GPUARRAY/IMFILTER, GPUARRAY. % Copyright 1993-2013 The MathWorks, Inc. [a, method, padSize, padVal, direction] = ParseInputs(varargin{:}); b = padarray_algo(a, padSize, method, padVal, direction); %%% %%% ParseInputs %%% function [a, method, padSize, padVal, direction] = ParseInputs(varargin) narginchk(2,4); % fixed syntax args a = varargin{1}; padSize = varargin{2}; % default values method = 'constant'; padVal = 0; direction = 'both'; validateattributes(padSize, {'double'}, {'real' 'vector' 'nonnan' 'nonnegative' ... 'integer'}, mfilename, 'PADSIZE', 2); % Preprocess the padding size if (numel(padSize) < ndims(a)) padSize = padSize(:); padSize(ndims(a)) = 0; end if nargin > 2 firstStringToProcess = 3; if ~ischar(varargin{3}) % Third input must be pad value. padVal = varargin{3}; validateattributes(padVal, {'numeric' 'logical'}, {'scalar'}, ... mfilename, 'PADVAL', 3); firstStringToProcess = 4; end for k = firstStringToProcess:nargin validStrings = {'circular' 'replicate' 'symmetric' 'pre' ... 'post' 'both'}; string = validatestring(varargin{k}, validStrings, mfilename, ... 'METHOD or DIRECTION', k); switch string case {'circular' 'replicate' 'symmetric'} method = string; case {'pre' 'post' 'both'} direction = string; otherwise error(message('images:padarray:unexpectedError')) end end end
github
wangsuyuan/Imageprocesingtoobox-master
rgb2gray.m
.m
Imageprocesingtoobox-master/@gpuArray/rgb2gray.m
2,907
utf_8
2bb015f8740348907dd5af4650c9ca6c
function I = rgb2gray(X) %RGB2GRAY Convert RGB gpuArray image or colormap to grayscale. % RGB2GRAY converts RGB gpuArray images to grayscale by eliminating the % hue and saturation information while retaining the % luminance. % % I = RGB2GRAY(RGB) converts the truecolor gpuArray image RGB to the % grayscale intensity image I. % % NEWMAP = RGB2GRAY(MAP) returns a grayscale colormap % equivalent to MAP. % % Class Support % ------------- % If the input is an RGB gpuArray image, it can be uint8, uint16, double, % or single. The output gpuArray image I has the same class as the input % image. If the input is a colormap, the input and output colormaps are % both of class double. % % Example % ------- % I = gpuArray(imread('board.tif')); % J = rgb2gray(I); % figure, imshow(I), figure, imshow(J); % % [X,map] = gpuArray(imread('trees.tif')); % gmap = rgb2gray(map); % figure, imshow(X,map), figure, imshow(X,gmap); % % See also IND2GRAY, NTSC2RGB, RGB2IND, RGB2NTSC, GPUARRAY/MAT2GRAY, % GPUARRAY. % Copyright 2013 The MathWorks, Inc. X = parse_inputs(X); origSize = size(X); % Determine if input includes a 3-D array threeD = (ndims(X)==3); % Calculate transformation matrix T = inv([1.0 0.956 0.621; 1.0 -0.272 -0.647; 1.0 -1.106 1.703]); coef = T(1,:); if threeD % RGB if(isfloat(X)) % Shape input matrix so that it is a n x 3 array X = reshape(X,origSize(1)*origSize(2),3); sizeOutput = [origSize(1), origSize(2)]; I = X * coef'; I = min(max(I,0),1); %Make sure that the output matrix has the right size I = reshape(I,sizeOutput); else %I = X(:,:,1)*coef(1) + X(:,:,2)*coef(2) + X(:,:,3)*coef(3); s1.type = '()' ; s2.type ='()'; s3.type ='()'; s1.subs = {':',':',1}; s2.subs = {':',':',2}; s3.subs = {':',':',3}; I = arrayfun(@multiplyCoef,subsref(X,s1), subsref(X,s2), subsref(X,s3)); I = cast(I, classUnderlying(X)); end else % MAP I = X * coef'; I = min(max(I,0),1); I = [I,I,I]; end %---------------------------------- function eOut = multiplyCoef(r,g,b) eOut = double(r)*coef(1) + double(g)*coef(2) + double(b)*coef(3); end end %%% %Parse Inputs %%% function X = parse_inputs(X) if ismatrix(X) % colormap if (size(X,2) ~=3 || size(X,1) < 1) error(message('images:rgb2gray:invalidSizeForColormap')) end if ~strcmp(classUnderlying(X),'double') error(message('images:rgb2gray:notAValidColormap')) end elseif (ndims(X)==3) % rgb if ((size(X,3) ~= 3)) error(message('images:rgb2gray:invalidInputSizeRGB')) end else error(message('images:rgb2gray:invalidInputSize')) end %no logical arrays if islogical(X) error(message('images:rgb2gray:invalidType')) end end
github
wangsuyuan/Imageprocesingtoobox-master
imgradientxy.m
.m
Imageprocesingtoobox-master/@gpuArray/imgradientxy.m
7,437
utf_8
1879c6d1684e8f81b5079775dcb44db8
function [Gx, Gy] = imgradientxy(varargin) %IMGRADIENTXY Find the directional gradients of an image. % [Gx, Gy] = IMGRADIENTXY(I) takes a grayscale or binary gpuArray image I % as input and returns the gradient along the X axis, Gx, and the Y axis, % Gy. X axis points in the direction of increasing column subscripts and % Y axis points in the direction of increasing row subscripts. Gx and Gy % are the same size as the input gpuArray image I. % % [Gx, Gy] = IMGRADIENTXY(I, METHOD) calculates the directional gradients % of the gpuArray image I using the specified METHOD. % % Supported METHODs are: % % 'Sobel' : Sobel gradient operator (default) % % 'Prewitt' : Prewitt gradient operator % % 'CentralDifference' : Central difference gradient dI/dx = (I(x+1)- I(x-1))/ 2 % % 'IntermediateDifference': Intermediate difference gradient dI/dx = I(x+1) - I(x) % % Class Support % ------------- % The input gpuArray image I can be numeric or logical two-dimensional % matrix. Both Gx and Gy are of class double, unless the input gpuArray % image I is of class single, in which case Gx and Gy will be of class % single. % % Notes % ----- % 1. When applying the gradient operator at the boundaries of the image, % values outside the bounds of the image are assumed to equal the % nearest image border value. This is similar to the 'replicate' % boundary option in IMFILTER. % % Example 1 % --------- % This example computes and displays the directional gradients of the % image coins.png using Prewitt's gradient operator. % % I = gpuArray(imread('coins.png')); % imshow(I) % % [Gx, Gy] = imgradientxy(I,'prewitt'); % % figure, imshow(Gx, []), title('Directional gradient: X axis') % figure, imshow(Gy, []), title('Directional gradient: Y axis') % % Example 2 % --------- % This example computes and displays both the directional gradients and the % gradient magnitude and gradient direction for the image coins.png. % % I = gpuArray(imread('coins.png')); % imshow(I) % % [Gx, Gy] = imgradientxy(I); % [Gmag, Gdir] = imgradient(Gx, Gy); % % figure, imshow(Gmag, []), title('Gradient magnitude') % figure, imshow(Gdir, []), title('Gradient direction') % figure, imshow(Gx, []), title('Directional gradient: X axis') % figure, imshow(Gy, []), title('Directional gradient: Y axis') % % See also GPUARRAY/EDGE, FSPECIAL, GPUARRAY/IMGRADIENT, GPUARRAY. % Copyright 2013 The MathWorks, Inc. narginchk(1,2); [I, method] = parse_inputs(varargin{:}); if ~isfloat(I) I = double(I); end switch method case 'sobel' h = -fspecial('sobel'); % Align mask correctly along the x- and y- axes Gx = imfilter(I,h','replicate'); if nargout > 1 Gy = imfilter(I,h,'replicate'); end case 'prewitt' h = -fspecial('prewitt'); % Align mask correctly along the x- and y- axes Gx = imfilter(I,h','replicate'); if nargout > 1 Gy = imfilter(I,h,'replicate'); end case 'centraldifference' if isrow(I) Gx = gradient2(I); if nargout > 1 Gy = gpuArray.zeros(size(I),classUnderlying(I)); end elseif iscolumn(I) Gx = gpuArray.zeros(size(I),classUnderlying(I)); if nargout > 1 Gy = gradient2(I); end else [Gx, Gy] = gradient2(I); end case 'intermediatedifference' Gx = gpuArray.zeros(size(I),classUnderlying(I)); if (size(I,2) > 1) subsRight(1).type = '()'; subsRight(1).subs = {':',2:size(I,2)}; subsLeft(1).type = '()'; subsLeft(1).subs = {':',1:size(I,2)-1}; subsGx(1).type = '()'; subsGx(1).subs = {':',1:size(Gx,2)-1}; Gx = subsasgn(Gx,... subsGx,... subsref(I,subsRight) - subsref(I,subsLeft)); end if nargout > 1 Gy = gpuArray.zeros(size(I),classUnderlying(I)); if (size(I,1) > 1) subsLower(1).type = '()'; subsLower(1).subs = {2:size(I,1),':'}; subsUpper(1).type = '()'; subsUpper(1).subs = {1:size(I,1)-1,':'}; subsGy(1).type = '()'; subsGy(1).subs = {1:size(I,1)-1,':'}; Gy = subsasgn(Gy,... subsGy,... subsref(I,subsLower) - subsref(I,subsUpper)); end end end end %====================================================================== function [I, method] = parse_inputs(varargin) I = varargin{1}; hValidateAttributes(I,... {'logical','uint8','int8','uint16','int16','uint32','int32','single','double'}, ... {'2d','real'},mfilename,'I',1); method = 'sobel'; % Default method if (nargin > 1) methodstrings = {'sobel','prewitt','centraldifference', ... 'intermediatedifference'}; method = validatestring(varargin{2}, methodstrings, ... mfilename, 'Method', 2); end end %---------------------------------------------------------------------- %====================================================================== function varargout = gradient2(in_0) %Approximate 2d gradient. narginchk(1,1); nargoutchk(1,2); if iscolumn(in_0) in = in_0'; else in = in_0; end [m,n] = size(in); out = gpuArray.zeros([m,n],classUnderlying(in)); % Take forward differences on left and right edges if n > 1 %out(:,1) = in(:,2)-in(:,1); out = subsasgn(out,substruct('()',{':',1}),... subsref(in,substruct('()',{':',2}))-subsref(in,substruct('()',{':',1}))); %out(:,n) = in(:,n) - in(:,n-1); out = subsasgn(out,substruct('()',{':',n}),... subsref(in,substruct('()',{':',n}))-subsref(in,substruct('()',{':',n-1}))); end % Take centered differences on interior points if n > 2 %out(:,2:n-1) = ( in(:,3:n)-in(:,1:n-2) )./2; out = subsasgn(out,substruct('()',{':',2:n-1}),... ( subsref(in,substruct('()',{':',3:n}))-subsref(in,substruct('()',{':',1:n-2})) )./2); end if iscolumn(in_0) varargout{1} = out'; else varargout{1} = out; end if nargout == 2 out2 = gpuArray.zeros([m,n],classUnderlying(in)); % Take forward differences on top and bottom edges if m > 1 %out2(1,:) = in(2,:)-in(1,:); out2 = subsasgn(out2,substruct('()',{1,':'}),... subsref(in,substruct('()',{2,':'}))-subsref(in,substruct('()',{1,':'}))); %out2(m,:) = in(m,:)-in(m-1,:); out2 = subsasgn(out2,substruct('()',{m,':'}),... subsref(in,substruct('()',{m,':'}))-subsref(in,substruct('()',{m-1,':'}))); end % Take centered differences on interior points if m > 2 %out2(2:m-1,:) = ( in(3:m,:)-in(1:m-2,:) )./2; out2 = subsasgn(out2,substruct('()',{2:m-1,':'}),... ( subsref(in,substruct('()',{3:m,':'}))-subsref(in,substruct('()',{1:m-2,':'})) )./2); end varargout{2} = out2; end end %----------------------------------------------------------------------
github
wangsuyuan/Imageprocesingtoobox-master
imrotate.m
.m
Imageprocesingtoobox-master/@gpuArray/imrotate.m
8,201
utf_8
aa5b7a3a9d5251ee694943abefe820f7
function varargout = imrotate(varargin) %IMROTATE Rotate image. % B = IMROTATE(A, ANGLE) rotates the image in gpuArray A by ANGLE degrees % in a counterclockwise direction around its center point. To rotate the % image clockwise, specify a negative value for ANGLE. IMROTATE makes the % output gpuArray B large enough to contain the entire rotated image. % IMROTATE uses nearest neighbor interpolation, setting the values of % pixels in B that are outside the rotated image to 0 (zero). % % B = IMROTATE(A,ANGLE,METHOD) rotates the image in gpuArray A, using the % interpolation method specified by METHOD. METHOD is a string that can % have one of the following values. The default value is enclosed in % braces ({}). % % {'nearest'} Nearest neighbor interpolation % % 'bilinear' Bilinear interpolation % % 'bicubic' Bicubic interpolation. Note: This interpolation % method can produce pixel values outside the original % range. % % B = IMROTATE(A,ANGLE,METHOD,BBOX) rotates image in gpuArray A, where % BBOX specifies the size of the output gpuArray B. BBOX is a text string % that can have either of the following values. The default value is % enclosed in braces % ({}). % % {'loose'} Make output gpuArray B large enough to contain the % entire rotated image. B is generally larger than A. % % 'crop' Make output gpuArray B the same size as the input % gpuArray A, cropping the rotated image to fit. % % Class Support % ------------- % The input gpuArray image can contain uint8, uint16, single-precision % floating-point, or logical pixels. The output image is of the same % class as the input image. % % Note % ---- % The 'bicubic' interpolation mode used in the GPU implementation of this % function differs from the default (CPU) bicubic mode. The GPU and CPU % versions of this function are expected to give slightly different % results. % % Example % ------- % X = gpuArray(imread('pout.tif')); % Y = imrotate(X, 37, 'loose', 'bilinear'); % figure; imshow(Y) % % See also IMCROP, GPUARRAY/IMRESIZE, IMTRANSFORM, TFORMARRAY, GPUARRAY. % Copyright 2012-2013 The MathWorks, Inc. [A,angle,method,bbox] = parse_inputs(varargin{:}); if (isempty(A)) B = A; % No rotation needed else so = size(A); twod_size = so(1:2); thirdD = prod(so(3:end)); r = rem(angle, 360); switch (r) case {0} B = A; case {90, 270} A = reshape(A,[twod_size thirdD]); not_square = twod_size(1) ~= twod_size(2); multiple_of_ninety = mod(floor(angle/90), 4); if strcmpi(bbox, 'crop') && not_square % center rotated image and preserve size if ndims(A)>2 %#ok<ISMAT> dim = 3; else dim = ndims(A); end v = repmat({':'},[1 dim]); imbegin = (max(twod_size) == so)*abs(diff(floor(twod_size/2))); vec = 1:min(twod_size); v(1) = {imbegin(1)+vec}; v(2) = {imbegin(2)+vec}; new_size = [twod_size thirdD]; % pre-allocate array if islogical(A) B = gpuArray.false(new_size); else B = gpuArray.zeros(new_size,classUnderlying(A)); end s.type = '()'; s.subs = v; for k = 1:thirdD s.subs{3} = k; % B(:,:,k) = rot90(A(:,:,k),multiple_of_ninety); B = subsasgn(B, s, rot90(subsref(A, s), multiple_of_ninety)); end else % don't preserve original size new_size = [fliplr(twod_size) thirdD]; B = pagefun(@rot90,A,multiple_of_ninety); end B = reshape(B,[new_size(1) new_size(2) so(3:end)]); case {180} v = repmat({':'},[1 ndims(A)]); v(1) = {twod_size(1):-1:1}; v(2) = {twod_size(2):-1:1}; s.type = '()'; s.subs = v; B = subsref(A, s); otherwise padSize = [2 2]; if (~ismatrix(A)) padSize(ndims(A)) = 0; end %pad input gpuArray to overcome different edge behavior in NPP. A = padarray_algo(A, padSize, 'constant', 0, 'both'); [~,~,~,~,outputSize] = getOutputBound(angle,twod_size,bbox); if (isreal(A)) B = imrotategpumex(A, angle, method, outputSize); else B = complex(imrotategpumex(real(A), angle, method, outputSize),... imrotategpumex(imag(A), angle, method, outputSize)); end end end varargout{1} = B; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % function to parse inputs %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [A,ang,method,bbox] = parse_inputs(varargin) % Outputs: A the input gpuArray % ang the angle by which to rotate the input image % method interpolation method (nearest,bilinear,bicubic) % bbox bounding box option 'loose' or 'crop' % Defaults: method = 'n'; bbox = 'l'; narginchk(2,4) switch nargin case 2, % imrotate(A,ang) A = varargin{1}; ang=varargin{2}; case 3, % imrotate(A,ang,method) or A = varargin{1}; % imrotate(A,ang,box) ang=varargin{2}; method=varargin{3}; case 4, % imrotate(A,ang,method,box) A = varargin{1}; ang=varargin{2}; method=varargin{3}; bbox=varargin{4}; otherwise, error(message('images:imrotate:invalidInputs')) end % Check validity of the input parameters if ischar(method) && ischar(bbox), strings = {'nearest','bilinear','bicubic','crop','loose'}; idx = strmatch(lower(method),strings); if isempty(idx), error(message('images:imrotate:unrecognizedInterpolationMethod', method)) elseif length(idx)>1, error(message('images:imrotate:ambiguousInterpolationMethod', method)) else if idx==4,bbox=strings{4};method=strings{1}; elseif idx==5,bbox = strings{5};method=strings{1}; else method = strings{idx}; end end idx = strmatch(lower(bbox),strings(4:5)); if isempty(idx), error(message('images:imrotate:unrecognizedBBox', bbox)) elseif length(idx)>1, error(message('images:imrotate:ambiguousBBox', bbox)) else bbox = strings{3+idx}; end else error(message('images:imrotate:expectedString')) end hValidateAttributes(A,... {'uint8','uint16','logical','single'},{},mfilename,'input image',1); % Ang must always be double. ang = double(ang); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Function: getOutputBound % function [loA,hiA,loB,hiB,outputSize] = getOutputBound(angle,twod_size,bbox) % Coordinates from center of A hiA = (twod_size-1)/2; loA = -hiA; if strcmpi(bbox, 'loose') % Determine limits for rotated image % Compute bounding box of roated image phi = angle*pi/180; % Convert to radians sinPhi = sin(phi); cosPhi = cos(phi); T = [ cosPhi sinPhi 0 -sinPhi cosPhi 0 0 0 1 ]; rotate = affine2d(T); [x,y] = rotate.outputLimits([loA(1) hiA(1)], [hiA(2) hiA(2)]); hiB = ceil(max(abs([x' y']))/2)*2; loB = -hiB; outputSize = hiB - loB + 1; else % Cropped image hiB = hiA; loB = loA; outputSize = twod_size; end
github
wangsuyuan/Imageprocesingtoobox-master
imnoise.m
.m
Imageprocesingtoobox-master/@gpuArray/imnoise.m
11,566
utf_8
5c907a664971c69a29354a8539437f37
function b = imnoise(varargin) %IMNOISE Add noise to gpuArray image. % J = IMNOISE(I,TYPE,...) Add noise of a given TYPE to the gpuArray % intensity image I. TYPE is a string that can have one of these values: % % 'gaussian' Gaussian white noise with constant % mean and variance % % 'localvar' Zero-mean Gaussian white noise % with an intensity-dependent variance % % 'poisson' Poisson noise % % 'salt & pepper' "On and Off" pixels % % 'speckle' Multiplicative noise % % Depending on TYPE, you can specify additional parameters to IMNOISE. % All numerical parameters are normalized; they correspond to operations % with images with intensities ranging from 0 to 1. % % J = IMNOISE(I,'gaussian',M,V) adds Gaussian white noise of mean M and % variance V to the gpuArray image I. When unspecified, M and V default % to 0 and 0.01 respectively. % % J = imnoise(I,'localvar',V) adds zero-mean, Gaussian white noise of % local variance, V, to the gpuArray image I. V is an array of the same % size as I. % % J = imnoise(I,'localvar',IMAGE_INTENSITY,VAR) adds zero-mean, Gaussian % noise to a gpuArray image, I, where the local variance of the noise is % a function of the image intensity values in I. IMAGE_INTENSITY and VAR % are vectors of the same size, and PLOT(IMAGE_INTENSITY,VAR) plots the % functional relationship between noise variance and image intensity. % IMAGE_INTENSITY must contain normalized intensity values ranging from 0 % to 1. % % J = IMNOISE(I,'poisson') generates Poisson noise from the data instead % of adding artificial noise to the data. If I is double precision, % then input pixel values are interpreted as means of Poisson % distributions scaled up by 1e12. For example, if an input pixel has % the value 5.5e-12, then the corresponding output pixel will be % generated from a Poisson distribution with mean of 5.5 and then scaled % back down by 1e12. If I is single precision, the scale factor used is % 1e6. If I is uint8 or uint16, then input pixel values are used % directly without scaling. For example, if a pixel in a uint8 input % has the value 10, then the corresponding output pixel will be % generated from a Poisson distribution with mean 10. % % J = IMNOISE(I,'salt & pepper',D) adds "salt and pepper" noise to the % gpuArray image I, where D is the noise density. This affects % approximately D*numel(I) pixels. The default for D is 0.05. % % J = IMNOISE(I,'speckle',V) adds multiplicative noise to the gpuArray % image I, using the equation J = I + n*I, where n is uniformly % distributed random noise with mean 0 and variance V. The default for V % is 0.04. % % Note % ---- % The mean and variance parameters for 'gaussian', 'localvar', and % 'speckle' noise types are always specified as if for a double gpuArray % image in the range [0, 1]. If the input image is of class uint8 or % uint16, the imnoise function converts the gpuArray image to double, % adds noise according to the specified type and parameters, and then % converts the noisy gpuArray image back to the same class as the input. % % Class Support % ------------- % For most noise types, input gpuArray I can have underlying class be % uint8, uint16, double, int16, or single. For Poisson noise, int16 is % not allowed. The output gpuArray image J has the same class as I. If I % has more than two dimensions it is treated as a multidimensional % intensity image and not as an RGB gpuArray image. % % Example % ------- % I = gpuArray(imread('eight.tif')); % J = imnoise(I,'salt & pepper', 0.02); % figure, imshow(I), figure, imshow(J) % % See also GPUARRAY/RAND, GPUARRAY/RANDN, GPUARRAY. % Copyright 2013 The MathWorks, Inc. % Check the input-array type. if(~isa(varargin{1},'gpuArray')) % CPU code path if the first input is not a gpuArray b = imnoise(gatherIfNecessary(varargin)); return; end [a, code, classIn, classChanged, p3, p4] = ParseInputs(varargin{:}); clear varargin; sizeA = size(a); switch code case 'gaussian' % Gaussian white noise %b = a + sqrt(p4)*randn(sizeA) + p3; p4 = sqrt(p4); r = gpuArray.randn(sizeA); b = arrayfun(@applyGaussian, a,r); b = images.internal.changeClass(classIn, b); case 'localvar_1' % Gaussian white noise with variance varying locally b = images.internal.algimnoise(a, code, classIn, classChanged, p3, p4); case 'localvar_2' % Gaussian white noise with variance varying locally b = images.internal.algimnoise(a, code, classIn, classChanged, p3, p4); case 'poisson' % Poisson noise b = images.internal.algimnoise(a, code, classIn, classChanged, p3, p4); case 'salt & pepper' % Salt & pepper noise r = gpuArray.rand(sizeA); p3by2 = p3/2; b = arrayfun(@applysnp, a, r); b = images.internal.changeClass(classIn, b); case 'speckle' % Speckle (multiplicative) noise p3factor = sqrt(12*p3); r = gpuArray.rand(sizeA); b = arrayfun(@applySpeckle, a, r); b = images.internal.changeClass(classIn, b); end function pixout = applyGaussian(pixin, r) %b = a + sqrt(p4)*randn(sizeA) + p3; pixout = pixin + r*p4+p3; pixout = max(0, min(pixout,1)); end function pixout = applysnp(pixin,r) %b(r < p3/2) = 0; % Minimum value %b(r >= p3/2 & r < p3) = 1; % Maximum (saturated) value pixout = (r>=p3by2)*( (r<p3) + pixin*(r>=p3)); pixout = max(0, min(pixout,1)); end function pixout = applySpeckle(pixin,r) %b = a + sqrt(12*p3)*a.*(rand(sizeA)-.5); pixout = pixin + p3factor*pixin*(r-0.5); pixout = max(0, min(pixout,1)); end end %%% %%% ParseInputs %%% function [a, code, classIn, classChanged, p3, p4, msg] = ParseInputs(varargin) % Initialization p3 = []; p4 = []; msg = ''; % Check the number of input arguments. narginchk(1,4); % Check the input-array type. a = varargin{1}; hValidateAttributes(a,... {'uint8','uint16','double','int16','single'}, ... {},mfilename,'I',1); gatheredVarargin = gatherIfNecessary(varargin{2:end}); varargin = {a, gatheredVarargin{:}}; % Change class to double classIn = classUnderlying(a); classChanged = 0; if ~strcmp(classIn, 'double'); a = im2double(a); classChanged = 1; else % Clip so a is between 0 and 1. a = max(min(a,1),0); end % Check the noise type. if nargin > 1 if ~ischar(varargin{2}) error(message('images:imnoise:invalidNoiseType')) end % Preprocess noise type string to detect abbreviations. allStrings = {'gaussian', 'salt & pepper', 'speckle', 'poisson','localvar'}; idx = find(strncmpi(varargin{2}, allStrings, numel(varargin{2}))); switch length(idx) case 0 error(message('images:imnoise:unknownNoiseType', varargin{ 2 })) case 1 code = allStrings{idx}; otherwise error(message('images:imnoise:ambiguousNoiseType', varargin{ 2 })) end else code = 'gaussian'; % default noise type end switch code case 'poisson' if nargin > 2 error(message('images:imnoise:tooManyPoissonInputs')) end if isa(a, 'int16') error(message('images:imnoise:badClassForPoisson')); end case 'gaussian' p3 = 0; % default mean p4 = 0.01; % default variance if nargin > 2 p3 = varargin{3}; if ~isRealScalar(p3) error(message('images:imnoise:invalidMean')) end end if nargin > 3 p4 = varargin{4}; if ~isNonnegativeRealScalar(p4) error(message('images:imnoise:invalidVariance', 'gaussian')) end end case 'salt & pepper' p3 = 0.05; % default density if nargin > 2 p3 = varargin{3}; if ~isNonnegativeRealScalar(p3) || (p3 > 1) error(message('images:imnoise:invalidNoiseDensity')) end if nargin > 3 error(message('images:imnoise:tooManySaltAndPepperInputs')) end end case 'speckle' p3 = 0.05; % default variance if nargin > 2 p3 = varargin{3}; if ~isNonnegativeRealScalar(p3) error(message('images:imnoise:invalidVariance', 'speckle')) end end if nargin > 3 error(message('images:imnoise:tooManySpeckleInputs')) end case 'localvar' if nargin < 3 error(message('images:imnoise:toofewLocalVarInputs')) elseif nargin == 3 % IMNOISE(a,'localvar',v) code = 'localvar_1'; p3 = varargin{3}; if ~isNonnegativeReal(p3) || ~isequal(size(p3),size(a)) error(message('images:imnoise:invalidLocalVarianceValueAndSize')) end elseif nargin == 4 % IMNOISE(a,'localvar',IMAGE_INTENSITY,NOISE_VARIANCE) code = 'localvar_2'; p3 = varargin{3}; p4 = varargin{4}; if ~isNonnegativeRealVector(p3) || (any(p3) > 1) error(message('images:imnoise:invalidImageIntensity')) end if ~isNonnegativeRealVector(p4) error(message('images:imnoise:invalidLocalVariance')) end if ~isequal(size(p3),size(p4)) error(message('images:imnoise:invalidSize')) end % Intensity values should be in increasing order for gpu [p3, sInds] = sort(p3); p4 = p4(sInds); else error(message('images:imnoise:tooManyLocalVarInputs')) end end end %%% %%% isReal %%% function t = isReal(P) % isReal(P) returns 1 if P contains only real % numbers and returns 0 otherwise. % isFinite = all(isfinite(P(:))); t = isreal(P) && isFinite && ~isempty(P); end %%% %%% isNonnegativeReal %%% function t = isNonnegativeReal(P) % isNonnegativeReal(P) returns 1 if P contains only real % numbers greater than or equal to 0 and returns 0 otherwise. % t = isReal(P) && all(P(:)>=0); end %%% %%% isRealScalar %%% function t = isRealScalar(P) % isRealScalar(P) returns 1 if P is a real, % scalar number and returns 0 otherwise. % t = isReal(P) && (numel(P)==1); end %%% %%% isNonnegativeRealScalar %%% function t = isNonnegativeRealScalar(P) % isNonnegativeRealScalar(P) returns 1 if P is a real, % scalar number greater than 0 and returns 0 otherwise. % t = isReal(P) && all(P(:)>=0) && (numel(P)==1); end %%% %%% isVector %%% function t = isVector(P) % isVector(P) returns 1 if P is a vector and returns 0 otherwise. % t = ((numel(P) >= 2) && ((size(P,1) == 1) || (size(P,2) == 1))); end %%% %%% isNonnegativeRealVector %%% function t = isNonnegativeRealVector(P) % isNonnegativeRealVector(P) returns 1 if P is a real, % vector greater than 0 and returns 0 otherwise. % t = isReal(P) && all(P(:)>=0) && isVector(P); end
github
wangsuyuan/Imageprocesingtoobox-master
normxcorr2.m
.m
Imageprocesingtoobox-master/@gpuArray/normxcorr2.m
7,447
utf_8
83737fbfe2ae6f1fbd16a1bf0a0c4392
function C = normxcorr2(varargin) %NORMXCORR2 Normalized two-dimensional cross-correlation. % C = NORMXCORR2(TEMPLATE,A) computes the normalized cross-correlation of % gpuArray TEMPLATE and A. The gpuArray A must be larger than the % gpuArray TEMPLATE for the normalization to be meaningful. The values of % TEMPLATE cannot all be the same. The resulting matrix C contains % correlation coefficients and its values may range from -1.0 to 1.0. % % Class Support % ------------- % The input matrices are numeric. The class underlying output matrix C is % double. % % Remarks % ------- % Normalized cross correlation is an undefined operation in regions where % A has zero variance over the full extent of the template. In these % regions, we assign correlation coefficients of zero to the output C. % % Example % ------- % template = .2*gpuArray.ones(11); % % Make light gray plus on dark gray background % template(6,3:9) = .6; % template(3:9,6) = .6; % % Make white plus on black background % BW = template > 0.5; % figure, imshow(BW), figure, imshow(template) % % Make new image that offsets the template % offsetTemplate = .2*gpuArray.ones(21); % offset = [3 5]; % shift by 3 rows, 5 columns % offsetTemplate( (1:size(template,1))+offset(1),... % (1:size(template,2))+offset(2) ) = template; % figure, imshow(offsetTemplate) % % % cross-correlate BW and offsetTemplate to recover offset % cc = normxcorr2(BW,offsetTemplate); % [max_cc, imax] = max(abs(cc(:))); % [ypeak, xpeak] = ind2sub(size(cc),imax(1)); % corr_offset = [ (ypeak-size(template,1)) (xpeak-size(template,2)) ]; % isequal(corr_offset,offset) % 1 means offset was recovered % % See also CORRCOEF. % Copyright 2013 The MathWorks, Inc. % Input-output specs % ------------------ % T: 2-D, real, full matrix % logical, uint8, uint16, or double % no NaNs, no Infs % prod(size(T)) >= 2 % std(T(:))~=0 % % A: 2-D, real, full matrix % logical, uint8, uint16, or double % no NaNs, no Infs % size(A,1) >= size(T,1) % size(A,2) >= size(T,2) % % C: double [T, A] = ParseInputs(varargin{:}); % We normalize the cross correlation to get correlation coefficients using the % definition of Haralick and Shapiro, Volume II (p. 317), generalized to % two-dimensions. % % Lewis explicitly defines the normalized cross-correlation in two-dimensions % in this paper (equation 2): % % "Fast Normalized Cross-Correlation", by J. P. Lewis, Industrial Light & Magic. % % Our technical reference document on NORMXCORR2 shows how to get from % equation 2 of the Lewis paper to the code below. xcorr_TA = xcorr2_fast(T,A); [m,n] = size(T); mn = m*n; local_sum_A = local_sum(A,m,n); local_sum_A2 = local_sum(A.*A,m,n); % Note: diff_local_sums should be nonnegative, but may have negative % values due to round off errors. Below, we use max to ensure the % radicand is nonnegative. % diff_local_sums = ( local_sum_A2 - (local_sum_A.^2)/mn ); % denom_A = sqrt( max(diff_local_sums,0) ); % denom = denom_T*denom_A; % numerator = (xcorr_TA - local_sum_A*sum(reshape(T,numel(T),1))/mn ); Tcol = reshape(T,numel(T),1); sumT = sum(Tcol); stdT = std(Tcol); denom_T = sqrt(mn-1)*stdT; [numerator,denom] = arrayfun(@computeNumDen,local_sum_A,local_sum_A2,xcorr_TA); function [num,den] = computeNumDen(local_sum_a,local_sum_a2,xcorr_ta) diff_local_sum = local_sum_a2 - (local_sum_a^2)/mn; denom_A = sqrt(max(diff_local_sum,0)); den = denom_T*denom_A; num = xcorr_ta - local_sum_a*sumT/mn; end % We know denom_T~=0 from input parsing; % so denom is only zero where denom_A is zero, and in % these locations, C is also zero. % C = zeros(size(numerator)); % i_nonzero = find(denom > tol); % C(i_nonzero) = numerator(i_nonzero) ./ denom(i_nonzero); % Another numerics backstop. If any of the coefficients are outside the % range [-1 1], the numerics are unstable to small variance in A or T. In % these cases, set C to zero to reflect undefined 0/0 condition. % C( ( abs(C) - 1 ) > sqrt(eps(1)) ) = 0; tol = sqrt( eps( max(abs(reshape(denom,numel(denom),1)))) ); C = arrayfun(@computeNCC,numerator,denom); function c = computeNCC(num,den) c = 0; if(den>tol) c = num/den; end c = (abs(c)-1<=sqrt(eps(1)))*c; end end %------------------------------- % Function local_sum % function local_sum_A = local_sum(A,m,n) % We thank Eli Horn for providing this code, used with his permission, % to speed up the calculation of local sums. The algorithm depends on % precomputing running sums as described in "Fast Normalized % Cross-Correlation", by J. P. Lewis, Industrial Light & Magic. B = padarray(A,[m n]); s = cumsum(B,1); % c = s(1+m:end-1,:)-s(1:end-m-1,:); c = subsref(s,substruct('()',{1+m:size(s,1)-1 ,':'})) ... - subsref(s,substruct('()',{1 :size(s,1)-m-1,':'})); s = cumsum(c,2); % local_sum_A = s(:,1+n:end-1)-s(:,1:end-n-1); local_sum_A = subsref(s,substruct('()',{':',1+n:size(s,2)-1 })) ... - subsref(s,substruct('()',{':',1 :size(s,2)-n-1})); end %------------------------------- % Function xcorr2_fast % function cross_corr = xcorr2_fast(T,A) T_size = size(T); A_size = size(A); outsize = A_size + T_size - 1; if (numel(T)<2500) cross_corr = conv2(rot90(T,2),A); else cross_corr = freqxcorr(T,A,outsize); end end %------------------------------- % Function freqxcorr % function xcorr_ab = freqxcorr(a,b,outsize) % calculate correlation in frequency domain Fa = fft2(rot90(a,2),outsize(1),outsize(2)); Fb = fft2(b, outsize(1),outsize(2)); xcorr_ab = ifft2(Fa .* Fb, 'symmetric'); end %----------------------------------------------------------------------------- function [T, A] = ParseInputs(varargin) narginchk(2,2) T = gpuArray(varargin{1}); A = gpuArray(varargin{2}); hValidateAttributes(T,{'logical','numeric'},{'real','2d', 'finite'},... mfilename,'T',1); hValidateAttributes(A,{'logical','numeric'},{'real','2d', 'finite'},... mfilename,'A',2); checkSizesTandA(T,A) % See geck 342320. If either A or T has a minimum value which is negative, we % need to shift the array so all values are positive to ensure numerically % robust results for the normalized cross-correlation. A = shiftData(A); T = shiftData(T); checkIfFlat(T); end %----------------------------------------------------------------------------- function B = shiftData(A) B = double(A); is_unsigned = strcmp(classUnderlying(A),'uint8') || ... strcmp(classUnderlying(A),'uint16') || ... strcmp(classUnderlying(A),'uint32'); if ~is_unsigned min_B = min(reshape(B,numel(B),1)); if min_B < 0 B = B - min_B; end end end %----------------------------------------------------------------------------- function checkSizesTandA(T,A) if numel(T) < 2 error(message('images:normxcorr2:invalidTemplate')) end if size(A,1)<size(T,1) || size(A,2)<size(T,2) error(message('images:normxcorr2:invalidSizeForA')) end end %----------------------------------------------------------------------------- function checkIfFlat(T) s.type = '()'; s.subs = {1}; oneElement = subsref(T, s); if all(oneElement==reshape(T,numel(T),1)) error(message('images:normxcorr2:sameElementsInTemplate')) end end
github
wangsuyuan/Imageprocesingtoobox-master
im2uint8.m
.m
Imageprocesingtoobox-master/@gpuArray/im2uint8.m
4,843
utf_8
e110587eea6c78c6845e415550224b50
function u = im2uint8(img, varargin) %IM2UINT8 Convert gpuArray image to 8-bit unsigned integers. % IM2UINT8 takes a gpuArray image as input, and returns a gpuArray image % of underying class uint8. If the input gpuArray is of class uint8, the % output gpuArray is identical to it. If the input gpuArray is not % uint8, IM2UINT8 returns the equivalent gpuArray of underlying class % uint8, rescaling or offsetting the data as necessary. % % I2 = IM2UINT8(I1) converts the intensity gpuArray image I1 to uint8, % rescaling the data if necessary. % % RGB2 = IM2UINT8(RGB1) converts the truecolor gpuArray image RGB1 to % uint8, rescaling the data if necessary. % % I = IM2UINT8(BW) converts the binary gpuArray image BW to a uint8 % intensity image, changing one-valued elements to 255. % % X2 = IM2UINT8(X1,'indexed') converts the indexed gpuArray image X1 to % uint8, offsetting the data if necessary. Note that it is not always % possible to convert an indexed gpuArray image to uint8. If X1 is % double, then the maximum value of X1 must be 256 or less. If X1 is % uint16, the maximum value of X1 must be 255 or less. % % Class Support % ------------- % Intensity and truecolor gpuArray images can be uint8, uint16, double, % logical, single, or int16. Indexed gpuArray images can be uint8, % uint16, double or logical. Binary input gpuArray images must be % logical. The output gpuArray is uint8. % % Example % ------- % I1 = gpuArray(reshape(uint16(linspace(0,65535,25)),[5 5])) % I2 = im2uint8(I1) % % See also GPUARRAY/IM2DOUBLE, GPUARRAY/IM2INT16, GPUARRAY/IM2SINGLE, % GPUARRAY/IM2UINT16, GPUARRAY/UINT8, GPUARRAY. % Copyright 2013 The MathWorks, Inc. %% inputs narginchk(1,2); classImg = classUnderlying(img); hValidateAttributes(img,... {'double','logical','uint8','uint16','single','int16'}, ... {},mfilename,'Image',1); if(~isreal(img)) warning(message('images:im2uint8:ignoringImaginaryPartOfInput')); img = real(img); end if nargin == 2 validatestring(varargin{1},{'indexed'},mfilename,'type',2); end %% process if strcmp(classImg, 'uint8') u = img; elseif strcmp(classImg, 'logical') u = uint8(img) * 255; else %double, single, uint16, or int16 if nargin == 1 if strcmp(classImg, 'int16') z = uint16(int32(img) + 32768); u = uint8(double(z)*1/257); end % intensity image if strcmp(classImg, 'double') u = arrayfun(@grayto8double,img); elseif strcmp(classImg, 'single') u = arrayfun(@grayto8single,img); elseif strcmp(classImg, 'uint16') u = arrayfun(@grayto8uint8,img); end else s.type = '()'; s.subs = {':'}; if strcmp(classImg, 'int16') error(message('images:im2uint8:invalidIndexedImage')) elseif strcmp(classImg, 'uint16') if (max(subsref(img,s)) > 255) error(message('images:im2uint8:tooManyColorsFor8bitStorage')) else u = uint8(img); end else %double or single if any(max(subsref(img,s)) >= 257) error(message('images:im2uint8:tooManyColorsFor8bitStorage')) elseif any(min(subsref(img,s)) < 1) error(message('images:im2uint8:invalidIndexValue')) else u = uint8(img-1); end end end end function b = grayto8double(img) %GRAYTO8 Scale and convert grayscale image to uint8. % B = GRAYTO8(A) converts the double array A to uint8 by % scaling A by 255 and then rounding. NaN's in A are converted % to 0. Values in A greater than 1.0 are converted to 255; % values less than 0.0 are converted to 0. if isnan(img) b = uint8(0); else % uint8() rounds DOUBLE and SINGLE values. No need to add 0.5 as in % grayto8 MEX code img = img * 255; if img > 255 img = 255; elseif img < 0 img = 0; end b = uint8(img); end function b = grayto8single(img) %GRAYTO8 Scale and convert grayscale image to uint8. % B = GRAYTO8(A) converts the double array A to uint8 by % scaling A by 255 and then rounding. NaN's in A are converted % to 0. Values in A greater than 1.0 are converted to 255; % values less than 0.0 are converted to 0. if isnan(img) b = uint8(0); else % uint8() rounds DOUBLE and SINGLE values. No need to add 0.5 as in % grayto8 MEX code maxVal = single(255); minVal = single(0); img = img * maxVal; if img > maxVal img = maxVal; elseif img < minVal img = minVal; end b = uint8(img); end function b = grayto8uint8(img) b = uint8(double(img) * 1/257);
github
wangsuyuan/Imageprocesingtoobox-master
im2int16.m
.m
Imageprocesingtoobox-master/@gpuArray/im2int16.m
4,101
utf_8
b82817abcde17bfebd5fe10f09ce4a93
function J = im2int16(I) %IM2INT16 Convert gpuArray image to 16-bit signed integers. % IM2INT16 takes a gpuArray image I as input, and returns a gpuArray % image J of underlying class int16. If I is int16, then J is identical % to it. If I is not int16 then IM2INT16 returns the equivalent gpuArray % image J of underlying class int16, rescaling the data as necessary. % % I2 = IM2INT16(I1) converts the gpuArray intensity image I1 to int16, % rescaling the data if necessary. % % RGB2 = IM2INT16(RGB1) converts the truecolor image RGB1 to % int16, rescaling the data if necessary. % % I = IM2INT16(BW) converts the binary gpuArray image BW to an int16 % gpuArray intensity image, changing false-valued elements to -32768 and % true-valued elements to 32767. % % Class Support % ------------- % Intensity and truecolor gpuArray images can be uint8, uint16, double, % logical, single, or int16. Binary input gpuArray images must be % logical. The output image is a gpuArray with underlying class int16. % % Example % ------- % I1 = gpuArray(reshape(linspace(0,1,20),[5 4])) % I2 = im2int16(I1) % % See also GPUARRAY/IM2DOUBLE, GPUARRAY/IM2SINGLE, GPUARRAY/IM2UINT8, % GPUARRAY/IM2UINT16, GPUARRAY/INT16, GPUARRAY. % Copyright 2013 The MathWorks, Inc. %% inputs narginchk(1,1); classIn = classUnderlying(I); hValidateAttributes(I,... {'int16','uint16','uint8','double','single','logical'}, ... {},mfilename,'I',1); if(~isreal(I)) warning(message('images:im2int16:ignoringImaginaryPartOfInput')); I = real(I); end %% process if strcmp(classIn,'int16') J = I; elseif islogical(I) J = arrayfun(@scaleLogicalToint16,I); else % double, single, uint8, or uint16 if ~strcmp(classIn, 'uint16') if strcmp(classIn, 'double') J = arrayfun(@grayto16double,I); elseif strcmp(classIn, 'single') J = arrayfun(@grayto16single,I); elseif strcmp(classIn, 'uint8') J = arrayfun(@grayto16uint8,I); end else J = I; end % Convert uint16 to int16. J = arrayfun(@uint16toint16,J); end function pixout = scaleLogicalToint16(pixin) % J = int16(I)*int16(32767) + int16(~I)*int16(-32768); pixout = int16(pixin)*int16(32767) + int16(pixin==0)*int16(-32768); function b = grayto16uint8(img) %GRAYTO16 Scale and convert grayscale image to uint16. % B = GRAYTO16(A) converts the uint8 array A by scaling the % elements of A by 257 and then casting to uint8. b = bitor(bitshift(uint16(img),8),uint16(img)); function b = grayto16double(img) %GRAYTO16 Scale and convert grayscale image to uint16. % B = GRAYTO16(A) converts the double array A to uint16 by % scaling A by 65535 and then rounding. NaN's in A are converted % to 0. Values in A greater than 1.0 are converted to 65535; % values less than 0.0 are converted to 0. if isnan(img) b = uint16(0); else % uint16() rounds DOUBLE and SINGLE values. No need to add 0.5 as in % grayto16 MEX code img = img * 65535; if img > 65535 img = 65535; elseif img < 0 img = 0; end b = uint16(img); end function b = grayto16single(img) %GRAYTO16 Scale and convert grayscale image to uint16. % B = GRAYTO16(A) converts the double array A to uint16 by % scaling A by 65535 and then rounding. NaN's in A are converted % to 0. Values in A greater than 1.0 are converted to 65535; % values less than 0.0 are converted to 0. if isnan(img) b = uint16(0); else % uint16() rounds DOUBLE and SINGLE values. No need to add 0.5 as in % grayto16 MEX code maxVal = single(65535); minVal = single(0); img = img * maxVal; if img > maxVal img = maxVal; elseif img < minVal img = minVal; end b = uint16(img); end function z = uint16toint16(img) %UINT16TOINT16 converts uint16 to int16 % Z = UINT16TOINT16(I) converts uint16 data (range = 0 to 65535) to int16 % data (range = -32768 to 32767). z = int16(int32(img)-int32(32768));
github
wangsuyuan/Imageprocesingtoobox-master
imabsdiff.m
.m
Imageprocesingtoobox-master/@gpuArray/imabsdiff.m
3,734
utf_8
c96891b3d506862c1b4e86aaf541d921
function Z = imabsdiff(varargin) %IMABSDIFF Absolute difference of two images. % Z = IMABSDIFF(X,Y) subtracts each element in gpuArray Y from the % corresponding element in gpuArray X and returns the absolute difference % in the corresponding element of the output array Z. X and Y are real, % nonsparse, numeric or logical arrays with the same class and size. Z % has the same class and size as X and Y. If X and Y are integer % arrays, elements in the output that exceed the range of the integer % type are truncated. At least one of the inputs must be a gpuArray. % % If X and Y are single or double arrays, you can use the expression % ABS(X-Y) instead of this function. If X and Y are logical arrays, you % can use the expression XOR(A,B) instead of this function. % % Example % ------- % Display the absolute difference between a filtered image and the % original. % % I = gpuArray(imread('cameraman.tif')); % J = imfilter(I,fspecial('gaussian')); % K = imabsdiff(I,J); % figure, imshow(K,[]) % % See also IMADD, IMCOMPLEMENT, IMDIVIDE, GPUARRAY/IMLINCOMB, IMSUBTRACT, % GPUARRAY. % Copyright 2012-2013 The MathWorks, Inc. narginchk(2,2); X = varargin{1}; Y = varargin{2}; % Both inputs must be real. if ~(isreal(X) && isreal(Y)) error(message('images:imabsdiff:gpuArrayReal')); end % Convert both inputs to gpuArray's. if ~isa(X,'gpuArray') X = gpuArray(X); end if ~isa(Y,'gpuArray') Y = gpuArray(Y); end % Both inputs need to be of the same size and class. checkForSameSizeAndClass(X, Y); datatype = classUnderlying(X); if isempty(X) if strcmp(datatype,'logical') Z = gpuArray.false(size(X)); else Z = gpuArray.zeros(size(X), datatype); end else switch datatype case 'int8' Z = arrayfun(@imabsdiffint8,X,Y); case 'uint8' Z = arrayfun(@imabsdiffuint8,X,Y); case 'int16' Z = arrayfun(@imabsdiffint16,X,Y); case 'uint16' Z = arrayfun(@imabsdiffuint16,X,Y); case 'int32' Z = arrayfun(@imabsdiffint32,X,Y); case 'uint32' Z = arrayfun(@imabsdiffuint32,X,Y); case 'single' Z = arrayfun(@imabsdifffloatingpoint,X,Y); case 'double' Z = arrayfun(@imabsdifffloatingpoint,X,Y); case 'logical' Z = xor(X,Y); otherwise error(message('images:imabsdiff:unsupportedDataType')); end end end function z = imabsdiffint8(x,y) %IMABSDIFFINT8 compute absolute difference between pixels of type % int8. z = int8( abs( int16(x) - int16(y) ) ); end function z = imabsdiffuint8(x,y) %IMABSDIFFUINT8 compute absolute difference between pixels of type % uint8. z = uint8( abs( int16(x) - int16(y) ) ); end function z = imabsdiffint16(x,y) %IMABSDIFFINT16 compute absolute difference between pixels of type % int16. z = int16( abs( int32(x) - int32(y) ) ); end function z = imabsdiffuint16(x,y) %IMABSDIFFUINT16 compute absolute difference between pixels of type % uint16. z = uint16( abs( int32(x) - int32(y) ) ); end function z = imabsdiffint32(x,y) %IMABSDIFFINT32 compute absolute difference between pixels of type % int32. z = int32( abs( double(x) - double(y) ) ); end function z = imabsdiffuint32(x,y) %IMABSDIFFUINT32 compute absolute difference between pixels of type % uint32. z = uint32( abs( double(x) - double(y) ) ); end function z = imabsdifffloatingpoint(x,y) %IMABSDIFFFLOAT compute absolute difference between pixels of type % single/double. z = abs( x - y ); end
github
wangsuyuan/Imageprocesingtoobox-master
imlincomb.m
.m
Imageprocesingtoobox-master/@gpuArray/imlincomb.m
6,507
utf_8
6adf6a3d5cb2c9c40c860bffc30868b8
function Z = imlincomb(varargin) %IMLINCOMB Linear combination of images. % Z = IMLINCOMB(K1,A1,K2,A2, ..., Kn,An) computes K1*A1 + K2*A2 + ... + % Kn*An. A1, A2, ..., An are gpuArray's with the same class and size, % and K1, K2, ..., Kn are real double scalars. Z has the same size and % class as A1 unless A1 is logical, in which case Z is double. % % Z = IMLINCOMB(K1,A1,K2,A2, ..., Kn,An,K) computes K1*A1 + K2*A2 + % ... + Kn*An + K. % % Z = IMLINCOMB(..., OUTPUT_CLASS) lets you specify the class of Z. % OUTPUT_CLASS is a string containing the name of a numeric class. % % Use IMLINCOMB to perform a series of arithmetic operations on a pair % of images, rather than nesting calls to individual arithmetic % functions, such as IMADD and IMMULTIPLY. When you nest calls to the % arithmetic functions, and the input arrays have integer class, then % each function truncates and rounds the result before passing it to % the next function, thus losing accuracy in the final result. % IMLINCOMB performs all the arithmetic operations at once before % truncating and rounding the final result. % % Each element of the output, Z, is computed individually in % double-precision floating point. When Z is an integer array, elements % of Z that exceed the range of the integer type are truncated, and % fractional values are rounded. At least one of the images A1, A2, ... % An needs to be a gpuArray for computation to be performed on the GPU. % The scalars can also be gpuArray's. % % Note: % ----- % IMLINCOMB is a convenience function, enabling functions/scripts which % call it to accept gpuArray objects. If your images are already on the % GPU, consider using ARRAYFUN to cast the pixels to a larger datatype, % compute the linear combination of the series of images directly, and % cast the data to the output type. This will likely be more efficient % than using IMLINCOMB, which is a general purpose function. % % For example, to perform the linear combination specified below on 3 % uint8 images, % % Z = 0.299*R + 0.587*G + 0.114*B % % use the following: % % fHandle = @(r,g,b) uint8( 0.299*double(r) + 0.587*double(g) +... % 0.114*double(b) ); % % Z = arrayfun( fHandle, R,G,B ); % % % Example 1 % --------- % Scale an image by a factor of two. % % I = gpuArray(imread('cameraman.tif')); % J = imlincomb(2,I); % figure, imshow(J) % % Example 2 % --------- % Form a difference image with the zero value shifted to 128. % % I = gpuArray(imread('cameraman.tif')); % J = imfilter(I, fspecial('gaussian')); % K = imlincomb(1,I,-1,J,128); % K(r,c) = I(r,c) - J(r,c) + 128 % figure, imshow(K) % % Example 3 % --------- % Add two images with a specified output class. % % I = gpuArray(imread('rice.png')); % J = gpuArray(imread('cameraman.tif')); % K = imlincomb(1,I,1,J,'uint16'); % figure, imshow(K,[]) % % See also IMADD, IMCOMPLEMENT, IMDIVIDE, IMMULTIPLY, IMSUBTRACT, % GPUARRAY. % Copyright 2012-2013 The MathWorks, Inc. [ims, scalars, outputClass] = ParseInputs(varargin{:}); num_images = numel(ims); if any(cellfun('isclass',ims,'gpuArray')) if num_images == 2 % two image arrayfun. Z = imlincomb_twoImage(ims, scalars, outputClass); elseif num_images == 3 % three image arrayfun. Z = imlincomb_threeImage(ims, scalars, outputClass); else % lazy evaluation. Z = imlincomb_lazyEval(ims, scalars, outputClass); end else % if no images are gpuArrays, do work on the CPU. Z = images.internal.imlincombc(ims,scalars,outputClass); end %-------------------------------------------------------------------------- function out = imlincomb_twoImage(images, scalars, outputClass) if numel(scalars)==2 out = cast( arrayfun(@lincombTwoImage,... images{1},images{2},... scalars(1),scalars(2),0), outputClass ); else out = cast( arrayfun(@lincombTwoImage,... images{1},images{2},... scalars(1),scalars(2),scalars(3)), outputClass ); end %-------------------------------------------------------------------------- function out = imlincomb_threeImage(images, scalars, outputClass) if numel(scalars)==3 out = cast( arrayfun(@lincombThreeImage,... images{1},images{2},images{3},... scalars(1),scalars(2),scalars(3),0), outputClass ); else out = cast( arrayfun(@lincombThreeImage,... images{1},images{2},images{3},... scalars(1),scalars(2),scalars(3),scalars(4)), outputClass ); end %-------------------------------------------------------------------------- function out = imlincomb_lazyEval(images, scalars, outputClass) % rely on lazy evaluation to chain this loop. out = scalars(1).*double(images{1}); for n = 2 : numel(images) out = out + scalars(n).*double(images{n}); end if numel(images)==numel(scalars) out = cast(out,outputClass); else out = cast(out + scalars(end),outputClass); end %-------------------------------------------------------------------------- function [ims, scalars, output_class] = ParseInputs(varargin) narginchk(2, Inf); % get and check input type. if strcmp(class(varargin{2}),'gpuArray') %#ok<*STISA> input_class = classUnderlying(varargin{2}); else input_class = class(varargin{2}); end % determine output type. if ischar(varargin{end}) valid_strings = {'uint8' 'uint16' 'uint32' 'int8' 'int16' 'int32' ... 'single' 'double'}; output_class = validatestring(varargin{end}, valid_strings, mfilename, ... 'OUTPUT_CLASS', 3); varargin(end) = []; else if islogical(varargin{2}) output_class = 'double'; else output_class = input_class; end end % check images. ims = varargin(2:2:end); % check and gather scalars. for p = 1:2:length(varargin) varargin{p} = gather(varargin{p}); validateattributes(varargin{p}, {'double'}, {'real' 'nonsparse' 'scalar'}, ... mfilename, sprintf('K%d', (p+1)/2), p); end scalars = [varargin{1:2:end}]; % check image size and class. for n = 2 : numel(ims) if ~isequal( size(ims{n}),size(ims{1}) ) error(message('images:imlincomb:mismatchedSize')); end if strcmp(class(ims{n}),'gpuArray') && ~strcmp(classUnderlying(ims{n}),input_class)... ||( ~strcmp(class(ims{n}),'gpuArray') && ~(strcmp(class(ims{n}),input_class)) ) error(message('images:imlincomb:mismatchedType')); end end
github
wangsuyuan/Imageprocesingtoobox-master
imfilter.m
.m
Imageprocesingtoobox-master/@gpuArray/imfilter.m
9,498
utf_8
f661bcffae73194f86e2efb63c4ec74c
function b = imfilter(varargin) %IMFILTER N-D filtering of multidimensional images. % B = IMFILTER(A,H) filters the multidimensional array A with the % filter H. A can be logical or it can be a nonsparse numeric % array of any class and dimension. The result, B, has the same % size and class as A. When A is a gpuArray object, H must be a % vector or 2-D matrix. % % Each element of the output, B, is computed using either single- % or double-precision floating point, depending on the data type % of A. When A contains double-precision or UINT32 values, the % computations are performed using double-precision values. All % other data types use single-precision. If A is an integer or % logical array, then output elements that exceed the range of % the given type are truncated, and fractional values are rounded. % % B = IMFILTER(A,H,OPTION1,OPTION2,...) performs multidimensional % filtering according to the specified options. Option arguments can % have the following values: % % - Boundary options % % X Input array values outside the bounds of the array % are implicitly assumed to have the value X. When no % boundary option is specified, IMFILTER uses X = 0. % % 'symmetric' Input array values outside the bounds of the array % are computed by mirror-reflecting the array across % the array border. % % 'replicate' Input array values outside the bounds of the array % are assumed to equal the nearest array border % value. % % 'circular' Input array values outside the bounds of the array % are computed by implicitly assuming the input array % is periodic. % % - Output size options % (Output size options for IMFILTER are analogous to the SHAPE option % in the functions CONV2 and FILTER2.) % % 'same' The output array is the same size as the input % array. This is the default behavior when no output % size options are specified. % % 'full' The output array is the full filtered result, and so % is larger than the input array. % % - Correlation and convolution % % 'corr' IMFILTER performs multidimensional filtering using % correlation, which is the same way that FILTER2 % performs filtering. When no correlation or % convolution option is specified, IMFILTER uses % correlation. % % 'conv' IMFILTER performs multidimensional filtering using % convolution. % % Example % ------------- % originalRGB = gpuArray(imread('peppers.png')); % h = fspecial('motion',50,45); % filteredRGB = imfilter(originalRGB,h); % figure, imshow(originalRGB) % figure, imshow(filteredRGB) % boundaryReplicateRGB = imfilter(originalRGB,h,'replicate'); % figure, imshow(boundaryReplicateRGB) % % See also FSPECIAL, GPUARRAY/CONV2, GPUARRAY/CONVN, GPUARRAY/FILTER2, % GPUARRAY. % Copyright 1993-2013 The MathWorks, Inc. [a, h, boundary, sameSize] = parse_inputs(varargin{:}); [finalSize, pad] = computeSizes(a, h, sameSize); %Empty Inputs % 'Same' output then size(b) = size(a) % 'Full' output then size(b) = size(h)+size(a)-1 if isempty(a) b = handleEmptyImage(a, sameSize, finalSize); return elseif isempty(h) b = handleEmptyFilter(a, sameSize, finalSize); return end boundaryStr = boundary; padVal = 0; if(~ischar(boundary)) boundaryStr = 'constant'; padVal = boundary; end %Special case if(ismatrix(a) && isequal(size(h),[3 3]) && sameSize... && isreal(a) && isreal(h) && ~strcmp(boundaryStr,'circular')) h = gpuArray(double(h)); padVal = cast(gather(padVal), classUnderlying(a)); b = imfiltergpumex(a, h, boundaryStr, padVal); return; end % Zero-pad input based on dimensions of filter kernel. a = padarray_algo(a,pad,boundaryStr,padVal,'both'); [separableFlag, u, s, v] = isSeparable(a, h); if (separableFlag) % Separable - Extract the components of the separable filter hcol = u(:,1) * sqrt(s(1)); hrow = v(:,1)' * sqrt(s(1)); b = filterPartOrWhole(a, finalSize, hrow, hcol, pad+1, sameSize); else % non-separable filter case b = filterPartOrWhole(a, finalSize, h, [], pad+1, sameSize); end %-------------------------------------------------------------- function [a, h, boundary, sameSize] = parse_inputs(a, h, varargin) narginchk(2,5); if ~isa(a, 'gpuArray') error(message('images:imfilter:gpuImageType')) end if (~ismatrix(h)) error(message('images:imfilter:gpuFilterKernelDims')) end %Assign defaults boundary = 0; %Scalar value of zero output = 'same'; do_fcn = 'corr'; allStrings = {'replicate', 'symmetric', 'circular', 'conv', 'corr', ... 'full','same'}; for k = 1:length(varargin) if ischar(varargin{k}) string = validatestring(varargin{k}, allStrings,... mfilename, 'OPTION',k+2); switch string case {'replicate', 'symmetric', 'circular'} boundary = string; case {'full','same'} output = string; case {'conv','corr'} do_fcn = string; end else validateattributes(varargin{k},{'numeric'},{'nonsparse'},mfilename,'OPTION',k+2); boundary = varargin{k}; end %else end sameSize = strcmp(output,'same'); convMode = strcmp(do_fcn,'conv'); % if isa(h, 'gpuArray') if ~convMode h = rot90(h,2); end else if convMode h = gpuArray(h); else % For convMode, filter must be rotated. Do this on the CPU for small sizes, as % it is likely to be slow. if numel(h) < 100000 h = gpuArray(rot90(h,2)); else h = rot90(gpuArray(h),2); end end end %-------------------------------------------------------------- function [separable, u, s, v] = isSeparable(a, h) % check for filter separability only if the kernel has enough % elements to make it worthwhile, both the image and the filter % kernel are two-dimensional and the kernel is not a row or column % vector, nor does it contain any NaNs of Infs. if strcmp(classUnderlying(a),'double') sep_threshold = 150; else sep_threshold = 900; end subs.type = '()'; subs.subs = {':'}; if ((numel(h) >= sep_threshold) && ... (ismatrix(a)) && ... (ismatrix(h)) && ... all(size(h) ~= 1) && ... all(isfinite(subsref(h,subs)))) [u, s, v] = svd(gather(h)); s = diag(s); tol = length(h) * s(1) * eps; rank = sum(s > tol); if (rank == 1) separable = true; else separable = false; end else separable = false; u = []; s = []; v = []; end %-------------------------------------------------------------- function b = handleEmptyImage(a, sameSize, im_size) if (sameSize) b = a; else if all(im_size >= 0) b = zeros(im_size, class(a)); else error(message('images:imfilter:negativeDimensionBadSizeB')) end end %-------------------------------------------------------------- function b = handleEmptyFilter(a, sameSize, im_size) if (sameSize) b = zeros(size(a), class(a)); else if all(im_size>=0) b = zeros(im_size, class(a)); else error(message('images:imfilter:negativeDimensionBadSizeB')) end end %-------------------------------------------------------------- function [finalSize, pad] = computeSizes(a, h, sameSize) rank_a = ndims(a); rank_h = ndims(h); % Pad dimensions with ones if filter and image rank are different size_h = [size(h) ones(1,rank_a-rank_h)]; size_a = [size(a) ones(1,rank_h-rank_a)]; if (sameSize) %Same output finalSize = size_a; %Calculate the number of pad pixels filter_center = floor((size_h + 1)/2); pad = size_h - filter_center; else %Full output finalSize = size_a+size_h-1; pad = size_h - 1; end %-------------------------------------------------------------- function a = filterPartOrWhole(a, outSize, h1, h2, outputStartIdx, sameSize) % intermediate results should be stored in doubles in order to % maintain sufficient precision origClass = classUnderlying(a); switch (origClass) case {'double', 'uint32'} sameClass = strcmp(origClass, 'double'); if (~sameClass) a = double(a); end otherwise sameClass = strcmp(origClass, 'single'); if (~sameClass) a = single(a); end end % Perform the filter. if (sameSize) sizeFlag = 'same'; else sizeFlag = 'full'; end if (isempty(h2)) % Nonseparable. a = convn(a, h1, sizeFlag); else % Separable - isSeparable() already checks for 2-D image and kernel. a = conv2(h1, h2, a, sizeFlag); end % Retrieve the part of the image that's required. sRHS.type = '()'; sRHS.subs = {outputStartIdx(1):(outputStartIdx(1) + outSize(1) - 1), ... outputStartIdx(2):(outputStartIdx(2) + outSize(2) - 1), ... ':'}; a = subsref(a, sRHS); % Cast the data as appropriate. if (~sameClass) a = castData(a, origClass); end %-------------------------------------------------------------- function result = castData(result, origClass) if (strcmp(origClass, 'logical')) result = result >= 0.5; else result = cast(result, origClass); end
github
wangsuyuan/Imageprocesingtoobox-master
bwmorph.m
.m
Imageprocesingtoobox-master/@gpuArray/bwmorph.m
16,608
utf_8
096f4eb02067e14b48c5853808f0bfa3
function bwout = bwmorph(bwin,opStr,n) %BWMORPH Morphological operations on binary image. % BW2 = BWMORPH(BW1,OPERATION) applies a specific % morphological operation to the binary gpuArray image BW1. % % BW2 = BWMORPH(BW1,OPERATION,N) applies the operation N % times. N can be Inf, in which case the operation is repeated % until the image no longer changes. % % OPERATION is a string that can have one of these values: % 'bothat' Subtract the input image from its closing % 'branchpoints' Find branch points of skeleton % 'bridge' Bridge previously unconnected pixels % 'clean' Remove isolated pixels (1's surrounded by 0's) % 'close' Perform binary closure (dilation followed by % erosion) % 'diag' Diagonal fill to eliminate 8-connectivity of % background % 'endpoints' Find end points of skeleton % 'fill' Fill isolated interior pixels (0's surrounded by % 1's) % 'hbreak' Remove H-connected pixels % 'majority' Set a pixel to 1 if five or more pixels in its % 3-by-3 neighborhood are 1's % 'open' Perform binary opening (erosion followed by % dilation) % 'remove' Set a pixel to 0 if its 4-connected neighbors % are all 1's, thus leaving only boundary % pixels % 'shrink' With N = Inf, shrink objects to points; shrink % objects with holes to connected rings % 'skel' With N = Inf, remove pixels on the boundaries % of objects without allowing objects to break % apart % 'spur' Remove end points of lines without removing % small objects completely % 'thicken' With N = Inf, thicken objects by adding pixels % to the exterior of objects without connected % previously unconnected objects % 'thin' With N = Inf, remove pixels so that an object % without holes shrinks to a minimally % connected stroke, and an object with holes % shrinks to a ring halfway between the hole % and outer boundary % 'tophat' Subtract the opening from the input image % % Class Support % ------------- % The input gpuArray image BW1 can be numeric or logical. % It must be 2-D, real and non-sparse. The output gpuArray image % BW2 is logical. % % Remarks % ------- % To perform erosion or dilation using the structuring element ones(3), % use IMERODE or IMDILATE. % % Examples % -------- % BW1 = gpuArray(imread('circles.png')); % figure, imshow(BW1) % BW2 = bwmorph(BW1,'remove'); % BW3 = bwmorph(BW1,'skel',Inf); % figure, imshow(BW2) % figure, imshow(BW3) % % See also GPUARRAY/IMERODE, GPUARRAY/IMDILATE, GPUARRAY, BWEULER, % BWPERIM. % Copyright 2012-2013 The MathWorks, Inc. %% Input argument parsing narginchk(2,3) if (nargin < 3) n = 1; end hValidateAttributes(bwin,... {'logical','uint8','int8','uint16','int16','uint32','int32','single','double'},... {'real','2d'},mfilename,'BW',1); if ~islogical(bwin) bwin = (bwin ~= 0); end validOperations = {'bothat',... 'branchpoints',... 'bridge',... 'clean',... 'close',... 'diag',... 'dilate',... 'endpoints',... 'erode',... 'fatten',... 'fill',... 'hbreak',... 'majority',... 'perim4',... 'perim8',... 'open',... 'remove',... 'shrink',... 'skeleton',... 'spur',... 'thicken',... 'thin',... 'tophat'}; opStr = validatestring(opStr,validOperations, 'bwmorph'); %% Call the core function if(isempty(bwin)) bwout = bwin; return; end if(n<1) % nothing to do bwout = bwin; elseif(n==1) bwout = bwmorphApplyOnce(bwin,opStr); else % Repeat N times or till output stops changing iter = 0; bwout = bwin; while(iter<n) last_aout = bwout; bwout = bwmorphApplyOnce(bwout,opStr); iter = iter+1; if(isequal(last_aout, bwout)) % the output is not changing anymore break end end end if (nargout == 0) imshow(bwout); end end function bw = bwmorphApplyOnce(bw, opStr) switch opStr % % Function BOTHAT % case 'bothat' bwc = bwlookupgpumex(bw, gpuArray(images.internal.lutdilate())); bwc = bwlookupgpumex(bwc, gpuArray(images.internal.luterode())); bw = bwc & ~bw; % % Function BRANCHPOINTS % case 'branchpoints' % Initial branch point candidates C = bwlookupgpumex(bw, gpuArray(images.internal.lutbranchpoints())); % Background 4-Connected Object Count (Vp) B = bwlookupgpumex(bw, gpuArray(uint8(images.internal.lutbackcount4()))); % End Points (Vp = 1) E = (B == 1); % Final branch point candidates FC = ~E .* C; % Generate mask that defines pixels for which Vp = 2 and no % foreground neighbor q for which Vq > 2 % Vp = 2 Mask Vp = ((B == 2) & ~E); % Vq > 2 Mask Vq = ((B > 2) & ~E); % Dilate Vq D = bwlookupgpumex(Vq, gpuArray(images.internal.lutdilate())); % Intersection between dilated Vq and final candidates w/ Vp = 2 M = (FC & Vp) & D; % Final Branch Points bw = FC & ~M; % % Function BRIDGE % case 'bridge' lut = images.internal.lutbridge(); bw = bwlookupgpumex(bw, gpuArray(lut)); % % Function CLEAN % case 'clean' lut = images.internal.lutclean(); bw = bwlookupgpumex(bw, gpuArray(lut)); % % Function CLOSE % case 'close' bwd = bwlookupgpumex(bw, gpuArray(images.internal.lutdilate())); bw = bwlookupgpumex(bwd, gpuArray(images.internal.luterode())); % % Function DIAG % case 'diag' lut = images.internal.lutdiag(); bw = bwlookupgpumex(bw, gpuArray(lut)); % % Function DILATE % case 'dilate' lut = images.internal.lutdilate(); bw = bwlookupgpumex(bw, gpuArray(lut)); % % Function ENDPOINTS % case 'endpoints' lut = images.internal.lutendpoints(); bw = bwlookupgpumex(bw, gpuArray(lut)); % % Function ERODE % case 'erode' lut = images.internal.luterode(); bw = bwlookupgpumex(bw, gpuArray(lut)); % % Function FATTEN % case 'fatten' lut = images.internal.lutfatten(); bw = bwlookupgpumex(bw, gpuArray(lut)); % % Function FILL % case 'fill' lut = images.internal.lutfill(); bw = bwlookupgpumex(bw, gpuArray(lut)); % % Function HBREAK % case 'hbreak' lut = images.internal.luthbreak(); bw = bwlookupgpumex(bw, gpuArray(lut)); % % Function MAJORITY % case 'majority' lut = images.internal.lutmajority(); bw = bwlookupgpumex(bw, gpuArray(lut)); % % Function OPEN % case 'open' bw = bwlookupgpumex(bw,gpuArray(images.internal.luterode())); bw = bwlookupgpumex(bw,gpuArray(images.internal.lutdilate())); % % Function PERIM4 % case 'perim4' lut = images.internal.lutper4(); bw = bwlookupgpumex(bw, gpuArray(lut)); % % Function PERIM8 % case 'perim8' lut = images.internal.lutper8(); bw = bwlookupgpumex(bw, gpuArray(lut)); % % Function REMOVE % case 'remove' lut = images.internal.lutremove(); bw = bwlookupgpumex(bw, gpuArray(lut)); % % Function SHRINK % case 'shrink' table = images.internal.lutshrink(); % First subiteration m = bwlookupgpumex(bw, gpuArray(table)); sub = bw & ~m; %bw(1:2:end,1:2:end) = sub(1:2:end,1:2:end); subStruct.type = '()'; subStruct.subs = {1:2:size(bw,1), 1:2:size(bw,2)}; bw = subsasgn(bw, subStruct, subsref(sub, subStruct)); % Second subiteration m = bwlookupgpumex(bw, gpuArray(table)); sub = bw & ~m; %bw(2:2:end,2:2:end) = sub(2:2:end,2:2:end); subStruct.type = '()'; subStruct.subs = {2:2:size(bw,1), 2:2:size(bw,2)}; bw = subsasgn(bw, subStruct, subsref(sub, subStruct)); % Third subiteration m = bwlookupgpumex(bw, gpuArray(table)); sub = bw & ~m; %bw(1:2:end,2:2:end) = sub(1:2:end,2:2:end); subStruct.type = '()'; subStruct.subs = {1:2:size(bw,1), 2:2:size(bw,2)}; bw = subsasgn(bw, subStruct, subsref(sub, subStruct)); % Fourth subiteration m = bwlookupgpumex(bw, gpuArray(table)); sub = bw & ~m; %bw(2:2:end,1:2:end) = sub(2:2:end,1:2:end); subStruct.type = '()'; subStruct.subs = {2:2:size(bw,1), 1:2:size(bw,2)}; bw = subsasgn(bw, subStruct, subsref(sub, subStruct)); % % Function SKEL % case 'skeleton' for i = 1:8 bw = bwlookupgpumex(bw, gpuArray(images.internal.lutskel(i))); end % % Function SPUR % case 'spur' %SPUR Remove parasitic spurs. % [C,LUT] = spur(A, numIterations) removes parasitic spurs from % the binary image A that are shorter than numIterations. lut = images.internal.lutspur(); % Start by complementing the image. The lookup table is designed % to remove endpoints in a complemented image, where 0-valued % pixels are considered to be foreground pixels. That way, % because bwlookup assumes that pixels outside the image are 0, % spur removal takes place as if the image were completely % surrounded by foreground pixels. That way, lines that % intersect the edge of the image aren't pruned at the edge. bw = ~bw; % Identify all end points. These form the entire set of % pixels that can be removed in this iteration. However, % some of these points may not be removed. endPoints = bwlookupgpumex(bw, gpuArray(images.internal.lutspur())); % Remove end points in the first field. %bw(1:2:end, 1:2:end) = xor(bw(1:2:end, 1:2:end), ... % endPoints(1:2:end, 1:2:end)); subStruct.type = '()'; subStruct.subs = {1:2:size(bw,1), 1:2:size(bw,2)}; ff = xor(subsref(bw, subStruct), subsref(endPoints, subStruct)); bw = subsasgn(bw, subStruct, ff); % In the second field, remove any of the original end points % that are still end points. newEndPoints = endPoints & bwlookupgpumex(bw, gpuArray(lut)); %bw(1:2:end, 2:2:end) = xor(bw(1:2:end, 2:2:end), ... % newEndPoints(1:2:end, 2:2:end)); subStruct.type = '()'; subStruct.subs = {1:2:size(bw,1), 2:2:size(bw,2)}; ff = xor(subsref(bw, subStruct), subsref(newEndPoints, subStruct)); bw = subsasgn(bw, subStruct, ff); % In the third field, remove any of the original end points % that are still end points. newEndPoints = endPoints & bwlookupgpumex(bw, gpuArray(lut)); %bw(2:2:end, 1:2:end) = xor(bw(2:2:end, 1:2:end), ... % newEndPoints(2:2:end, 1:2:end)); subStruct.type = '()'; subStruct.subs = {2:2:size(bw,1), 1:2:size(bw,2)}; ff = xor(subsref(bw, subStruct), subsref(newEndPoints, subStruct)); bw = subsasgn(bw, subStruct, ff); % In the fourth field, remove any of the original end points % that are still end points. newEndPoints = endPoints & bwlookupgpumex(bw, gpuArray(lut)); %bw(2:2:end, 2:2:end) = xor(bw(2:2:end, 2:2:end), ... % newEndPoints(2:2:end, 2:2:end)); subStruct.type = '()'; subStruct.subs = {2:2:size(bw,1), 2:2:size(bw,2)}; ff = xor(subsref(bw, subStruct), subsref(newEndPoints, subStruct)); bw = subsasgn(bw, subStruct, ff); % Now that we're finished, we need to complement the image once % more. bw = ~bw; % % Function THIN % case 'thin' % Louisa Lam, Seong-Whan Lee, and Ching Y. Wuen, "Thinning Methodologies-A % Comprehensive Survey," IEEE TrPAMI, vol. 14, no. 9, pp. 869-885, 1992. The % algorithm is described at the bottom of the first column and the top of the % second column on page 879. lut1 = images.internal.lutthin1(); image_iter1 = bwlookupgpumex(bw, gpuArray(lut1)); lut2 = images.internal.lutthin2(); bw = bwlookupgpumex(image_iter1, gpuArray(lut2)); % % Function TOPHAT % case 'tophat' bwe = bwlookupgpumex(bw,gpuArray(images.internal.luterode())); bwd = bwlookupgpumex(bwe,gpuArray(images.internal.lutdilate())); bw = bw&~bwd; % % Function THICKEN % case 'thicken' % Isolated pixels are going to need a "jump-start" to get % them going; otherwise, they won't "thicken". % First, identify the isolated pixels. iso = bwlookupgpumex(bw, gpuArray(images.internal.lutiso())); if (any(any(iso(:)))) % Identify possible pixels to maybe change to one. growMaybe = bwlookupgpumex(iso, gpuArray(images.internal.lutdilate())); % Identify pixel locations in the original image % with only one on pixel in the 3-by-3 neighborhood. oneNeighbor = bwlookupgpumex(bw, gpuArray(images.internal.lutsingle())); % If a pixel is adjacent to an isolated pixel, *and* it % doesn't also have another neighbor, set it to one. bw = bw | (oneNeighbor & growMaybe); end % Create a padded logical array [m,n] = size(bw); m = m+4; n = n+4; c = true([m,n], 'like', bw); %c(3:(m-2),3:(n-2)) = ~bw; subStruct.type = '()'; subStruct.subs = {3:(m-2), 3:(n-2)}; c = subsasgn(c, subStruct, ~bw); % thin lut1 = images.internal.lutthin1(); image_iter1 = bwlookupgpumex(c, gpuArray(lut1)); lut2 = images.internal.lutthin2(); cc = bwlookupgpumex(image_iter1, gpuArray(lut2)); % diag lutd = images.internal.lutdiag(); d = bwlookupgpumex(cc, gpuArray(lutd)); c = (c & ~cc & d) | cc; %c(1:m, 1:2) = true; subStruct.type = '()'; subStruct.subs = {1:m, 1:2}; c = subsasgn(c, subStruct, true); %c(1:m, (n-1):n) = true; subStruct.type = '()'; subStruct.subs = {1:m, (n-1):n}; c = subsasgn(c, subStruct, true); %c(1:2, 1:n) = true; subStruct.type = '()'; subStruct.subs = {1:2, 1:n}; c = subsasgn(c, subStruct, true); %c((m-1):m, 1:n) = true; subStruct.type = '()'; subStruct.subs = {(m-1):m, 1:n}; c = subsasgn(c, subStruct, true); %c = ~c(3:(m-2),3:(n-2)); subStruct.type = '()'; subStruct.subs = {3:(m-2), 3:(n-2)}; c = subsref(c, subStruct); c = ~c; bw = c; otherwise error(message('images:bwmorph:unknownOperation',opStr)); end end
github
wangsuyuan/Imageprocesingtoobox-master
imgradient.m
.m
Imageprocesingtoobox-master/@gpuArray/imgradient.m
6,769
utf_8
d569bf9873ebf2e6d435c7558ab2ae1c
function [Gmag, Gdir] = imgradient(varargin) %IMGRADIENT Find the gradient magnitude and direction of an image. % [Gmag, Gdir] = IMGRADIENT(I) takes a grayscale or binary gpuArray image % I as input and returns the gradient magnitude, Gmag, and the gradient % direction, Gdir as gpuArray's. Gmag and Gdir are the same size as the % input image I. Gdir contains angles in degrees within the range [-180 % 180] measured counterclockwise from the positive X axis (X axis points % in the direction of increasing column subscripts). % % [Gmag, Gdir] = IMGRADIENT(I, METHOD) calculates the gradient magnitude % and direction using the specified METHOD. Supported METHODs are: % % 'Sobel' : Sobel gradient operator (default) % % 'Prewitt' : Prewitt gradient operator % % 'CentralDifference' : Central difference gradient dI/dx = (I(x+1)- I(x-1))/ 2 % % 'IntermediateDifference': Intermediate difference gradient dI/dx = I(x+1) - I(x) % % 'Roberts' : Roberts gradient operator % % [Gmag, Gdir] = IMGRADIENT(Gx, Gy) calculates the gradient magnitude and % direction from the directional gradients along the X axis, Gx, and % Y axis, Gy, such as that returned by IMGRADIENTXY. X axis points in the % direction of increasing column subscripts and Y axis points in the % direction of increasing row subscripts. % % Class Support % ------------- % The input gpuArray image I and the input directional gradients Gx and % Gy can be numeric or logical two-dimensional matrices. Both Gmag and % Gdir are of underlying class double in all cases, except when the input % gpuArray image I or either one or both of the directional gradients Gx % and Gy is of underlying class single. In that case Gmag and Gdir will % be of class single. % % Notes % ----- % 1. When applying the gradient operator at the boundaries of the image, % values outside the bounds of the image are assumed to equal the % nearest image border value. This is similar to the 'replicate' % boundary option in IMFILTER. % % Example 1 % --------- % This example computes and displays the gradient magnitude and direction % of the image coins.png using Prewitt's gradient operator. % % I = gpuArray(imread('coins.png')); % imshow(I) % % [Gmag, Gdir] = imgradient(I,'prewitt'); % % figure, imshow(Gmag, []), title('Gradient magnitude') % figure, imshow(Gdir, []), title('Gradient direction') % % Example 2 % --------- % This example computes and displays both the directional gradients and the % gradient magnitude and gradient direction for the image coins.png. % % I = gpuArray(imread('coins.png')); % imshow(I) % % [Gx, Gy] = imgradientxy(I); % [Gmag, Gdir] = imgradient(Gx, Gy); % % figure, imshow(Gmag, []), title('Gradient magnitude') % figure, imshow(Gdir, []), title('Gradient direction') % figure, imshow(Gx, []), title('Directional gradient: X axis') % figure, imshow(Gy, []), title('Directional gradient: Y axis') % % See also GPUARRAY/EDGE, FSPECIAL, GPUARRAY/IMGRADIENTXY, GPUARRAY. % Copyright 2013 The MathWorks, Inc. narginchk(1,2); [I, Gx, Gy, method] = parse_inputs(varargin{:}); % Compute directional gradients if (isempty(I)) % Gx, Gy are given as inputs if ~isfloat(Gx) Gx = double(Gx); end if ~isfloat(Gy) Gy = double(Gy); end else % If Gx, Gy not given, compute them. For all others except Roberts % method, use IMGRADIENTXY to compute Gx and Gy. if (strcmpi(method,'roberts')) if ~isfloat(I) I = double(I); end Gx = imfilter(I,[1 0; 0 -1],'replicate'); Gy = imfilter(I,[0 1; -1 0],'replicate'); else [Gx, Gy] = imgradientxy(I,method); end end % Compute gradient direction and magnitude if (nargout <= 1) Gmag = hypot(Gx,Gy); else toradian = 180/pi; % up-level indexing if (strcmpi(method,'roberts')) % For pixels with zero gradient (both Gx and Gy zero), Gdir is set % to 0. Compute direction only for pixels with non-zero gradient. % arrayfun is used to leverage element-wise computation speed-up. % up-level indexing pibyfour = pi/4; twopi = 2*pi; pii = pi; [Gmag,Gdir] = arrayfun(@computeDirectionAndMagnitudeGradientRoberts,Gx,Gy); else [Gmag,Gdir] = arrayfun(@computeDirectionAndMagnitudeGradient,Gx,Gy); end end % Nested function to compute gradient magnitude and direction for % 'roberts'. function [gmag,gdir] = computeDirectionAndMagnitudeGradientRoberts(gx,gy) if gx==0 && gy==0 gdir = 0; else gdir = atan2(gy,-gx) - pibyfour; if gdir < -pii gdir = gdir + twopi; end gdir = gdir*toradian; end gmag = hypot(gx,gy); end % Nested function to compute gradient magnitude and direction for % 'sobel' and 'prewitt'. function [gmag,gdir] = computeDirectionAndMagnitudeGradient(gx,gy) gdir = atan2(-gy,gx)*toradian; gmag = hypot(gx,gy); end end %====================================================================== function [I, Gx, Gy, method] = parse_inputs(varargin) methodstrings = {'sobel','prewitt','roberts','centraldifference', ... 'intermediatedifference'}; I = []; Gx = []; Gy = []; method = 'sobel'; % Default method if (nargin == 1) I = gpuArray( varargin{1} ); hValidateAttributes(I,... {'logical','uint8','int8','uint16','int16','uint32','int32','single','double'}, ... {'2d','real'},mfilename,'I',1); else % (nargin == 2) if ischar(varargin{2}) I = gpuArray( varargin{1} ); hValidateAttributes(I,... {'logical','uint8','int8','uint16','int16','uint32','int32','single','double'}, ... {'2d','real'},mfilename,'I',1); method = validatestring(varargin{2}, methodstrings, ... mfilename, 'Method', 2); else Gx = gpuArray( varargin{1} ); Gy = gpuArray( varargin{2} ); hValidateAttributes(Gx,... {'logical','uint8','int8','uint16','int16','uint32','int32','single','double'}, ... {'2d','real'},mfilename,'Gx',1); hValidateAttributes(Gy,... {'logical','uint8','int8','uint16','int16','uint32','int32','single','double'}, ... {'2d','real'},mfilename,'Gy',2); if (~isequal(size(Gx),size(Gy))) error(message('images:validate:unequalSizeMatrices','Gx','Gy')); end end end end %----------------------------------------------------------------------
github
wangsuyuan/Imageprocesingtoobox-master
histeq.m
.m
Imageprocesingtoobox-master/@gpuArray/histeq.m
7,854
utf_8
ae69fd5e7b0c95431671b9653bb91967
function [out,T] = histeq(varargin) %HISTEQ Enhance contrast using histogram equalization. % HISTEQ enhances the contrast of images by transforming the values in an % intensity image so that the histogram of the output image approximately % matches a specified histogram. % % J = HISTEQ(I,HGRAM) transforms the gpuArray intensity image I so that % the histogram of the output gpuArray image J with length(HGRAM) bins % approximately matches HGRAM. The gpuArray vector HGRAM should contain % integer counts for equally spaced bins with intensity values in the % appropriate range: [0,1] for images of class double or single, [0,255] % for images of class uint8, [0,65535] for images of class uint16, and % [-32768, 32767] for images of class int16. HISTEQ automatically scales % HGRAM so that sum(HGRAM) = NUMEL(I). The histogram of J will better % match HGRAM when length(HGRAM) is much smaller than the number of % discrete levels in I. % % J = HISTEQ(I,N) transforms the gpuArray intensity image I, returning in % J a gpuArray intensity image with N discrete levels. A roughly equal % number of pixels is mapped to each of the N levels in J, so that the % histogram of J is approximately flat. (The histogram of J is flatter % when N is much smaller than the number of discrete levels in I.) The % default value for N is 64. % % [J,T] = HISTEQ(I) returns the gray scale transformation that maps gray % levels in the intensity image I to gray levels in J. % % Class Support % ------------- % For syntaxes that include a gpuArray intensity image I as input, I can % be uint8, uint16, int16, double or single. The output gpuArray image J % has the same class as I. % % Also, the optional output T (the gray level transform) is always a % gpuArray of class double. % % Example % ------- % Enhance the contrast of an intensity image using histogram % equalization. % % I = gpuArray(imread('tire.tif')); % J = histeq(I); % figure, imshow(I), figure, imshow(J) % % See also ADAPTHISTEQ, BRIGHTEN, GPUARRAY/IMADJUST, GPUARRAY/IMHIST, % IMHISTMATCH, GPUARRAY. % Copyright 2013 The MathWorks, Inc. narginchk(1,2); nargoutchk(0,2); im = varargin{1}; %Dispatch to CPU if ~isa(im,'gpuArray') args = gatherIfNecessary(varargin{:}); switch nargout case 0 histeq(args{:}); return; case 1 out = histeq(args{:}); return; case 2 [out,T] = histeq(args{:}); return; end end %Check image hValidateAttributes(im,... {'uint8','uint16','int16','single','double'}, ... {'real','2d'},mfilename,'I',1); nLevelsIn = 256; %Number of levels used in computing histogram over %input image. if nargin == 1 %HISTEQ(I) nLevelsSpec = 64; %Default number of levels for histogram equalization. hgramSpec = gpuArray.ones(nLevelsSpec,1)*(numel(im)/nLevelsSpec); elseif nargin == 2 if isscalar(varargin{2}) %HISTEQ(I,N) nLevelsSpec = gather(varargin{2}); validateattributes(nLevelsSpec,{'single','double'},... {'nonsparse','integer','real','positive','scalar'},... mfilename,'N',2); hgramSpec = gpuArray.ones(nLevelsSpec,1)*(numel(im)/nLevelsSpec); else %HISTEQ(I,HGRAM) hgramSpec = varargin{2}; nLevelsSpec = numel(hgramSpec); if isa(hgramSpec,'gpuArray') hValidateAttributes(hgramSpec,... {'single','double'},... {'real','vector','nonempty'},mfilename,'hgram',2); else validateattributes(hgramSpec,... {'single','double'},... {'real','nonsparse','vector','nonempty'},... mfilename,'hgram',2); end %Convert hgram to a column vector. if ~iscolumn(hgramSpec) hgramSpec = hgramSpec'; end %Normalize hgram so sum(hgram)=numel(im) hgramSpec = hgramSpec*(numel(im)/sum(hgramSpec)); end end classChanged = false; if strcmp(classUnderlying(im),'int16') classChanged = true; im = im2uint16(im); end %Compute imput image histogram and CDF. hgramIn = (imhist(im,nLevelsIn))'; cumIn = cumsum(hgramIn); T = createTransformationToIntensityImage(im,hgramSpec,nLevelsSpec,nLevelsIn,hgramIn,cumIn); imout = applyTransformation(im,T); if classChanged imout = im2int16(imout); end if nargout == 0 imshow(imout); return; else out = imout; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function T = createTransformationToIntensityImage(a,hgramSpec,nSpec,nIn,hgramIn,cumIn) %Compute the gray-level transformation needed to match histogram of input %image hgramIn with specified histogram hgramSpec. num_a = numel(a); cumSpec = cumsum(hgramSpec); tol_val = num_a*sqrt(eps); %hgramIn(1)=0,hgramIn(end)=0; hgramIn = subsasgn(hgramIn,substruct('()',{[1 nIn]}),0); if nSpec~=nIn % Rely on arrayfun to do a repmat-like expansion. err = arrayfun(@computeTransformation,cumSpec,cumIn,hgramIn); else % Do the repmat ourselves when m==n err = arrayfun(@computeTransformation,repmat(cumSpec,1,nSpec),cumIn,hgramIn); end [~,T] = min(err); T = (T-1)/(nSpec-1); %Nested function to compute Transformation matrix. function e = computeTransformation(cd,c,t) e = cd-c + t/2; if e < -tol_val e = num_a; end end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function out = applyTransformation(im,T) %Apply gray-level transformation defined in T to im. classname = classUnderlying(im); nLevels = 255; switch classname case 'uint8' scale = nLevels / 255; if nLevels == 255 out = arrayfun(@grayxformUint8,im); else out = arrayfun(@grayxformUint8Scale,im); end case 'uint16' scale = nLevels / 65535; if nLevels == 65535 out = arrayfun(@grayxformUint16,im); else out = arrayfun(@grayxformUint16Scale,im); end case 'single' out = arrayfun(@grayxformSingleScale,im); case 'double' out = arrayfun(@grayxformDoubleScale,im); otherwise error(message('images:grayxform:unsupportedInputClass')); end % Nested functions for pixel-wise computation. function pix_out = grayxformUint8(pix_in) %GRAYXFORMUINT8 pixel-wise mapping for uint8 images with standard %mapping. pix_out = uint8(255.0*T(uint32(pix_in)+1)); end function pix_out = grayxformUint16(pix_in) %GRAYXFORMUINT16 pixel-wise mapping for uint16 images with standard %mapping. pix_out = uint16(65535.0*T(uint32(pix_in)+1)); end function pix_out = grayxformUint8Scale(pix_in) %GRAYXFORMUINT8SCALE general pixel-wise mapping for uint8 images. index = ceil(scale*double(pix_in) + 0.5); pix_out = uint8( 255.0*T(index) ); end function pix_out = grayxformUint16Scale(pix_in) %GRAYXFORMUINT8SCALE general pixel-wise mapping for uint16 images. index = ceil(scale*double(pix_in) + 0.5); pix_out = uint16( 65535.0*T(index) ); end function pix_out = grayxformDoubleScale(pix_in) %GRAYXFORMDOUBLESCALE general pixel-wise mapping for double images. if pix_in>=0 && pix_in<=1 index = floor(pix_in*nLevels+.5)+1; pix_out = T(index); elseif pix_in >1 pix_out = T(nLevels+1); else pix_out = T(1); end end function pix_out = grayxformSingleScale(pix_in) %GRAYXFORMSINGLESCALE general pixel-wise mapping for single images. if pix_in>=0 && pix_in<=1 index = floor(pix_in*nLevels+.5)+1; pix_out = single(T(index)); elseif pix_in >1 pix_out = single(T(nLevels+1)); else pix_out = single(T(1)); end end end
github
wangsuyuan/Imageprocesingtoobox-master
stretchlim.m
.m
Imageprocesingtoobox-master/@gpuArray/stretchlim.m
3,803
utf_8
092c68e2e1f03b7f2edd0bef10399c08
function lowhigh = stretchlim(varargin) %STRETCHLIM Find limits to contrast stretch a gpuArray image. % LOW_HIGH = STRETCHLIM(I,TOL) returns a pair of gray values that can be % used by IMADJUST to increase the contrast of a gpuArray image. % % TOL = [LOW_FRACT HIGH_FRACT] specifies the fraction of gpuArray image to % saturate at low and high pixel values. % % If TOL is a scalar, TOL = LOW_FRACT, and HIGH_FRACT = 1 - LOW_FRACT, % which saturates equal fractions at low and high pixel values. % % If you omit the argument, TOL defaults to [0.01 0.99], saturating 2%. % % If TOL = 0, LOW_HIGH = [min(I(:)); max(I(:))]. % % LOW_HIGH = STRETCHLIM(RGB,TOL) returns a 2-by-3 matrix of pixel value % pairs to saturate each plane of the RGB image. TOL specifies the same % fractions of saturation for each plane. % % Class Support % ------------- % The input image can be uint8, uint16, int16, double, or single, and must % be real and nonsparse. The output limits are double and have values % between 0 and 1. % % Note % ---- % If TOL is too big, such that no pixels would be left after saturating % low and high pixel values, then STRETCHLIM returns [0; 1]. % % Example % ------- % I = gpuArray(imread('pout.tif')); % J = imadjust(I,stretchlim(I),[]); % figure, imshow(I), figure, imshow(J) % % See also BRIGHTEN, DECORRSTRETCH, GPUARRAY/HISTEQ, GPUARRAY/IMADJUST. % Copyright 2013 The MathWorks, Inc. if ~isa(varargin{1},'gpuArray') || strcmp(classUnderlying(varargin{1}),'uint8') % Dispatch to CPU args = gatherIfNecessary(varargin{:}); lowhigh = gpuArray(stretchlim(args{:})); return; end [img,tol] = ParseInputs(varargin{:}); if strcmp(classUnderlying(img),'uint8') nbins = 256; else nbins = 65536; end tol_low = tol(1); tol_high = tol(2); p = size(img,3); if tol_low < tol_high ilowhigh = gpuArray.zeros(2,p); for i = 1:p % Find limits, one plane at a time sIdx.type = '()'; sIdx.subs = {':',':',i}; N = imhistgpumex(subsref(img,sIdx),nbins); cdf = cumsum(N)/sum(N); %cumulative distribution function ilow = find(cdf > tol_low, 1, 'first'); ihigh = find(cdf >= tol_high, 1, 'first'); lhIdx.type = '()'; lhIdx.subs = {':',i}; if ilow == ihigh % this could happen if img is flat ilowhigh = subsasgn(ilowhigh,lhIdx, [1;nbins]); else ilowhigh = subsasgn(ilowhigh,lhIdx, [ilow; ihigh]); end end lowhigh = (ilowhigh - 1)/(nbins-1); % convert to range [0 1] else % tol_low >= tol_high, this tolerance does not make sense. For example, if % the tolerance is .5 then no pixels would be left after saturating % low and high pixel values. In all of these cases, STRETCHLIM % returns [0; 1]. See gecks 278249 and 235648. lowhigh = repmat(gpuArray([0;1]),1,p); end %----------------------------------------------------------------------------- function [img,tol] = ParseInputs(varargin) narginchk(1, 2); img = varargin{1}; hValidateAttributes(img,... {'uint8', 'uint16', 'double', 'int16', 'single'},... {'real'},mfilename, 'I or RGB', 1); if (ndims(img) > 3) error(message('images:stretchlim:dimTooHigh')) end tol = [.01 .99]; %default if nargin == 2 tol = gather(varargin{2}); switch numel(tol) case 1 tol(2) = 1 - tol; case 2 if (tol(1) >= tol(2)) error(message('images:stretchlim:invalidTolOrder')) end otherwise error(message('images:stretchlim:invalidTolSize')) end end if ( any(tol < 0) || any(tol > 1) || any(isnan(tol)) ) error(message('images:stretchlim:tolOutOfRange')) end
github
wangsuyuan/Imageprocesingtoobox-master
imfill.m
.m
Imageprocesingtoobox-master/@gpuArray/imfill.m
9,187
utf_8
63688d92d55590f72ada05025b677cb1
function [I2,locations] = imfill(varargin) %IMFILL Fill image regions and holes. % BW2 = IMFILL(BW1,LOCATIONS) performs a flood-fill operation on % background pixels of the 2-D input binary gpuArray image BW1, starting % from the points specified in LOCATIONS. LOCATIONS can be a P-by-1 % vector, in which case it contains the linear indices of the starting % locations. LOCATIONS can also be a P-by-2 matrix, in which case each % row contains the array indices of one of the starting locations. % % BW2 = IMFILL(BW1,'holes') fills holes in the 2-D binary gpuArray image, % BW1. A hole is a set of background pixels that cannot be reached by % filling in the background from the edge of the image. % % I2 = IMFILL(I1) fills holes in an 2-D intensity gpuArray image, I1. In % this case a hole is an area of dark pixels surrounded by lighter % pixels. % % Specifying Connectivity % ----------------------- % By default, IMFILL uses 4-connected background neighbors for the 2-D % inputs. You can override the default connectivity with these syntaxes: % % BW2 = IMFILL(BW1,LOCATIONS,CONN) % BW2 = IMFILL(BW1,CONN,'holes') % I2 = IMFILL(I1,CONN) % % CONN may have the following scalar values: % % 4 two-dimensional four-connected neighborhood % 8 two-dimensional eight-connected neighborhood % % Performance Note % ----------------------- % With IMFILL computations on the GPU, better performance can be % achieved with syntaxes where the LOCATIONS input is used: % % BW2 = IMFILL(BW1,LOCATIONS) % BW2 = IMFILL(BW1,LOCATIONS,CONN) % % Interactive Use % ----------------------- % Interactive syntaxes are not supported on the GPU: % % BW2 = IMFILL(BW1) % [BW2,LOCATIONS] = IMFILL(BW1) % BW2 = IMFILL(BW1,0,CONN) % % Class Support % ------------- % The input gpuArray image can have its underlying class being logical or % numeric (excluding uint64 or int64), and it must be real and 2-D. The % output image has the same class as the input image. % % Examples % -------- % Fill in the background of a binary gpuArray image from a specified % starting location: % % BW1 = logical([1 0 0 0 0 0 0 0 % 1 1 1 1 1 0 0 0 % 1 0 0 0 1 0 1 0 % 1 0 0 0 1 1 1 0 % 1 1 1 1 0 1 1 1 % 1 0 0 1 1 0 1 0 % 1 0 0 0 1 0 1 0 % 1 0 0 0 1 1 1 0]); % BW1 = gpuArray(BW1); % BW2 = imfill(BW1,[3 3],8) % % Fill in the holes of a binary gpuArray image: % % BW4 = gpuArray(im2bw(imread('coins.png'))); % BW5 = imfill(BW4,'holes'); % figure, imshow(BW4), figure, imshow(BW5) % % Fill in the holes of an intensity gpuArray image: % % I = gpuArray(imread('tire.tif')); % I2 = imfill(I); % figure, imshow(I), figure, imshow(I2) % % See also BWSELECT, GPUARRAY/IMRECONSTRUCT, ROIFILL. % Copyright 2013 The MathWorks, Inc. % Grandfathered syntaxes: % IMFILL(I1,'holes') - no longer necessary to use 'holes' % IMFILL(I1,CONN,'holes') - no longer necessary to use 'holes' % Testing notes % ============= % I - real, full, nonsparse, numeric array, 2-d % - Infs OK % - NaNs not allowed % % CONN - valid 2-d min and max connectivity specifier % % LOCATIONS - can be either a P-by-1 double vector containing % valid linear indices into the input image, or a % P-by-ndims(I) array. In the second case, each row % of LOCATIONS must contain a set of valid array indices % into the input image. % % 'holes' - match is case-insensitive; partial match allowed. % % CPU dispatch if necessary if ~isa(varargin{1}, 'gpuArray') args = gatherIfNecessary(varargin{:}); [I2,locations] = imfill(args{:}); return; end [I,locations,conn,do_fillholes] = parse_inputs(varargin{:}); % Return now if no hole to fill if isempty(I) || (~do_fillholes && isempty(locations)) I2 = I; return end if do_fillholes if islogical(I) mask = uint8(I); else mask = I; end mask = padarray(mask, ones(1,ndims(mask)), -Inf, 'both'); mask = imcomplement(mask); marker = mask; idx = cell(1,ndims(I)); for k = 1:ndims(I) idx{k} = 2:(size(marker,k) - 1); end sIdx.type = '()'; sIdx.subs = idx; marker = subsasgn(marker,sIdx,cast(-Inf, 'like', marker)); I2 = imreconstruct(marker, mask, conn); I2 = imcomplement(I2); I2 = subsref(I2,sIdx); if islogical(I) I2 = logical(I2); end else mask = imcomplement(I); marker = gpuArray.false(size(mask)); sIdx.type = '()'; sIdx.subs = {locations}; marker = subsasgn(marker, sIdx, subsref(mask, sIdx)); marker = imreconstruct(marker, mask, conn); I2 = I | marker; end %%% %%% Subfunction ParseInputs %%% function [IM,locations,conn,do_fillholes] = parse_inputs(varargin) narginchk(1,3); IM = varargin{1}; do_interactive = false; do_fillholes = false; conn = 4; % default to minimal 2-D connectivity do_conn_check = false; locations = []; do_location_check = false; hValidateAttributes(IM,... {'logical','uint8','int8','uint16','int16','uint32','int32','single','double'},... {'real', '2d', 'nonnan'},mfilename,'I1 or BW1',1); switch nargin case 1 if islogical(IM) % IMFILL(BW1) do_interactive = true; else % IMFILL(I1) do_fillholes = true; end case 2 if islogical(IM) if ischar(varargin{2}) % IMFILL(BW1, 'holes') validatestring(varargin{2}, {'holes'}, mfilename, 'OPTION', 2); do_fillholes = true; else % IMFILL(BW1, LOCATIONS) locations = varargin{2}; do_location_check = true; end else if ischar(varargin{2}) % IMFILL(I1, 'holes') validatestring(varargin{2}, {'holes'}, mfilename, 'OPTION', 2); do_fillholes = true; else % IMFILL(I1, CONN) conn = varargin{2}; do_conn_check = true; do_fillholes = true; end end case 3 if islogical(IM) if ischar(varargin{3}) % IMFILL(BW1,CONN,'holes') validatestring(varargin{3}, {'holes'}, mfilename, 'OPTION', 3); do_fillholes = true; conn = varargin{2}; do_conn_check = true; else if isequal(varargin{2}, 0) % IMFILL(BW1,0,CONN) do_interactive = true; else % IMFILL(BW1,LOCATIONS,CONN) locations = varargin{2}; do_location_check = true; conn = varargin{3}; do_conn_check = true; end end else % IMFILL(I1,CONN,'holes') validatestring(varargin{3}, {'holes'}, mfilename, 'OPTION', 3); do_fillholes = true; conn = varargin{2}; do_conn_check = true; end end if do_conn_check % Preprocess conn conn = gather(conn); if isscalar(conn) if (conn~=4 && conn~=8) error(message('images:imfill:unsupportedConnForGPU')); end else if isequal(conn,conndef(2,'min')) conn = 4; elseif isequal(conn,conndef(2,'max')) conn = 8; else error(message('images:imfill:unsupportedConnForGPU')); end end else % Default to maximal 2D connectivity conn = 4; end if do_location_check % locations are checked on the CPU locations = gather(locations); locations = check_locations(locations, size(IM)); elseif do_interactive error(message('images:imfill:noInteractiveOnGPU')); end % Convert to linear indices if necessary. if ~do_fillholes && (size(locations,2) ~= 1) idx = cell(1,ndims(IM)); for k = 1:ndims(IM) idx{k} = locations(:,k); end locations = sub2ind(size(IM), idx{:}); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function locations = check_locations(locations, image_size) % Checks validity of LOCATIONS. Converts LOCATIONS to linear index % form. Warns if any locations are out of range. validateattributes(locations, {'double'}, {'real' 'positive' 'integer' '2d'}, ... mfilename, 'LOCATIONS', 2); num_dims = length(image_size); if (size(locations,2) ~= 1) && (size(locations,2) ~= num_dims) error(message('images:imfill:badLocationSize', iptnum2ordinal( 2 ))); end if size(locations,2) == 1 bad_pix = (locations < 1) | (locations > prod(image_size)); else bad_pix = zeros(size(locations,1),1); for k = 1:num_dims bad_pix = bad_pix | ((locations(:,k) < 1) | ... (locations(:,k) > image_size(k))); end end if any(bad_pix) warning(message('images:imfill:outOfRange')); locations(bad_pix,:) = []; end
github
wangsuyuan/Imageprocesingtoobox-master
im2uint16.m
.m
Imageprocesingtoobox-master/@gpuArray/im2uint16.m
4,853
utf_8
2c8a1a3f84d6d73ff8553d05927578d8
function u = im2uint16(img, varargin) %IM2UINT16 Convert gpuArray image to 16-bit unsigned integers. % IM2UINT16 takes a gpuArray image as input, and returns a gpuArray image % of underlying class uint16. If the input gpuArray image is of class % uint16, the output gpuArray is identical to it. If the input gpuArray % image is not uint16, IM2UINT16 returns the equivalent gpuArray image of % underlying class uint16, rescaling or offsetting the data as necessary. % % I2 = IM2UINT16(I1) converts the intensity gpuArray image I1 to uint16, % rescaling the data if necessary. % % RGB2 = IM2UINT16(RGB1) converts the truecolor gpuArray image RGB1 to % uint16, rescaling the data if necessary. % % X2 = IM2UINT16(X1,'indexed') converts the indexed gpuArray image X1 to % uint16, offsetting the data if necessary. If X1 is double, then the % maximum value of X1 must be 65536 or less. % % I = IM2UINT16(BW) converts the binary image BW to a uint16 gpuArray % intensity image, changing one-valued elements to 65535. % % Class Support % ------------- % Intensity and truecolor gpuArray images can be uint8, uint16, double, % logical, single, or int16. Indexed images can be uint8, uint16, double % or logical. Binary input images must be logical. The output image is % uint16. % % Example % ------- % I1 = gpuArray(reshape(linspace(0,1,20),[5 4])) % I2 = im2uint16(I1) % % See also GPUARRAY/IM2DOUBLE, GPUARRAY/IM2INT16, GPUARRAY/IM2SINGLE, % GPUARRAY/IM2UINT8, GPUARRAY/UINT16, GPUARRAY. % Copyright 2013 The MathWorks, Inc. %% inputs narginchk(1,2); classIn = classUnderlying(img); hValidateAttributes(img,... {'double','logical','uint8','uint16','int16','single'}, ... {},mfilename,'IMG',1); if(~isreal(img)) warning(message('images:im2uint16:ignoringImaginaryPartOfInput')); img = real(img); end if nargin == 2 validatestring(varargin{1}, {'indexed'}, mfilename, 'type', 2); end %% process if strcmp(classIn, 'uint16') u = img; elseif islogical(img) u = uint16(img) * 65535; elseif strcmp(classIn,'int16') if nargin == 1 u = arrayfun(@int16touint16,img); else error(message('images:im2uint16:invalidIndexedImage')) end else %double, single, or uint8 if nargin==1 % intensity image if strcmp(classIn, 'double') u = arrayfun(@grayto16double,img); elseif strcmp(classIn, 'single') u = arrayfun(@grayto16single,img); elseif strcmp(classIn, 'uint8') u = arrayfun(@grayto16uint8,img); end else if strcmp(classIn, 'uint8') u = uint16(img); else % img is double or single s.type = '()'; s.subs = {':'}; if any(max(subsref(img,s)) >= 65537) error(message('images:im2uint16:tooManyColors')) elseif any(min(subsref(img,s)) < 1) error(message('images:im2uint16:invalidIndex')) else u = uint16(img-1); end end end end function b = grayto16uint8(img) %GRAYTO16 Scale and convert grayscale image to uint16. % B = GRAYTO16(A) converts the uint8 array A by scaling the % elements of A by 257 and then casting to uint8. b = bitor(bitshift(uint16(img),8),uint16(img)); function b = grayto16double(img) %GRAYTO16 Scale and convert grayscale image to uint16. % B = GRAYTO16(A) converts the double array A to uint16 by % scaling A by 65535 and then rounding. NaN's in A are converted % to 0. Values in A greater than 1.0 are converted to 65535; % values less than 0.0 are converted to 0. if isnan(img) b = uint16(0); else % uint16() rounds DOUBLE and SINGLE values. No need to add 0.5 as in % grayto16 MEX code img = img * 65535; if img > 65535 img = 65535; elseif img < 0 img = 0; end b = uint16(img); end function b = grayto16single(img) %GRAYTO16 Scale and convert grayscale image to uint16. % B = GRAYTO16(A) converts the double array A to uint16 by % scaling A by 65535 and then rounding. NaN's in A are converted % to 0. Values in A greater than 1.0 are converted to 65535; % values less than 0.0 are converted to 0. if isnan(img) b = uint16(0); else % uint16() rounds DOUBLE and SINGLE values. No need to add 0.5 as in % grayto16 MEX code maxVal = single(65535); minVal = single(0); img = img * maxVal; if img > maxVal img = maxVal; elseif img < minVal img = minVal; end b = uint16(img); end function z = int16touint16(img) %INT16TOUINT16 converts int16 to uint16 % Z = INT16TOUINT16(I) converts int16 data (range = -32768 to 32767) to uint16 % data (range = 0 to 65535). z = uint16(int32(img) + 32768);
github
wangsuyuan/Imageprocesingtoobox-master
std2.m
.m
Imageprocesingtoobox-master/@gpuArray/std2.m
1,043
utf_8
13e5093bb1ad70d0e551119e820649a5
function s = std2(a) %STD2 Standard deviation of matrix elements. % B = STD2(A) computes the standard deviation of the values in % gpuArray A. % % Class Support % ------------- % A can be a numeric or logical gpuArray. B is a scalar double gpuArray. % % Example % ------- % I = gpuArray(imread('liftingbody.png')); % val = std2(I) % % See also GPUARRAY/CORR2, MEAN2, MEAN, STD, GPUARRAY. % Copyright 2013 The MathWorks, Inc. if isempty(a) s = gpuArray(NaN); return; end n = numel(a); % convert to column-vector. a = reshape(a,n,1); % set up normalization factor and image mean. norm_factor = 1/(max(n-1,1)); mean_a = sum(a,'double')/n; a = arrayfun(@computeSquaredDifferences,a); % std is sqrt of sum of normalized square difference from mean. s = sqrt(norm_factor*sum(a)); %nested function to allow up-level indexing of mean. function aout = computeSquaredDifferences(ain) % compute squared difference from mean. aout = (abs(double(ain)-mean_a))^2; % abs guarantees a real result end end
github
wangsuyuan/Imageprocesingtoobox-master
edge.m
.m
Imageprocesingtoobox-master/@gpuArray/edge.m
13,182
utf_8
a4f38fd1dac4f529479a1b113102769a
function [eout,thresh,gv_45,gh_135] = edge(varargin) %EDGE Find edges in intensity image. % EDGE takes an intensity or a binary gpuArray image I as its input, and % returns a binary gpuArray image BW of the same size as I, with 1's % where the function finds edges in I and 0's elsewhere. % % EDGE supports five different edge-finding methods: % % The Sobel method finds edges using the Sobel approximation to the % derivative. It returns edges at those points where the gradient of % I is maximum. % % The Prewitt method finds edges using the Prewitt approximation to % the derivative. It returns edges at those points where the gradient % of I is maximum. % % The Roberts method finds edges using the Roberts approximation to % the derivative. It returns edges at those points where the gradient % of I is maximum. % % The Laplacian of Gaussian method finds edges by looking for zero % crossings after filtering I with a Laplacian of Gaussian filter. % % The zero-cross method finds edges by looking for zero crossings % after filtering I with a filter you specify. % % The parameters you can supply differ depending on the method you % specify. If you do not specify a method, EDGE uses the Sobel method. % % Sobel Method % ------------ % BW = EDGE(I,'sobel') specifies the Sobel method. % % BW = EDGE(I,'sobel',THRESH) specifies the sensitivity threshold for % the Sobel method. EDGE ignores all edges that are not stronger than % THRESH. If you do not specify THRESH, or if THRESH is empty ([]), % EDGE chooses the value automatically. % % BW = EDGE(I,'sobel',THRESH,DIRECTION) specifies directionality for the % Sobel method. DIRECTION is a string specifying whether to look for % 'horizontal' or 'vertical' edges, or 'both' (the default). % % BW = EDGE(I,'sobel',...,OPTIONS) provides an optional string % input. String 'nothinning' speeds up the operation of the algorithm by % skipping the additional edge thinning stage. By default, or when % 'thinning' string is specified, the algorithm applies edge thinning. % % [BW,thresh] = EDGE(I,'sobel',...) returns the threshold value. % % Prewitt Method % -------------- % BW = EDGE(I,'prewitt') specifies the Prewitt method. % % BW = EDGE(I,'prewitt',THRESH) specifies the sensitivity threshold for % the Prewitt method. EDGE ignores all edges that are not stronger than % THRESH. If you do not specify THRESH, or if THRESH is empty ([]), % EDGE chooses the value automatically. % % BW = EDGE(I,'prewitt',THRESH,DIRECTION) specifies directionality for % the Prewitt method. DIRECTION is a string specifying whether to look % for 'horizontal' or 'vertical' edges, or 'both' (the default). % % BW = EDGE(I,'prewitt',...,OPTIONS) provides an optional string % input. String 'nothinning' speeds up the operation of the algorithm by % skipping the additional edge thinning stage. By default, or when % 'thinning' string is specified, the algorithm applies edge thinning. % % [BW,thresh] = EDGE(I,'prewitt',...) returns the threshold value. % % Roberts Method % -------------- % BW = EDGE(I,'roberts') specifies the Roberts method. % % BW = EDGE(I,'roberts',THRESH) specifies the sensitivity threshold for % the Roberts method. EDGE ignores all edges that are not stronger than % THRESH. If you do not specify THRESH, or if THRESH is empty ([]), % EDGE chooses the value automatically. % % BW = EDGE(I,'roberts',...,OPTIONS) provides an optional string % input. String 'nothinning' speeds up the operation of the algorithm by % skipping the additional edge thinning stage. By default, or when % 'thinning' string is specified, the algorithm applies edge thinning. % % [BW,thresh] = EDGE(I,'roberts',...) returns the threshold value. % % Laplacian of Gaussian Method % ---------------------------- % BW = EDGE(I,'log') specifies the Laplacian of Gaussian method. % % BW = EDGE(I,'log',THRESH) specifies the sensitivity threshold for the % Laplacian of Gaussian method. EDGE ignores all edges that are not % stronger than THRESH. If you do not specify THRESH, or if THRESH is % empty ([]), EDGE chooses the value automatically. % % BW = EDGE(I,'log',THRESH,SIGMA) specifies the Laplacian of Gaussian % method, using SIGMA as the standard deviation of the LoG filter. The % default SIGMA is 2; the size of the filter is N-by-N, where % N=CEIL(SIGMA*3)*2+1. % % [BW,thresh] = EDGE(I,'log',...) returns the threshold value. % % Zero-cross Method % ----------------- % BW = EDGE(I,'zerocross',THRESH,H) specifies the zero-cross method, % using the specified filter H. If THRESH is empty ([]), EDGE chooses % the sensitivity threshold automatically. % % [BW,THRESH] = EDGE(I,'zerocross',...) returns the threshold value. % % % Class Support % ------------- % I is a gpuArray. BW is a gpuArray with underlying class logical. % % Remarks % ------- % For the 'log' and 'zerocross' methods, if you specify a % threshold of 0, the output image has closed contours because % it includes all of the zero crossings in the input image. % % Example % ------- % Find the edges of the circuit.tif image using the Prewitt and Canny % methods: % % I = gpuArray(imread('circuit.tif')); % BW1 = edge(I,'prewitt'); % BW2 = edge(I,'sobel'); % figure, imshow(BW1) % figure, imshow(BW2) % % See also FSPECIAL, GPUARRAY/IMGRADIENT, GPUARRAY/IMGRADIENTXY, % GPUARRAY. % Copyright 2013 The MathWorks, Inc. % [BW,thresh,gv,gh] = EDGE(I,'sobel',...) returns vertical and % horizontal edge responses to Sobel gradient operators. You can % also use these expressions to obtain gradient responses: % if ~(isa(I,'double') || isa(I,'single')); I = im2single(I); end % gh = imfilter(I,fspecial('sobel') /8,'replicate'); and % gv = imfilter(I,fspecial('sobel')'/8,'replicate'); % % [BW,thresh,gv,gh] = EDGE(I,'prewitt',...) returns vertical and % horizontal edge responses to Prewitt gradient operators. You can % also use these expressions to obtain gradient responses: % if ~(isa(I,'double') || isa(I,'single')); I = im2single(I); end % gh = imfilter(I,fspecial('prewitt') /6,'replicate'); and % gv = imfilter(I,fspecial('prewitt')'/6,'replicate'); % % [BW,thresh,g45,g135] = EDGE(I,'roberts',...) returns 45 degree and % 135 degree edge responses to Roberts gradient operators. You can % also use these expressions to obtain gradient responses: % if ~(isa(I,'double') || isa(I,'single')); I = im2single(I); end % g45 = imfilter(I,[1 0; 0 -1]/2,'replicate'); and % g135 = imfilter(I,[0 1;-1 0]/2,'replicate'); narginchk(1,5) % Dispatch to CPU if needed if ~isa(varargin{1},'gpuArray') % Gather the inputs. for i = 2 : nargin varargin{i} = gather(varargin{i}); end % Call the CPU implementation switch nargout case 0 edge(varargin{:}); case 1 eout = edge(varargin{:}); case 2 [eout,thresh] = edge(varargin{:}); case 3 [eout,thresh,gv_45] = edge(varargin{:}); case 4 [eout,thresh,gv_45,gh_135] = edge(varargin{:}); end return; end % Parse inputs [a,method,thresh,sigma,thinning,H,kx,ky] = parse_inputs(varargin{:}); % Check that the user specified a valid number of output arguments if ~any(strcmp(method,{'sobel','roberts','prewitt'})) && (nargout>2) error(message('images:edge:tooManyOutputs')); end % Transform to a double precision intensity image if necessary if ~isfloat(a) a = im2single(a); end [m,n] = size(a); if any(strcmp(method, {'log','zerocross'})) % We don't use image blocks here if isempty(H), fsize = ceil(sigma*3) * 2 + 1; % choose an odd fsize > 6*sigma; op = fspecial('log',fsize,sigma); else op = H; end op = op - sum(op(:))/numel(op); % make the op to sum to zero b = imfilter(a,op,'replicate'); if isempty(thresh) thresh = .75*mean2(abs(b)); end % detect zero-crossings by looking for [+-],[-+],[+-]' and [-+]' % transitions in b that are greater than thresh. also look for % [+0-],[-0+],[+0-]' and [-0+]' transitions. e = zerocrossinggpumex(b,gather(thresh)); % to stay consistent with CPU behavior, set boundary pixels to zero. if ~isempty(e) e = subsasgn(e,substruct('()',{1,':'}),gpuArray.false);%e(1 ,: ) = false; e = subsasgn(e,substruct('()',{m,':'}),gpuArray.false);%e(end,: ) = false; e = subsasgn(e,substruct('()',{':',1}),gpuArray.false);%e(: ,1 ) = false; e = subsasgn(e,substruct('()',{':',n}),gpuArray.false);%e(: ,end) = false; end else % one of the easy methods (roberts,sobel,prewitt) if strcmp(method,'sobel') op = fspecial('sobel')/8; % Sobel approximation to derivative x_mask = op'; % gradient in the X direction y_mask = op; scale = 4; % for calculating the automatic threshold isroberts = false; elseif strcmp(method,'prewitt') op = fspecial('prewitt')/6; % Prewitt approximation to derivative x_mask = op'; y_mask = op; scale = 4; isroberts = false; elseif strcmp(method, 'roberts') x_mask = [1 0; 0 -1]/2; % Roberts approximation to diagonal derivative y_mask = [0 1;-1 0]/2; scale = 6; isroberts = true; else error(message('images:edge:invalidEdgeDetectionMethod', method)) end % compute the gradient in x and y direction bx = imfilter(a,x_mask,'replicate'); by = imfilter(a,y_mask,'replicate'); if (nargout > 2) % if gradients are requested gv_45 = bx; gh_135 = by; end % compute the magnitude b = arrayfun(@computegradientmagnitude,bx,by); % determine the threshold; see page 514 of "Digital Imaging Processing" by % William K. Pratt if isempty(thresh), % Determine cutoff based on RMS estimate of noise % Mean of the magnitude squared image is a % value that's roughly proportional to SNR cutoff = scale*mean2(b); thresh = sqrt(cutoff); else % Use relative tolerance specified by the user cutoff = (thresh).^2; end if thinning e = computeedgegpumex(b,bx,by,kx,ky,isroberts,100*eps,gather(cutoff)); else e = b > cutoff; end end if nargout==0, imshow(e); else eout = e; end % nested function to compute pixel-wise gradient magnitude function bmag = computegradientmagnitude(b_x,b_y) bmag = kx*b_x*b_x + ky*b_y*b_y; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Local Function : parse_inputs % function [I,Method,Thresh,Sigma,Thinning,H,kx,ky] = parse_inputs(varargin) % OUTPUTS: % I Image Data % Method Edge detection method % Thresh Threshold value % Sigma standard deviation of Gaussian % H Filter for Zero-crossing detection % kx,ky From Directionality vector I = varargin{1}; hValidateAttributes(I,... {'logical','uint8','int8','uint16','int16','uint32','int32','single','double'},... {'real','2d'},mfilename,'I',1); % Defaults Method = 'sobel'; Direction = 'both'; Thinning = true; methods = {'canny','canny_old','prewitt','sobel','marr-hildreth','log','roberts','zerocross'}; directions = {'both','horizontal','vertical'}; options = {'thinning','nothinning'}; % Now parse the nargin-1 remaining input arguments % First get the strings - we do this because the interpretation of the % rest of the arguments will depend on the method. nonstr = []; % ordered indices of non-string arguments for i = 2:nargin if ischar(varargin{i}) str = lower(varargin{i}); j = find(strcmp(str,methods)); k = find(strcmp(str,directions)); l = find(strcmp(str,options)); if ~isempty(j) Method = methods{j(1)}; if strcmp(Method,'marr-hildreth') error(message('images:removed:syntax','EDGE(I,''marr-hildreth'',...)','EDGE(I,''log'',...)')) end % Canny is not supported on the GPU. if strcmp(Method,'canny') || strcmp(Method,'canny_old') error(message('images:edge:cannyUnsupportedOnGpu', Method)); end elseif ~isempty(k) Direction = directions{k(1)}; elseif ~isempty(l) if strcmp(options{l(1)},'thinning') Thinning = true; else Thinning = false; end else error(message('images:edge:invalidInputString', varargin{ i })) end else % gather if necessary. varargin{i} = gather(varargin{i}); nonstr = [nonstr i]; %#ok<AGROW> end end % Now get the rest of the arguments [Thresh,Sigma,H,kx,ky] = images.internal.parseNonStringInputsEdge(varargin,Method,Direction,nonstr); end
github
wangsuyuan/Imageprocesingtoobox-master
morphopAlgo.m
.m
Imageprocesingtoobox-master/@gpuArray/private/morphopAlgo.m
5,840
utf_8
d007ed841fa1001d56781cac5ae81054
function B = morphopAlgo(A,se,padfull,unpad,op_type) %MORPHOPALGO Algorithmic core for gpuArray image dilation/erosion. Intended %for use with morphopInputParser in functions like IMDILATE, IMERODE, %IMOPEN, IMCLOSE, IMTOPHAT and IMBOTHAT. % Copyright 2013 The MathWorks, Inc. num_strels = length(se); ndims_A = ndims(A); size_A = size(A); centers = zeros(num_strels,2); pad_size = zeros(num_strels,2); dst_size = zeros(num_strels,2); additional_offset = zeros(num_strels,2); % additional offset to account % for effective mask size being % smaller. % Get the center location and neighborhood sizes. for k = 1 : num_strels [centers(k,:),pad_size(k,:)] = getcenterandsize(se(k)); end % Cast pad_val to the input image class pad_val = cast(getPadValue(A,op_type),classUnderlying(A)); if padfull % Pad the input for 'full' option. % Find the array offsets and centers for each structuring element in % the sequence. Use these values to update the extent of the effective % mask and the additional offsets needed. min_extent = zeros(num_strels,2); max_extent = zeros(num_strels,2); for k = 1 : num_strels % Get the array offsets offset_k = getneighbors(se(k)); % This is the upper-left corner of the effective mask. min_offset = min([offset_k;[0 0]]); %include the center % This is the lower-right corner of the effective mask. max_offset = max([offset_k;[0 0]]); %include the center % Find the new extent of the effective mask. min_extent(k,:) = centers(k,:) + min_offset; max_extent(k,:) = centers(k,:) + max_offset; additional_offset(k,:) = pad_size(k,:)-max_extent(k,:); end % Pad the input by the sum of padding needed for each structuring % element. max_pad_size = sum((pad_size-1),1); if numel(max_pad_size) < ndims_A max_pad_size(ndims_A) = 0; end A = constantpaduint8mex(A,max_pad_size,pad_val,'both'); % Compute the destination size for each dilation/erosion output. % Corresponding to each successive structuring element, the destination % size is the previous destination size minus the padding for that % structuing element. The padding needs to be reduced according to the % effective size of the mask. if num_strels>0 dst_size(1,:) = [size(A,1) size(A,2)]-2*(pad_size(1,:)-1)+(max_extent(1,:)-min_extent(1,:)); end for k = 2 : num_strels dst_size(k,:) = dst_size(k-1,:) - 2*(pad_size(k,:)-1) + (max_extent(k,:)-min_extent(k,:)); end else % Pad the input for 'same' option. [max_pad_size, k] = max(pad_size,[],1); prepad_size = centers(k(1),:) - 1; postpad_size = max_pad_size - centers(k(1),:); if numel(prepad_size) < ndims_A prepad_size(ndims_A) = 0; postpad_size(ndims_A) = 0; end A = constantpaduint8mex(A,[prepad_size;postpad_size],pad_val,'both'); dst_size = repmat([size_A(1) size_A(2)],[num_strels,1]); end % Zero-based offset from starting pixel. centers_offset = centers - 1; % Create gpuArray's from the STREL objects mask = cell(1,num_strels); for k = 1 : num_strels mask{k} = gpuArray(cast(getnhood(se(k)),classUnderlying(A))); end % Apply the operation (dilation/erosion) on the image with the sequence of % structuring elements. B = A; if strcmp(op_type,'dilate') for k = 1 : num_strels B = morphmexgpu(B,mask{k},centers_offset(k,:),... additional_offset(k,:),dst_size(k,:),'dilate'); end else for k = 1 : num_strels B = morphmexgpu(B,mask{k},centers_offset(k,:),... additional_offset(k,:),dst_size(k,:),'erode'); end % Special case: If input is logical and atleast one mask has an empty % neighborhood, handle it. if strcmp(classUnderlying(B),'logical') && ... any(arrayfun(@(x) all(~any(getnhood(x))), se)) B = (B~=0); end end % Unpad the image if needed. if unpad % Note: % * This went through the padfull codepath. We crop accordingly. % * Call to SUBSREF needs to be explicit from within @gpuArray % directory. idx = cell(1,ndims_A); sum_centers = zeros(1,2); for k = 1 : num_strels sum_centers = sum_centers + (size(mask{k}) - centers(k,:)); end sum_addoffs = sum(additional_offset,1); for k = 1:2 first = 1 + sum_centers(k) - sum_addoffs(k); last = first + size_A(k) - 1; idx{k} = first:last; end for k = 3:ndims_A idx{k} = ':'; end subscripts.type = '()'; subscripts.subs = idx; B = subsref(B,subscripts); end %-------------------------------------------------------------------------- %========================================================================== function pad_value = getPadValue(A, op_type) % Returns the appropriate pad value, depending on whether we are performing % erosion or dilation, and whether or not A is logical (binary). if strcmp(op_type, 'dilate') pad_value = -Inf; else pad_value = Inf; end if islogical(A) % Use 0s and 1s instead of plus/minus Inf. pad_value = max(min(pad_value, 1), 0); end %-------------------------------------------------------------------------- %========================================================================== function [center,sz] = getcenterandsize(se) % Compute center of the structuring element. sz = size(se.getnhood()); center = floor((sz+1)/2); %--------------------------------------------------------------------------
github
wangsuyuan/Imageprocesingtoobox-master
morphopInputParser.m
.m
Imageprocesingtoobox-master/@gpuArray/private/morphopInputParser.m
3,065
utf_8
7bea034bd4ddfe28d541ef78b5578b38
function [A,se,padfull,unpad,op_type] = morphopInputParser(A,se,op_type,func_name,varargin) %MORPHOPINPUTPARSER Parse and validate inputs to morphology family of %functions and determine padding requirements. Intended for use with %morphopAlgo in functions IMDILATE, IMERODE, IMOPEN, IMCLOSE, IMTOPHAT and %IMBOTHAT. % Copyright 2013 The MathWorks, Inc. narginchk(4,5); % Get required inputs and check for validity. A = checkInputImage(A); se = strelcheck(se,func_name,'SE',2); % Process optional arguments. padopt = processOptionalArguments(func_name,varargin{:}); % Get sequence of structuring elements. se = getsequence(se); % Find conditionals needed to determing padding requirements. num_strels = length(se); strel_is_single = num_strels == 1; output_is_full = strcmp(padopt,'full'); % Check structuring element error conditions. Only 2D, flat structuring % elements are allowed. strel_is_all_2d = true; for k = 1:num_strels if (ndims(getnhood(se(k))) > 2) %#ok<ISMAT> strel_is_all_2d = false; break; end end if ~strel_is_all_2d error(message('images:morphop:gpuStrelNot2D')); end strel_is_all_flat = all(isflat(se)); if ~strel_is_all_flat error(message('images:morphop:gpuStrelNotFlat')); end % Reflect the structuring element if dilating. if strcmp(op_type,'dilate') se = reflect2dFlatStrel(se); else % If a structuring element is empty, pad a zero by reflecting. This is % required because the underlying GPU implementation does not accept empty % neighbohoods. for k = 1:num_strels if isempty(getnhood(se(k))) se(k)=reflect2dFlatStrel(se(k)); end end end % Determine whether padding and unpadding is necessary. % Pad the input when the pad option is'full' or the structuring element is % not single. padfull = output_is_full || (~strel_is_single); % Unpad only if the pad option is 'same' and the structuring element is % not single. unpad = (~strel_is_single) && (~output_is_full); %-------------------------------------------------------------------------- %========================================================================== function A = checkInputImage(A) %Check input image validity % The input image must be a gpuArray holding real data of type UINT8 or % LOGICAL. if ~isreal(A) error(message('images:morphop:gpuImageComplexity')); end if ~(strcmp(classUnderlying(A),'uint8') || strcmp(classUnderlying(A),'logical')) error(message('images:morphop:gpuUnderlyingClassTypeImage')); end %-------------------------------------------------------------------------- %========================================================================== function padopt = processOptionalArguments(func_name, varargin) % Process padding option. % Default value padopt = 'same'; if ~isempty(varargin) allowed_strings = {'same','full'}; padopt = validatestring(varargin{1},allowed_strings, func_name,... 'OPTION',3); end %--------------------------------------------------------------------------
github
wangsuyuan/Imageprocesingtoobox-master
iptcheckmap.m
.m
Imageprocesingtoobox-master/@gpuArray/private/iptcheckmap.m
1,759
utf_8
3366775bec56f6d92f2168538604b0b1
function iptcheckmap(map, function_name, variable_name, argument_position) %IPTCHECKMAP Check validity of colormap. % IPTCHECKMAP(MAP,FUNC_NAME,VAR_NAME,ARG_POS) checks to see if % MAP is a valid MATLAB colormap and issues a formatted error % message if it is invalid. % % FUNC_NAME is a string that specifies the name used in the formatted % error message to identify the function checking the colormap. % % VAR_NAME is a string that specifies the name used in the formatted % error message to identify the argument being checked. % % ARG_POS is a positive integer that indicates the position of % the argument being checked in the function argument list. % IPTCHECKMAP includes this information in the formatted error message. % % Example % ------- % % bad_map = ones(10); % iptcheckmap(bad_map,'func_name','var_name',2) % % See also IPTCHECKHANDLE % Copyright 2013 The MathWorks, Inc. mapClass = classUnderlying(map); if ~strcmp(mapClass,'double') || isempty(map) || ... (~ismatrix(map)) || (size(map,2) ~= 3) || ... issparse(map) compose_error('images:validate:badMapMatrix', upper( function_name ), argument_position, variable_name) end if any(any(map(:) < 0) | any(map(:) > 1))>0 compose_error('images:validate:badMapValues', upper( function_name ), argument_position, variable_name) end %----------------------------------------------------------------------------------- function specific_msg = compose_error(id, function_name, arg_position, variable_name) bad_map_msg = message('images:validate:badMap', upper(function_name), arg_position, variable_name); specific_msg = message(id,bad_map_msg.getString()); ME = MException(id,'%s',specific_msg.getString()); ME.throwAsCaller()
github
wangsuyuan/Imageprocesingtoobox-master
intlut.m
.m
Imageprocesingtoobox-master/@gpuArray/private/intlut.m
2,267
utf_8
42bf30d9a236bfee8fa4717e1f2be9a7
function B = intlut(varargin) %INTLUT Convert integer values using lookup table. % B = INTLUT(A,LUT) converts values in array A based on lookup table % LUT and returns these new values in array B. % % For example, if A is a uint8 vector whose kth element is equal % to alpha, then B(k) is equal to the LUT value corresponding % to alpha, i.e., LUT(alpha+1). % % Class Support % ------------- % A can be uint8, uint16, or int16. If A is uint8, LUT must be % a uint8 vector with 256 elements. If A is uint16 or int16, % LUT must be a vector with 65536 elements that has the same class % as A. B has the same size and class as A. % % Example % ------- % A = uint8([1 2 3 4; 5 6 7 8;9 10 11 12]) % LUT = repmat(uint8([0 150 200 255]),1,64); % B = intlut(A,LUT) % Copyright 2013 The MathWorks, Inc. narginchk(2,2); [A, classA, LUT, ~] = parseInputs(varargin{:}); %% B = LUT(A) if strcmp(classA,'int16') B = arrayfun(@lookupInt16,A); else B = arrayfun(@lookup,A); end %---------------------------------------------------------------------- function out = lookup(img) % 1-based indexing out = LUT(int32(img)+int32(1)); end %---------------------------------------------------------------------- function out = lookupInt16(img) % 1-based indexing % int16 special case for negative index value lookup out = LUT(int32(img)+int32(1)+int32(32768)); end end function [A, classA, LUT, classLUT] = parseInputs(varargin) A = gpuArray(varargin{1}); LUT = gpuArray(varargin{2}); hValidateAttributes(A,... {'uint8','uint16','int16'},... {'real'},mfilename, 'A', 1); hValidateAttributes(LUT,... {'uint8','uint16','int16'},... {'vector','real'},mfilename, 'LUT', 2); classA = classUnderlying(A); classLUT = classUnderlying(LUT); if ~isequal(classA,classLUT) error(message('images:intlut:inputsHaveDifferentClasses')) end if strcmp(classLUT,'uint8') && length(LUT) ~= 256 error(message('images:intlut:wrongNumberOfElementsInLUT8Bit')) end if (strcmp(classLUT,'uint16') || strcmp(classLUT,'int16')) && ... length(LUT) ~= 65536 error(message('images:intlut:wrongNumberOfElementsInLUT16Bit')) end end
github
wangsuyuan/Imageprocesingtoobox-master
padarray_algo.m
.m
Imageprocesingtoobox-master/@gpuArray/private/padarray_algo.m
1,870
utf_8
f4489e1c4fa1070e1f9750171d3f64bf
function b = padarray_algo(a, padSize, method, padVal, direction) %PADARRAY_ALGO Pad array. % B = PADARRAY_AGLO(A,PADSIZE,METHOD,PADVAL,DIRECTION) internal helper % function for PADARRAY, which performs no input validation. See the % help for PADARRAY for the description of input arguments, class % support, and examples. % Copyright 2012 The MathWorks, Inc. if isempty(a) % treat empty matrix similar for any method if strcmp(direction,'both') sizeB = size(a) + 2*padSize; else sizeB = size(a) + padSize; end b = mkconstarray(classUnderlying(a), padVal, sizeB); elseif strcmpi(method,'constant') % constant value padding with padVal b = ConstantPad(a, padSize, padVal, direction); else % compute indices then index into input image aSize = size(a); aIdx = getPaddingIndices(aSize,padSize,method,direction); s.type = '()'; s.subs = aIdx; b = subsref(a, s); end %%% %%% ConstantPad %%% function b = ConstantPad(a, padSize, padVal, direction) numDims = numel(padSize); % Form index vectors to subsasgn input array into output array. % Also compute the size of the output array. idx = cell(1,numDims); sizeB = zeros(1,numDims); for k = 1:numDims M = size(a,k); switch direction case 'pre' idx{k} = (1:M) + padSize(k); sizeB(k) = M + padSize(k); case 'post' idx{k} = 1:M; sizeB(k) = M + padSize(k); case 'both' idx{k} = (1:M) + padSize(k); sizeB(k) = M + 2*padSize(k); end end % Initialize output array with the padding value. Make sure the % output array is the same type as the input. b = mkconstarray(classUnderlying(a), padVal, sizeB); %b(idx{:}) = a; s.type = '()'; s.subs = idx; b = subsasgn(b, s, a);
github
wangsuyuan/Imageprocesingtoobox-master
getPaddingIndices.m
.m
Imageprocesingtoobox-master/@gpuArray/private/getPaddingIndices.m
2,951
utf_8
5d150a985dc5ac9e143c045184767e14
function aIdx = getPaddingIndices(aSize,padSize,method,direction) %getPaddingIndices is used by padarray and blockproc. % Computes padding indices of input image. This is function is used to % handle padding of in-memory images (via padarray) as well as % arbitrarily large images (via blockproc). % % aSize : result of size(I) where I is the image to be padded % padSize : padding amount in each dimension. % numel(padSize) can be greater than numel(aSize) % method : X or a 'string' padding method % direction : pre, post, or both. % % See the help for padarray for additional information. % Copyright 2010 The MathWorks, Inc. % make sure we have enough image dims for the requested padding if numel(padSize) > numel(aSize) singleton_dims = numel(padSize) - numel(aSize); aSize = [aSize ones(1,singleton_dims)]; end switch method case 'circular' aIdx = CircularPad(aSize, padSize, direction); case 'symmetric' aIdx = SymmetricPad(aSize, padSize, direction); case 'replicate' aIdx = ReplicatePad(aSize, padSize, direction); end %%% %%% CircularPad %%% function idx = CircularPad(aSize, padSize, direction) numDims = numel(padSize); % Form index vectors to subsasgn input array into output array. % Also compute the size of the output array. idx = cell(1,numDims); for k = 1:numDims M = aSize(k); dimNums = uint32(1:M); p = padSize(k); switch direction case 'pre' idx{k} = dimNums(mod(-p:M-1, M) + 1); case 'post' idx{k} = dimNums(mod(0:M+p-1, M) + 1); case 'both' idx{k} = dimNums(mod(-p:M+p-1, M) + 1); end end %%% %%% SymmetricPad %%% function idx = SymmetricPad(aSize, padSize, direction) numDims = numel(padSize); % Form index vectors to subsasgn input array into output array. % Also compute the size of the output array. idx = cell(1,numDims); for k = 1:numDims M = aSize(k); dimNums = uint32([1:M M:-1:1]); p = padSize(k); switch direction case 'pre' idx{k} = dimNums(mod(-p:M-1, 2*M) + 1); case 'post' idx{k} = dimNums(mod(0:M+p-1, 2*M) + 1); case 'both' idx{k} = dimNums(mod(-p:M+p-1, 2*M) + 1); end end %%% %%% ReplicatePad %%% function idx = ReplicatePad(aSize, padSize, direction) numDims = numel(padSize); % Form index vectors to subsasgn input array into output array. % Also compute the size of the output array. idx = cell(1,numDims); for k = 1:numDims M = aSize(k); p = padSize(k); onesVector = uint32(ones(1,p)); switch direction case 'pre' idx{k} = [onesVector 1:M]; case 'post' idx{k} = [1:M M*onesVector]; case 'both' idx{k} = [onesVector 1:M M*onesVector]; end end
github
wangsuyuan/Imageprocesingtoobox-master
conformalShowCircles.m
.m
Imageprocesingtoobox-master/imdemos/conformalShowCircles.m
1,286
utf_8
1e66322d244ab24885284ee330cab774
function conformalShowCircles(axIn, axOut, t1, t2) % conformalShowCircles Plot packed circles before/after transformation. % % Supports conformal transformation example, ConformalMappingImageExample.m % ("Exploring a Conformal Mapping"). % Copyright 2005-2013 The MathWorks, Inc. sep = 0.002; % Separation between circles d = 1/8; % Center-to-center distance radius = (d - sep)/2; % Radius of circles for u = -(5/4 - d/2) : d : (5/4 - d/2) for v = -(3/4 - d/2) : d : (3/4 - d/2) % Draw circle on input axes [uc,vc] = Circle(u,v,radius); line(uc,vc,'Parent',axIn,'Color',[0.3 0.3 0.3]); % Apply z = w + sqrt(w^2-1), draw circle on output axes [xc,yc] = tformfwd(t1,uc,vc); line(xc,yc,'Parent',axOut,'Color',[0 0.8 0]); % Apply z = w - sqrt(w^2-1), draw circle on output axes [xc,yc] = tformfwd(t2,uc,vc); line(xc,yc,'Parent',axOut,'Color',[0 0 0.9]); end end %------------------------------------------------------------- function [x, y] = Circle(xCenter, yCenter, radius) % Returns vectors containing the coordinates of a circle % with the specified center and radius. n = 32; theta = (0 : n)' * (2 * pi / n); x = xCenter + radius * cos(theta); y = yCenter + radius * sin(theta);
github
wangsuyuan/Imageprocesingtoobox-master
conformalShowLines.m
.m
Imageprocesingtoobox-master/imdemos/conformalShowLines.m
1,812
utf_8
5d8b9afc8b7fae13318411bd1a2022cd
function conformalShowLines(axIn, axOut, t1, t2) % conformalShowLines Plot a grid of lines before/after transformation. % % Supports conformal transformation example, ConformalMappingImageExample.m % ("Exploring a Conformal Mapping"). % Copyright 2005-2013 The MathWorks, Inc. d = 1/16; u1 = [-5/4 : d : -d, -1e-6]; u2 = 0 : d : 5/4; v1 = [-3/4 : d : -d, -1e-6]; v2 = 0 : d : 3/4; % Lower left quadrant [U,V] = meshgrid(u1,v1); color = [0.3 0.3 0.3]; plotMesh(axIn,U,V,color); plotMesh(axOut,tformfwd(t1,U,V),color); plotMesh(axOut,tformfwd(t2,U,V),color); % Upper left quadrant [U,V] = meshgrid(u1,v2); color = [0 0 0.8]; plotMesh(axIn,U,V,color); plotMesh(axOut,tformfwd(t1,U,V),color); plotMesh(axOut,tformfwd(t2,U,V),color); % Lower right quadrant [U,V] = meshgrid(u2,v1); color = [0 0.8 0]; plotMesh(axIn,U,V,color); plotMesh(axOut,tformfwd(t1,U,V),color); plotMesh(axOut,tformfwd(t2,U,V),color); % Upper right quadrant [U,V] = meshgrid(u2,v2); color = [0 0.7 0.7]; plotMesh(axIn,U,V,color); plotMesh(axOut,tformfwd(t1,U,V),color); plotMesh(axOut,tformfwd(t2,U,V),color); %------------------------------------------------------------- function plotMesh(varargin) % Plots a mesh on the axes AX with color COLOR, via calls % to 'LINE'. % % PLOTMESH(AX,X,Y,COLOR) accepts two M-by-N arrays X and Y % -- like the output of MESHGRID. % % PLOTMESH(AX,XY,COLOR) accepts a single M-by-N-by-2 array XY % -- like the output of TFORMFWD. if nargin == 3 ax = varargin{1}; XY = varargin{2}; color = varargin{3}; X = XY(:,:,1); Y = XY(:,:,2); else ax = varargin{1}; X = varargin{2}; Y = varargin{3}; color = varargin{4}; end for k = 1:size(X,1) line(X(k,:),Y(k,:),'Parent',ax,'Color',color); end for k = 1:size(X,2) line(X(:,k),Y(:,k),'Parent',ax,'Color',color); end
github
wangsuyuan/Imageprocesingtoobox-master
rgb2ycbcr.m
.m
Imageprocesingtoobox-master/colorspaces/rgb2ycbcr.m
4,738
utf_8
854b189ad37b73ba4dcf25e79dd82052
function ycbcr = rgb2ycbcr(varargin) %RGB2YCBCR Convert RGB color values to YCbCr color space. % YCBCRMAP = RGB2YCBCR(MAP) converts the RGB values in MAP to the YCBCR % color space. MAP must be a M-by-3 array. YCBCRMAP is a M-by-3 matrix % that contains the YCBCR luminance (Y) and chrominance (Cb and Cr) color % values as columns. Each row represents the equivalent color to the % corresponding row in the RGB colormap. % % YCBCR = RGB2YCBCR(RGB) converts the truecolor image RGB to the % equivalent image in the YCBCR color space. RGB must be a M-by-N-by-3 % array. % % If the input is uint8, then YCBCR is uint8 where Y is in the range [16 % 235], and Cb and Cr are in the range [16 240]. If the input is a double, % then Y is in the range [16/255 235/255] and Cb and Cr are in the range % [16/255 240/255]. If the input is uint16, then Y is in the range [4112 % 60395] and Cb and Cr are in the range [4112 61680]. % % Class Support % ------------- % If the input is an RGB image, it can be uint8, uint16, or double. If the % input is a colormap, then it must be double. The output has the same class % as the input. % % Examples % -------- % Convert RGB image to YCbCr. % % RGB = imread('board.tif'); % YCBCR = rgb2ycbcr(RGB); % % Convert RGB color space to YCbCr. % % map = jet(256); % newmap = rgb2ycbcr(map); % % See also NTSC2RGB, RGB2NTSC, YCBCR2RGB. % Copyright 1993-2010 The MathWorks, Inc. % References: % C.A. Poynton, "A Technical Introduction to Digital Video", John Wiley % & Sons, Inc., 1996, p. 175 % % Rec. ITU-R BT.601-5, "STUDIO ENCODING PARAMETERS OF DIGITAL TELEVISION % FOR STANDARD 4:3 AND WIDE-SCREEN 16:9 ASPECT RATIOS", % (1982-1986-1990-1992-1994-1995), Section 3.5. rgb = parse_inputs(varargin{:}); %initialize variables isColormap = false; %must reshape colormap to be m x n x 3 for transformation if (ndims(rgb) == 2) %colormap isColormap=true; colors = size(rgb,1); rgb = reshape(rgb, [colors 1 3]); end % This matrix comes from a formula in Poynton's, "Introduction to % Digital Video" (p. 176, equations 9.6). % T is from equation 9.6: ycbcr = origT * rgb + origOffset; origT = [65.481 128.553 24.966;... -37.797 -74.203 112; ... 112 -93.786 -18.214]; origOffset = [16;128;128]; % The formula ycbcr = origT * rgb + origOffset, converts a RGB image in the range % [0 1] to a YCbCr image where Y is in the range [16 235], and Cb and Cr % are in that range [16 240]. For each class type (double,uint8, % uint16), we must calculate scaling factors for origT and origOffset so that % the input image is scaled between 0 and 1, and so that the output image is % in the range of the respective class type. scaleFactor.double.T = 1/255; % scale output so in range [0 1]. scaleFactor.double.offset = 1/255; % scale output so in range [0 1]. scaleFactor.uint8.T = 1/255; % scale input so in range [0 1]. scaleFactor.uint8.offset = 1; % output is already in range [0 255]. scaleFactor.uint16.T = 257/65535; % scale input so it is in range [0 1] % and scale output so it is in range % [0 65535] (255*257 = 65535). scaleFactor.uint16.offset = 257; % scale output so it is in range [0 65535]. % The formula ycbcr = origT*rgb + origOffset is rewritten as % ycbcr = scaleFactorForT * origT * rgb + scaleFactorForOffset*origOffset. % To use imlincomb, we rewrite the formula as ycbcr = T * rgb + offset, where T and % offset are defined below. classIn = class(rgb); T = scaleFactor.(classIn).T * origT; offset = scaleFactor.(classIn).offset * origOffset; %initialize output ycbcr = zeros(size(rgb),classIn); for p = 1:3 ycbcr(:,:,p) = imlincomb(T(p,1),rgb(:,:,1),T(p,2),rgb(:,:,2), ... T(p,3),rgb(:,:,3),offset(p)); end if isColormap ycbcr = reshape(ycbcr, [colors 3 1]); end %%% %Parse Inputs %%% function X = parse_inputs(varargin) narginchk(1,1); X = varargin{1}; if ndims(X)==2 % For backward compatibility, this function handles uint8 and uint16 % colormaps. This usage will be removed in a future release. validateattributes(X,{'uint8','uint16','double'},{'nonempty'},mfilename,'MAP',1); if (size(X,2) ~=3 || size(X,1) < 1) error(message('images:rgb2ycbcr:invalidSizeForColormap')) end if ~isa(X,'double') warning(message('images:rgb2ycbcr:notAValidColormap')) X = im2double(X); end elseif ndims(X)==3 validateattributes(X,{'uint8','uint16','double'},{},mfilename,'RGB',1); if (size(X,3) ~=3) error(message('images:rgb2ycbcr:invalidTruecolorImage')) end else error(message('images:rgb2ycbcr:invalidInputSize')) end
github
wangsuyuan/Imageprocesingtoobox-master
iccwrite.m
.m
Imageprocesingtoobox-master/colorspaces/iccwrite.m
50,643
utf_8
6bb53c9105cc85db41e22336563abc3e
function p_new = iccwrite(p, filename) %ICCWRITE Write ICC color profile. % P_NEW = ICCWRITE(P, FILENAME) writes the International Color Consortium % (ICC) color profile data from the profile structure specified by P to % the file specified by FILENAME. % % P is a structure representing an ICC profile in the data format % returned by ICCREAD and used by MAKECFORM and APPLYCFORM to compute % color-space transformations. It must contain all tags and fields % required by the ICC profile specification. Some fields may be % inconsistent, however, because of interactive changes to the structure. % For instance, the tag table may not be correct because tags may have % been added, deleted, or modified since the tag table was constructed. % Hence, any necessary corrections will be made to the profile structure % before the profile is written to the file. The corrected structure % is returned as P_NEW. % % The VERSION field in P.HEADER is used to determine which version of the % ICC spec to follow in formatting the profile for output. Both Version % 2 and Version 4 are supported. % % The reference page for ICCREAD has additional information about the % fields of the structure P. For complete details, see the % specification ICC.1:2001-04 for Version 2 and ICC.1:2001-12 for % Version 4 (www.color.org). % % Example % ------- % Write a monitor profile. % % P = iccread('monitor.icm'); % pmon = iccwrite(P, 'monitor2.icm'); % % See also ISICC, ICCREAD, MAKECFORM, APPLYCFORM. % Copyright 2003-2013 The MathWorks, Inc. % Check input arguments narginchk(2, 2); validateattributes(filename, {'char'}, {'nonempty'}, 'iccwrite', 'FILENAME', 2); if ~isicc (p) error(message('images:iccwrite:invalidProfile')) end % Open (create) file for writing [fid, msg] = fopen(filename, 'w+', 'b'); if (fid < 0) error(message('images:iccwrite:errorOpeningFile', filename, msg)); end % Write profile data to file and update structure p_new = write_profile(fid, p); fclose(fid); p_new.Filename = filename; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function pnew = write_profile(fid, p) % WRITE_PROFILE(FID, P) writes ICC profile data to the file with % identifier FID from input structure P and returns updated structure % PNEW. % Initialize output structure pnew = p; % Determine version of ICC spec version = sscanf(p.Header.Version(1), '%d%'); % Encode tags in byte vector and construct new tag table [tagtable, tagheap] = encode_tags(p, version); if isempty(tagheap) fclose(fid); error(message('images:iccwrite:InvalidTags')) end % Compute and update sizes and offsets numtags = size(tagtable, 1); base_offset = 128 + 4 + 12 * numtags; % = length(header) + length(tag table) for k = 1:numtags tagtable{k, 2} = tagtable{k, 2} + base_offset; end pnew.Header.Size = base_offset + length(tagheap); pnew.TagTable = tagtable; % Encode header and tag table as byte vectors headerheap = uint8(encode_header(pnew.Header)); if isempty(headerheap) fclose(fid); error(message('images:iccwrite:InvalidHeader')) end tableheap = uint8(encode_tagtable(tagtable)); if isempty(tableheap) fclose(fid); error(message('images:iccwrite:InvalidTagTable')) end % Assemble profile as byte vector and write to file profileheap = uint8([headerheap, tableheap, tagheap]); if version > 2 % Compute MD5 checksum for profile; see clause 6.1.13. % Spec says to compute the checksum after setting bytes % 44-47 (indexed from 0), 64-67, and 84-99 to 0. tempheap = profileheap; tempheap([45:48 65:68 85:100]) = 0; pnew.Header.ProfileID = compute_md5(tempheap); profileheap(85:100) = pnew.Header.ProfileID; end fwrite_check(fid, profileheap, 'uint8'); %----------------------------------------------------- function out = encode_tagtable(tagtable) % Convert TagTable field into byte stream for profile % Allocate space; insert tag count numtags = size(tagtable, 1); out = uint8(zeros(1, 4 + 12 * numtags)); out(1:4) = longs2bytes(uint32(numtags)); offset = 4; % Insert signature, offset, and data_size for each tag for k = 1:numtags % iccread deblanks signatures. Make sure the signature here % has four characters, padded with blanks if necessary. sig = ' '; P = length(tagtable{k, 1}); sig(1:P) = tagtable{k, 1}; out((offset + 1):(offset + 4)) = uint8(sig); out((offset + 5):(offset + 8)) = longs2bytes(uint32(tagtable{k, 2})); out((offset + 9):(offset + 12)) = longs2bytes(uint32(tagtable{k, 3})); offset = offset + 12; end %----------------------------------------------------- %%% encode_tags function [tag_table, tagheap] = encode_tags(p, version) % Encode all public and private tags into byte stream, % recording their locations, etc., in a new tag table % Count public tags -- all fields except Filename, % Header, TagTable, and PrivateTags should count profile_fields = fieldnames(p); if isfield(p, 'MatTRC') mattrc_fields = fieldnames(p.MatTRC); else mattrc_fields = {}; end public_tagnames = get_public_tagnames(version); mattrc_tagnames = get_mattrc_tagnames(version); publiccount = count_matching_fields(profile_fields, public_tagnames(:, 2)) + ... count_matching_fields(mattrc_fields, mattrc_tagnames(:, 2)); % Count private tags privatecount = size(p.PrivateTags, 1); % Allocate space tag_table = cell(publiccount + privatecount, 3); tagrow = 1; tagheap = uint8(zeros(1, 0)); % empty 1-row array offset = 0; % Process public tags for k = 1:length(profile_fields) pdx = strmatch(profile_fields{k}, public_tagnames(:, 2), 'exact'); if ~isempty(pdx) signature = public_tagnames{pdx, 1}; tag = encode_public_tag(signature, p.(profile_fields{k}), ... p.Header.ConnectionSpace, version); if isempty(tag) warning(message('images:iccwrite:DefectiveTag', profile_fields{ k })) tagheap = []; return; end data_size = length(tag); % without padding sigmatch = find_signature_matches(signature, tagrow, tag_table); % ==> sigmatch contains row numbers of possible matching tags matchrow = find_matching_tags(sigmatch, tag, tag_table, tagheap); % Add row to Tag Table, either for alias or new tag: if matchrow ~= 0 % alias to previous tag tag_table{tagrow, 1} = signature; tag_table{tagrow, 2} = tag_table{matchrow, 2}; tag_table{tagrow, 3} = tag_table{matchrow, 3}; else % add new tag tag = bump(tag); % pad to 32-bit boundary % append to heap tagheap = [tagheap, tag]; %#ok<AGROW> tag_table{tagrow, 1} = signature; tag_table{tagrow, 2} = offset; tag_table{tagrow, 3} = data_size; % unpadded length offset = offset + length(tag); % includes padding end tagrow = tagrow + 1; end end for k = 1:length(mattrc_fields) mdx = strmatch(mattrc_fields{k}, mattrc_tagnames(:, 2), 'exact'); if ~isempty(mdx) signature = mattrc_tagnames{mdx, 1}; tag = encode_public_tag(signature, p.MatTRC.(mattrc_fields{k}), ... p.Header.ConnectionSpace, version); if isempty(tag) error(message('images:iccwrite:DefectiveTag', mattrc_fields{ k })) end data_size = length(tag); tag = bump(tag); tagheap = [tagheap, tag]; %#ok<AGROW> tag_table{tagrow, 1} = signature; tag_table{tagrow, 2} = offset; tag_table{tagrow, 3} = data_size; offset = offset + length(tag); tagrow = tagrow + 1; end end % Process private tags for k = 1:privatecount signature = p.PrivateTags{k, 1}; tag = encode_private_tag(p.PrivateTags{k, 2}); if isempty(tag) warning(message('images:iccwrite:DefectiveTagPrivate', signature)) tagheap = []; return; end data_size = length(tag); tag = bump(tag); tagheap = [tagheap, tag]; %#ok<AGROW> tag_table{tagrow, 1} = signature; tag_table{tagrow, 2} = offset; tag_table{tagrow, 3} = data_size; offset = offset + length(tag); tagrow = tagrow + 1; end %----------------------------------------------------- function count = count_matching_fields(fields, tagnames) % Return a count of the number of profile fields that match one or more % entries in the provided list if tagnames. count = 0; for k = 1:length(fields) idx = strmatch(fields{k}, tagnames, 'exact'); if ~isempty(idx) count = count + 1; end end %----------------------------------------------------- function sigmatch = find_signature_matches(signature, tag_row, tag_table) % If signature starts with 'A2B', find other tags in the first tag_row-1 % entries in the tag table starting with 'A2B'. % % If signature starts with 'B2A', find other tags in the first tag_row-1 % entries in the tag table starting with 'B2A'. % % sigmatch is a vector of indices into the tag table. if strcmp(signature(1 : 3), 'A2B') sigmatch = strmatch('A2B', tag_table(1 : tag_row - 1, 1)); elseif strcmp(signature(1 : 3), 'B2A') sigmatch = strmatch('B2A', tag_table(1 : tag_row - 1, 1)); else sigmatch = []; end %----------------------------------------------------- function idx = find_matching_tags(signature_matches, tag, tag_table, tag_heap) % Test tag data against other tags in the tag_table with matching % signatures. signature_matches is a vector of indices into tag_table. tag % is the tag data being tested. tag_heap is the binary table of all tag % data constructed so far. % % Returns idx, a scalar value. If a match was found, idx is the index into % tag_table of the corresponding tag. If no match is found, idx is 0. tag_size = numel(tag); idx = 0; for j = 1:numel(signature_matches) matchoff = tag_table{signature_matches(j), 2}; if tag_table{signature_matches(j), 3} == tag_size && ... all(tag_heap(matchoff + 1 : matchoff + tag_size) == tag) idx = signature_matches(j); break end end %----------------------------------------------------- function out = encode_header(header) % Encode header fields in byte stream for profile out = uint8(zeros(1, 128)); % fixed-length header % Clause 6.1.1 - Profile size out(1:4) = longs2bytes(uint32(header.Size)); % Clause 6.1.2 - CMM Type out(5:8) = uint8(header.CMMType); % Clause 6.1.3 - Profile Version % Byte 0: Major Revision in BCD % Byte 1: Minor Revision & Bug Fix Revision in each nibble in BCD % Byte 2: Reserved; expected to be 0 % Byte 3: Reserved; expected to be 0 version_numbers = sscanf(header.Version, '%d.%d.%d'); out(9) = uint8(version_numbers(1)); out(10) = uint8(16 * version_numbers(2) + version_numbers(3)); % Clause 6.1.4 - Profile/Device Class signature % Device Class Signature % ------------ --------- % Input Device profile 'scnr' % Display Device profile 'mntr' % Output Device profile 'prtr' device_classes = get_device_classes(version_numbers(1)); idx = strmatch(header.DeviceClass, device_classes(:, 2), 'exact'); if isempty(idx) out = []; return; end out(13:16) = uint8(device_classes{idx, 1}); % Clause 6.1.5 - Color Space signature % Four-byte string, although some of signatures have a blank % space at the end. colorspaces = get_colorspaces(version_numbers(1)); idx = strmatch(header.ColorSpace, colorspaces(:, 2), 'exact'); if isempty(idx) out = []; return; end out(17:20) = uint8(colorspaces{idx, 1}); % Clause 6.1.6 - Profile connection space signature % Either 'XYZ' or 'Lab'. However, if the profile is a DeviceLink % profile, the connection space signature is taken from the % colorspace signatures table. idx = strmatch(header.ConnectionSpace, colorspaces(:, 2), 'exact'); if isempty(idx) out = []; return; elseif ~strcmp(header.DeviceClass, 'device link') && idx > 2 out = []; % for non-DeviceLink, must be PCS return; else out(21:24) = uint8(colorspaces{idx, 1}); end date_time_num = datevec(header.CreationDate); out(25:36) = encode_date_time_number(uint16(date_time_num)); if ~strcmp(header.Signature, 'acsp') out = []; return; else out(37:40) = uint8('acsp'); end % Clause 6.1.7 - Primary platform signature % Four characters, though one code ('SGI ') ends with a space. % Zeros if there is no primary platform. switch header.PrimaryPlatform case 'none' out(41:44) = uint8([0 0 0 0]); case 'SGI' out(41:44) = uint8('SGI '); case 'Apple' out(41:44) = uint8('APPL'); case 'Microsoft' out(41:44) = uint8('MSFT'); case 'Sun' out(41:44) = uint8('SUNW'); case 'Taligent' out(41:44) = uint8('TGNT'); otherwise if numel(header.PrimaryPlatform) == 4 out(41:44) = uint8(header.PrimaryPlatform); warning(message('images:iccwrite:invalidPrimaryPlatform')); else out = []; return; end end % Clause 6.1.8 - Profile flags % Flags containing CMM hints. The least-significant 16 bits are reserved % by ICC, which currently defines position 0 as "0 if not embedded profile, % 1 if embedded profile" and position 1 as "1 if profile cannot be used % independently of embedded color data, otherwise 0." out(45:48) = uint8(longs2bytes(uint32(header.Flags))); % Clause 6.1.9 - Device manufacturer and model out(49:52) = uint8(header.DeviceManufacturer); out(53:56) = uint8(header.DeviceModel); % Clause 6.1.10 - Attributes % Device setup attributes, such as media type. The least-significant 32 % bits of this 64-bit value are reserved for ICC, which currently defines % bit positions 0 and 1. % UPDATE FOR ICC:1:2001-04 Clause 6.1.10 -- Bit positions 2 and 3 % POSITION 2: POSITIVE=0, NEGATIVE=1 % POSITION 3: COLOR=0, BLACK AND WHT=1 out(57:60) = uint8([0 0 0 0]); out(61:64) = longs2bytes(uint32(header.Attributes)); % Clause 6.1.11 - Rendering intent switch header.RenderingIntent case 'perceptual' value = 0; case 'relative colorimetric' value = 1; case 'saturation' value = 2; case 'absolute colorimetric' value = 3; otherwise out = []; return; end out(65:68) = longs2bytes(uint32(value)); % Clause 6.1 - Table 9 out(69:80) = encode_xyz_number(header.Illuminant); % Clause 6.12 - Profile creator out(81:84) = uint8(header.Creator); %--------------------------------------- %%% encode_public_tag function out = encode_public_tag(signature, public_tag, pcs, version) lut_types = {'A2B0','A2B1','A2B2','B2A0','B2A1','B2A2',... 'gamt','pre0','pre1','pre2'}; xyz_types = {'bkpt','bXYZ','gXYZ','lumi','rXYZ','wtpt'}; curve_types = {'bTRC','gTRC','kTRC','rTRC'}; text_desc_types = {'desc','dmdd','dmnd','scrd','vued'}; text_types = {'targ'}; non_interpreted_types = {'bfd ','devs',... 'psd0','psd1','psd2','psd3',... 'ps2s','ps2i','scrn'}; if version <= 2 text_types = [text_types, {'cprt'}]; non_interpreted_types = [non_interpreted_types, {'ncol'}]; else text_desc_types = [text_desc_types, {'cprt'}]; % non_interpreted_types = [non_interpreted_types, {'clrt'}]; end % Handle any tags that couldn't be interpreted on input if strcmp(class(public_tag), 'uint8') out = public_tag; return; end % Handle interpreted tags switch char(signature) case lut_types % See Clauses 6.4.* (v. 2) and 9.2.* (v. 4.2) if public_tag.MFT < 1 % for backwards compatibility out = encode_private_tag(public_tag.Data); else out = encode_lut_type(public_tag); end case xyz_types % Clauses 6.4.* (v. 2) and 9.2.* (v. 4.2) out = encode_xyz_type(public_tag); case curve_types % Clauses 6.4.* (v. 2) and 9.2.* (v. 4.2) out = encode_curve_type(public_tag); case text_desc_types % Clauses 6.4.* (v. 2) and 9.2.* (v. 4.2) if version > 2 out = encode_mluc(public_tag); else out = encode_text_description_type(public_tag); end case text_types % Clauses 6.4.* (v. 2) and 9.2.10 (v. 4.2) out = encode_text_type(public_tag); case non_interpreted_types % treat as private tag % Clauses 6.4.* (v. 2) out = encode_private_tag(public_tag); case 'calt' % Clause 6.4.9 (v. 2) and 9.2.9 (v. 4.2) out = encode_date_time_type(public_tag); case 'chad' % Clause 6.4.11 (v. 2) and 9.2.11 (v. 4.2) out = encode_sf32_type(public_tag); case 'chrm' % Clause 9.2.12 (v. 4.2) out = encode_chromaticity_type(public_tag); case 'clro' % Clause 9.2.13 (v. 4.2) out = encode_colorant_order_type(public_tag); case {'clrt', 'clot'} % Clause 9.2.14 (v. 4.2) out = encode_colorant_table_type(public_tag, pcs); case 'crdi' % Clause 6.4.14 (v. 2) or 6.4.16 (v. 4.0) out = encode_crd_info_type(public_tag); case 'meas' % Clause 9.2.23 (v. 4.2) out = encode_measurement_type(public_tag); case 'ncl2' % Clause 9.2.26 (v. 4.2) out = encode_named_color_type(public_tag, pcs); case 'pseq' % Clause 9.2.32 (v. 4.2) out = encode_profile_sequence_type(public_tag, version); case 'resp' % Clause 9.2.27 (v. 4.2) out = encode_response_curve_set16_type(public_tag); case 'tech' % Clause 9.2.35 (v. 4.2) out = encode_signature_type(public_tag); case 'view' % viewingConditionsTag clause 6.4.47 (v. 2) or 9.2.37 (v. 4.2) out = encode_viewing_conditions(public_tag); end %------------------------------------------ %%% encode_private_tag function out = encode_private_tag(tagdata) out = uint8(tagdata); %------------------------------------------ %%% encode_sf32_type function out = encode_sf32_type(vals) % Clause 6.5.14 (v. 2) or 10.18 (v. 4.2) % 0-3 'sf32' % 4-7 reserved, must be 0 % 8-n array of s15Fixed16Number values numvals = numel(vals); data_size = numvals * 4 + 8; out = uint8(zeros(1, data_size)); out(1:4) = uint8('sf32'); longs = int32(round(65536 * vals')); out(9:data_size) = longs2bytes(longs); %------------------------------------------ %%% encode_xyz_number function out = encode_xyz_number(xyz) % Clause 5.3.10 (v. 2) and 5.1.11 (v. 4.2) % 0-3 CIE X s15Fixed16Number % 4-7 CIE Y s15Fixed16Number % 8-11 CIE Z s15Fixed16Number out = longs2bytes(int32(round(65536 * xyz))); %------------------------------------------ %%% encode_xyz_type function out = encode_xyz_type(xyzs) % Clause 6.5.26 (v. 2) or 10.27 (v. 4.2) % 0-3 'XYZ ' % 4-7 reserved, must be 0 % 8-n array of XYZ numbers numxyzs = size(xyzs, 1); data_size = numxyzs * 3 * 4 + 8; out = uint8(zeros(1, data_size)); out(1:4) = uint8('XYZ '); longs = int32(round(65536 * xyzs')); out(9:data_size) = longs2bytes(longs); %------------------------------------------ %%% encode_chromaticity_type function out = encode_chromaticity_type(chrm) % Clause 10.2 (v. 4.2) % 0-3 'chrm' % 4-7 reserved, must be 0 % 8-9 number of device channels % 10-11 encoded phosphor/colorant type % 12-19 CIE xy coordinates of 1st channel % 20-end CIE xy coordinates of remaining channels numchan = size(chrm.xy, 1); % number of colorants out = uint8(zeros(1, 12 + 8 * numchan)); out(1 : 4) = uint8('chrm'); out(9 : 10) = shorts2bytes(uint16(numchan)); out(11 : 12) = shorts2bytes(uint16(chrm.ColorantCode)); current = 12; for i = 1 : numchan out(current + 1 : current + 4) = ... longs2bytes(uint32(round(65536.0 * chrm.xy(i, 1)))); out(current + 5 : current + 8) = ... longs2bytes(uint32(round(65536.0 * chrm.xy(i, 2)))); current = current + 8; end %------------------------------------------ %%% encode_colorant_order_type function out = encode_colorant_order_type(clro) % Clause 10.3 (v. 4.2) % 0-3 'clro' % 4-7 reserved, must be 0 % 8-11 number of colorants n % 12 index of first colorant in laydown % 13-end remaining (n - 1) indices, in laydown order numchan = length(clro); out = uint8(zeros(1, 12 + numchan)); out(1 : 4) = uint8('clro'); out(9 : 12) = longs2bytes(uint32(numchan)); for i = 1 : numchan out(12 + i) = uint8(clro(i)); end %------------------------------------------ %%% encode_colorant_table_type function out = encode_colorant_table_type(clrt, pcs) % Clause 10.4 (v. 4.2) % 0-3 'clrt' % 4-7 reserved, must be 0 % 8-11 number of colorants n % 12-43 name of first colorant, NULL terminated % 44-49 PCS values of first colorant as uint16 % 50-end name and PCS values of remaining colorants numchan = size(clrt, 1); out = uint8(zeros(1, 12 + 38 * numchan)); out(1 : 4) = uint8('clrt'); out(9 : 12) = longs2bytes(uint32(numchan)); next = 13; for i = 1 : numchan % Insert name, leaving space for at least one NULL at end lstring = min(length(clrt{i, 1}), 31); out(next : next + lstring - 1) = ... uint8(clrt{i, 1}(1 : lstring)); % Convert PCS coordinates to uint16 and insert pcs16 = encode_color(clrt{i, 2}, pcs, 'double', 'uint16'); out(next + 32 : next + 37) = shorts2bytes(pcs16); next = next + 38; end %------------------------------------------ %%% encode_curve_type function out = encode_curve_type(curve) % Clause 6.5.3 (v. 2) or 10.5 (v. 4.2) % 0-3 'curv' % 4-7 reserved, must be 0 % 8-11 count value, uint32 % 12-end curve values, uint16 % For v. 4 can also be 'para'; see Clause 10.15 (v. 4.2) if isnumeric(curve) % Encode curveType % Allocate space count = length(curve); if count == 1 && curve(1) == uint16(256) count = 0; % gamma == 1, ==> identity end out = uint8(zeros(1, 2 * count + 12)); % Insert signature and count out(1:4) = uint8('curv'); out(9:12) = longs2bytes(uint32(count)); % Encode curve data if count > 0 out(13:end) = shorts2bytes(uint16(curve)); end elseif isstruct(curve) && isfield(curve, 'FunctionType') ... && isfield(curve, 'Params') % Encode parametricCurveType % Allocate space out = uint8(zeros(1, 12 + 4 * length(curve.Params))); % Insert signature and function index out(1:4) = uint8('para'); out(9:10) = shorts2bytes(uint16(curve.FunctionType)); % Encode function parameters out(13:end) = longs2bytes(int32(round(65536 * curve.Params))); else % error return out = []; end %------------------------------------------ %%% encode viewingConditionsType function out = encode_viewing_conditions(conditions) % Clause 6.5.25 (v. 2) or 10.26 (v. 4.2) % 0-3 'view' % 4-7 reserved, must be 0 % 8-19 absolute XYZ for illuminant in cd/m^2 % 20-31 absolute XYZ for surround in cd/m^2 % 32-35 illuminant type illuminant_table = {'Unknown', 'D50', 'D65', 'D93', 'F2', ... 'D55', 'A', 'EquiPower', 'F8'}; out = uint8(zeros(1, 36)); out(1:4) = uint8('view'); out(9:20) = encode_xyz_number(conditions.IlluminantXYZ); out(21:32) = encode_xyz_number(conditions.SurroundXYZ); illum_idx = strmatch(conditions.IlluminantType, illuminant_table, 'exact'); out(33:36) = longs2bytes(uint32(illum_idx - 1)); %------------------------------------------ %%% encode_lut_type function out = encode_lut_type(lut) % Clauses 6.5.8 and 6.5.7 (v. 2) or 10.9 and 10.8 (v. 4.2) % 0-3 'mft1', 'mft2' % 4-7 reserved, must be 0 % 8 number of input channels, uint8 % 9 number of output channels, uint8 % 10 number of CLUT grid points, uint8 % 11 reserved for padding, must be 0 % 12-47 3-by-3 E matrix, stored row-major, each value s15Fixed16Number % 16-bit LUT type ('mft2'): % 48-49 number of input table entries, uint16 % 50-51 number of output table entries, uint16 % 52-n input tables, uint16 % CLUT values, uint16 % output tables, uint16 % 8-bit LUT type ('mft1'): % 48- input tables, uint8 % CLUT values, uint8 % output tables, uint8 % New v. 4 LUT types, Clauses 10.10 and 10.11 (v. 4.2) % 0-3 'mAB ', 'mBA ' % 4-7 reserved, must be 0 % 8 number of input channels, uint8 % 9 number of output channels, uint8 % 10-11 reserved for padding, must be 0 % 12-15 offset to first B-curve, uint32 % 16-19 offset to 3-by-4 matrix, uint32 % 20-23 offset to first M-curve, uint32 % 24-27 offset to CLUT values, uint32 % 28-31 offset to first A-curve, uint32 % 32-n data: curves stored as 'curv' or 'para' tags, % matrix stored as s15Fixed16Number[12], % CLUT stored as follows: % 0-15 number of grid points in each dimension, uint8 % 16 precision in bytes (1 or 2), uint8 % 17-19 reserved for padding, must be 0 % 20-n CLUT data points, uint8 or uint16 % Insert signature if lut.MFT == 1 out(1:4) = uint8('mft1'); elseif lut.MFT == 2 out(1:4) = uint8('mft2'); elseif lut.MFT == 3 out(1:4) = uint8('mAB '); elseif lut.MFT == 4 out(1:4) = uint8('mBA '); else out = []; return; end % Insert reserved padding bytes out(5:8) = uint8(zeros(1, 4)); % Determine input-output connectivity [num_input_channels, num_output_channels] = luttagchans(lut); if lut.MFT < 3 % older lut types % Determine lut dimensions and allocate space for i = 1 : num_input_channels itbl(:, i) = lut.InputTables{i}; %#ok<AGROW> end num_input_table_entries = size(itbl, 1); for i = 1 : num_output_channels otbl(:, i) = lut.OutputTables{i}; %#ok<AGROW> end num_output_table_entries = size(otbl, 1); num_clut_grid_points = size(lut.CLUT, 1); ndims_clut = num_output_channels; clut_size = ones(1, num_input_channels) * num_clut_grid_points; num_clut_elements = prod(clut_size); nbytesInput = num_input_table_entries * num_input_channels * lut.MFT; nbytesOutput = num_output_table_entries * num_output_channels * lut.MFT; nbytesCLUT = num_clut_elements * ndims_clut * lut.MFT; nbytes = 48 + nbytesInput + nbytesOutput + nbytesCLUT; if lut.MFT == 2 nbytes = nbytes + 4; % variable table sizes end out(9:nbytes) = uint8(zeros(1, nbytes - 8)); % Insert table dimensions out(9) = uint8(num_input_channels); out(10) = uint8(num_output_channels); out(11) = uint8(num_clut_grid_points); % Insert matrix out(13:48) = ... longs2bytes(int32(round ... (65536 * reshape(lut.PreMatrix(1:3, 1:3)', 1, 9)))); % Insert lut contents itbl = reshape(itbl, 1, num_input_channels * num_input_table_entries); otbl = reshape(otbl, 1, num_output_channels * num_output_table_entries); clut = reshape(lut.CLUT, num_clut_elements, ndims_clut)'; clut = reshape(clut, 1, ndims_clut * num_clut_elements); switch lut.MFT case 2 % Means 16-bit CLUT out(49:50) = shorts2bytes(uint16(num_input_table_entries)); out(51:52) = shorts2bytes(uint16(num_output_table_entries)); out(53:(52 + nbytesInput)) = shorts2bytes(uint16(itbl)); out((53 + nbytesInput):(52 + nbytesInput + nbytesCLUT)) = ... shorts2bytes(uint16(clut)); out((53 + nbytesInput + nbytesCLUT):(52 + nbytesInput + nbytesCLUT + nbytesOutput)) = ... shorts2bytes(uint16(otbl)); case 1 % Means 8-bit CLUT out(49:(48 + nbytesInput)) = uint8(itbl); out((49 + nbytesInput):(48 + nbytesInput + nbytesCLUT)) = uint8(clut); out((49 + nbytesInput + nbytesCLUT):(48 + nbytesInput + nbytesCLUT + nbytesOutput)) = ... uint8(otbl); end else % new v. 4 lut types out(9) = uint8(num_input_channels); out(10) = uint8(num_output_channels); out(11:12) = uint8(zeros(1, 2)); % required padding out(13:32) = uint8(zeros(1, 20)); % leave space for offsets % Identify storage elements if lut.MFT == 3 % lutAtoBType Acurve = lut.InputTables; ndlut = lut.CLUT; Mcurve = lut.OutputTables; PMatrix = lut.PostMatrix; Bcurve = lut.PostShaper; elseif lut.MFT == 4 % lutBtoAType Bcurve = lut.PreShaper; PMatrix = lut.PreMatrix; Mcurve = lut.InputTables; ndlut = lut.CLUT; Acurve = lut.OutputTables; end % Store B-curves (required) if isempty(Bcurve) out = []; return; else boffset = 32; current = boffset; numchan = size(Bcurve, 2); for i = 1 : numchan curve = encode_curve_type(Bcurve{i}); curve = bump(curve); out = [out, curve]; %#ok<AGROW> current = current + length(curve); end end % Store PCS-side matrix (optional) if isempty(PMatrix) xoffset = 0; else xoffset = current; mat3by3 = PMatrix(1:3, 1:3); out(current + 1 : current + 9 * 4) = longs2bytes(int32(round(mat3by3' * 65536))); current = current + 9 * 4; out(current + 1 : current + 3 * 4) = longs2bytes(int32(round(PMatrix(:, 4)' * 65536))); current = current + 3 * 4; end % Store M-curves (optional) if isempty(Mcurve) moffset = 0; else moffset = current; numchan = size(Mcurve, 2); for i = 1 : numchan curve = encode_curve_type(Mcurve{i}); curve = bump(curve); out = [out, curve]; %#ok<AGROW> current = current + length(curve); end end % Store n-dimensional LUT (optional) if isempty(ndlut) coffset = 0; else coffset = current; % Store grid dimensions size_ndlut = size(ndlut); clut_size = size_ndlut(1, 1 : num_input_channels); for i = 1 : num_input_channels out(current + i) = uint8(clut_size(num_input_channels + 1 - i)); end % reverse order of dimensions for ICC spec for i = num_input_channels + 1 : 16 % unused channel dimensions out(current + i) = uint8(0); end current = current + 16; % Store data size (in bytes) and add padding if isa(ndlut, 'uint8') datasize = 1; else % 'uint16' datasize = 2; end out(current + 1) = uint8(datasize); out(current + 2 : current + 4) = uint8(zeros(1, 3)); current = current + 4; % Store multidimensional table num_clut_elements = prod(clut_size); ndims_clut = num_output_channels; ndlut = reshape(ndlut, num_clut_elements, ndims_clut); ndlut = ndlut'; ndlut = reshape(ndlut, 1, num_clut_elements * ndims_clut); if datasize == 1 luttag = uint8(ndlut); else luttag = shorts2bytes(uint16(ndlut)); end luttag = bump(luttag); out = [out, luttag]; current = current + length(luttag); end % Store A-curves (optional) if isempty(Acurve) aoffset = 0; else aoffset = current; numchan = size(Acurve, 2); for i = 1 : numchan curve = encode_curve_type(Acurve{i}); curve = bump(curve); out = [out, curve]; %#ok<AGROW> current = current + length(curve); end end % Store offsets out(13:16) = longs2bytes(uint32(boffset)); out(17:20) = longs2bytes(uint32(xoffset)); out(21:24) = longs2bytes(uint32(moffset)); out(25:28) = longs2bytes(uint32(coffset)); out(29:32) = longs2bytes(uint32(aoffset)); end %------------------------------------------ %%% encode_measurement_type function out = encode_measurement_type(meas) % Clause 10.12 (v. 4.2) % 0-3 'meas' % 4-7 reserved, must be 0 % 8-11 encoded standard observer % 12-23 XYZ of measurement backing % 24-27 encoded measurement geometry % 28-31 encoded measurement flare % 32-35 encoded standard illuminant out = zeros(1, 36); out(1 : 4) = uint8('meas'); out(9 : 12) = longs2bytes(uint16(meas.ObserverCode)); out(13 : 24) = encode_xyz_number(meas.MeasurementBacking); out(25 : 28) = longs2bytes(uint16(meas.GeometryCode)); out(29 : 32) = longs2bytes(uint16(meas.FlareCode)); out(33 : 36) = longs2bytes(uint16(meas.IlluminantCode)); %------------------------------------------ %%% encode_named_color_type function out = encode_named_color_type(named, pcs) % Clause 10.14 (v. 4.2) % 0-3 'ncl2' (namedColor2Type signature) % 4-7 reserved, must be 0 % 8-11 vendor-specific flag % 12-15 count of named colours (n) % 16-19 number m of device coordinates % 20-51 prefix (including NULL terminator) % 52-83 suffix (including NULL terminator) % 84-115 first colour name (including NULL terminator) % 116-121 first colour's PCS coordinates % 122-(121 + 2m) first colour's device coordinates % . . . and so on for remaining (n - 1) colours n = size(named.NameTable, 1); m = named.DeviceCoordinates; out = zeros(1, 84 + n * (38 + 2 * m)); out(1:4) = uint8('ncl2'); out(9:12) = longs2bytes(uint32(hex2dec(named.VendorFlag))); out(13:16) = longs2bytes(uint32(n)); out(17:20) = longs2bytes(uint32(m)); lstring = min(length(named.Prefix), 31); % leave space for NULL out(21 : 20 + lstring) = uint8(named.Prefix(1:lstring)); lstring = min(length(named.Suffix), 31); out(53 : 52 + lstring) = uint8(named.Suffix(1:lstring)); next = 85; for i = 1 : n % Insert name, leaving space for at least one NULL at end lstring = min(length(named.NameTable{i, 1}), 31); out(next : next + lstring - 1) = ... uint8(named.NameTable{i, 1}(1 : lstring)); % Convert PCS coordinates to uint16 and insert pcs16 = encode_color(named.NameTable{i, 2}, pcs, ... 'double', 'uint16'); out(next + 32 : next + 37) = shorts2bytes(pcs16); % Convert any device coordinates to uint16 and insert if size(named.NameTable, 2) > 2 device16 = encode_color(named.NameTable{i, 3}, 'color_n', ... 'double', 'uint16'); out(next + 38 : next + 37 + 2 * m) = shorts2bytes(device16); end next = next + 38 + 2 * m; end %------------------------------------------ %%% encode_profile_sequence_type function out = encode_profile_sequence_type(seq, version) % Clause 10.16 (v. 4.2) % 0-3 'pseq' % 4-7 reserved, must be 0 % 8-11 count of profile description structures % 12- profile description structures % Initialize output array with signature and count out = uint8(zeros(1, 12)); out(1:4) = uint8('pseq'); n = length(seq); out(9:12) = longs2bytes(uint32(n)); % Append profile description structures technologies = get_technologies; for p = 1:n pdesc(1:4) = uint8(seq(p).DeviceManufacturer); pdesc(5:8) = uint8(seq(p).DeviceModel); pdesc(9:12) = uint8(zeros(1, 4)); pdesc(13:16) = longs2bytes(seq(p).Attributes); if strcmp(seq(p).Technology, 'Unspecified') pdesc(17:20) = uint8(zeros(1, 4)); else idx = strmatch(seq(p).Technology, technologies(:, 2)); if isempty(idx) pdesc(17:20) = uint8(zeros(1, 4)); else pdesc(17:20) = uint8(technologies{idx, 1}); end end out = [out, pdesc]; %#ok<AGROW> if version <= 2 if strcmp(seq(p).DeviceMfgDesc.String, 'Unavailable') blank.String = ''; blank.Optional = uint8(zeros(1, 78)); dmnd = encode_text_description_type(blank); else dmnd = encode_text_description_type(seq(p).DeviceMfgDesc); end else if strcmp(seq(p).DeviceMfgDesc.String, 'Unavailable') seq(p).DeviceMfgDesc.String = ''; end dmnd = encode_mluc(seq(p).DeviceMfgDesc); end out = [out, dmnd]; %#ok<AGROW> if version <= 2 if strcmp(seq(p).DeviceModelDesc.String, 'Unavailable') blank.String = ''; blank.Optional = uint8(zeros(1, 78)); dmdd = encode_text_description_type(blank); else dmdd = encode_text_description_type(seq(p).DeviceModelDesc); end else if strcmp(seq(p).DeviceModelDesc.String, 'Unavailable') seq(p).DeviceModelDesc.String = ''; end dmdd = encode_mluc(seq(p).DeviceModelDesc); end out = [out, dmdd]; %#ok<AGROW> end %------------------------------------------ %%% encode_response_curve_set16_type function out = encode_response_curve_set16_type(rcs2) % Clause 10.17 (v. 4.2) % 0-3 'rcs2' % 4-7 reserved, must be 0 % 8-9 number of channels n % 10-11 number of measurement types m % 12-(11+4m) array of offsets % (12+4m)-end m response-curve structures numtypes = length(rcs2); % 1D structure array numchan = size(rcs2(1).SolidXYZs, 1); out = uint8(zeros(1, 12 + 4 * numtypes)); out(1 : 4) = uint8('rcs2'); out(9 : 10) = shorts2bytes(uint16(numchan)); out(11 : 12) = shorts2bytes(uint16(numtypes)); current = 12 + 4 * numtypes; % start of response-curve structures % response-curve structure % 0-3 measurement-type signature % 4-(3+4n) number of measurements for each channel % (4+4n)-(3+16n) XYZ of solid-colorant patches % (4+16n)-end n response arrays for i = 1 : numtypes out(9 + 4 * i : 12 + 4 * i) = longs2bytes(uint16(current)); out(current + 1 : current + 4) = uint8(rcs2(i).MeasurementCode); current = current + 4; nmeas = zeros(1, numchan); for j = 1 : numchan nmeas(j) = size(rcs2(i).ResponseArray{j}, 1); out(current + 1 : current + 4) = longs2bytes(uint32(nmeas(j))); current = current + 4; end for j = 1 : numchan out(current + 1 : current + 12) = ... encode_xyz_number(rcs2(i).SolidXYZs(j, :)); current = current + 12; end for j = 1 : numchan responsearray = []; for k = 1 : nmeas(j) devcode = 65535.0 * rcs2(i).ResponseArray{j}(k, 1); measure = 65536.0 * rcs2(i).ResponseArray{j}(k, 2); response(1 : 2) = shorts2bytes(uint16(round(devcode))); response(5 : 8) = longs2bytes(uint32(round(measure))); responsearray = [responsearray response]; %#ok<AGROW> end out(current + 1 : current + 8 * nmeas(j)) = responsearray; current = current + 8 * nmeas(j); end end %------------------------------------------ %%% encode_signature_type function out = encode_signature_type(technology) % Clause 10.19 (v. 4.2) % 0-3 'sig ' % 4-7 reserved, must be 0 % 8-11 four-byte signature out = uint8(zeros(1, 12)); out(1:4) = uint8('sig '); if ~strcmp(technology, 'Unspecified') technologies = get_technologies; idx = strmatch(technology, technologies(:, 2)); if isempty(idx) return; else out(9:12) = uint8(technologies{idx, 1}); end end %------------------------------------------ %%% encode_text_description_type function out = encode_text_description_type(description) % Clause 6.5.17 (v. 2 only) % 0-3 'desc' % 4-7 reserved, must be 0 % 8-11 ASCII invariant description count, with terminating NULL % 12-(n-1) ASCII invariant description % followed by optional Unicode and ScriptCode descriptions, which we % replace with new text if the ASCII description has changed. % n-(n+3) Unicode language code (uint32) % (n+4)-(n+7) Unicode description count with NULL (uint32) % (n+8)-(m-1) Unicode description (2 bytes per character) % m-(m+1) ScriptCode code (uint16) % m+2 ScriptCode description count with NULL (uint8) % (m+3)-(m+69) ScriptCode description % Note: Unicode code and count are always required, as are % ScriptCode code, count, and description. These can % all be zeros, but they consume at least 78 bytes even % if no textual information is encoded. % Handle v. 2 type interpreted by older iccread if ~isfield(description, 'Plain') && ~isfield(description, 'String') description.String = description; description.Optional = uint8(zeros(1, 78)); % minimal data (no Unicode or ScriptCode) end if isfield(description, 'Plain') description.String = description.Plain; end if ~isfield(description, 'Optional') description.Optional = uint8(zeros(1, 78)); end % Allocate minimal space asciicount = length(description.String) + 1; optionalcount = length(description.Optional); out = uint8(zeros(1, 12 + asciicount + 78)); % Insert signature and ASCII character count out(1:4) = uint8('desc'); out(9:12) = longs2bytes(uint32(asciicount)); % Insert ASCII text description, with terminating NULL newstring = description.String; newstring(asciicount) = char(uint8(0)); % add null terminator out(13:(12 + asciicount)) = uint8(newstring); % Adjust Unicode & ScriptCode description, if any, to agree % with ASCII string, which may have been modified unicount = double(description.Optional(5 : 8)); unilength = bitshift(unicount(1), 24) + bitshift(unicount(2), 16) + ... bitshift(unicount(3), 8) + unicount(4); scriptsection = description.Optional(9 + 2 * unilength : end); % ScriptCode section is always 70 bytes. The first 3 are % reserved for code and count, leaving 67 for the string. % But some v. 2 profiles violate this rule, so we must make % allowances. The output profile will conform to the rule. sclength = length(scriptsection); if sclength < 70 scriptsection(sclength + 1 : 70) = uint8(zeros(1, 70 - sclength)); optionalcount = optionalcount + 70 - sclength; end scriptlength = double(scriptsection(3)); % actual string length scripttext = scriptsection(4 : 3 + scriptlength); % Replace any existing Unicode if it doesn't match ASCII String if unilength > 0 % there is a Unicode string % Compare with ASCII String unistring = native2unicode(description.Optional(9 : (8 + 2 * unilength)), ... 'utf-16be'); unistart = strfind(unistring, description.String); % skip leading characters if ~isempty(unistart) match = strcmp(unistring(unistart : end), description.String); else match = false; end if ~match % Replace with new Unicode string, keeping original FEFF % or other special character at beginning newunistring = unicode2native(newstring, 'utf-16be'); if description.Optional(9) ~= 0 % special character description.Optional(5 : 8) = longs2bytes(uint32(asciicount + 1)); description.Optional(11 : 10 + 2 * asciicount) = newunistring; optionalcount = 80 + 2 * asciicount; else % presumably, no leading special character description.Optional(5 : 8) = longs2bytes(uint32(asciicount)); description.Optional(9 : 8 + 2 * asciicount) = newunistring; optionalcount = 78 + 2 * asciicount; end end end % Replace any existing ScriptCode if it doesn't match ASCII String if scriptlength > 0 % there is a ScriptCode string % Compare with ASCII scriptstart = strfind(scripttext, newstring); if isempty(scriptstart) % it doesn't match % Replace ScriptCode, if it fits if asciicount < 68 scriptsection(3) = uint8(asciicount); scriptsection(4 : 3 + asciicount) = uint8(newstring); scriptsection(4 + asciicount : 70) = ... uint8(zeros(1, 67 - asciicount)); end end end % Whether replaced or not, reinsert ScriptCode into Optional after % Unicode (which may have changed) description.Optional(optionalcount - 69 : optionalcount) = ... scriptsection(1 : 70); % Insert optional Unicode and ScriptCode data into output array out((12 + asciicount + 1):(12 + asciicount + optionalcount)) ... = uint8(description.Optional(1 : optionalcount)); %------------------------------------------ function out = encode_mluc(description) % Clause 10.13 (v. 4.2) % 0-3 'mluc' % 4-7 reserved, must be 0 % 8-11 number of name records that follow (n) % 12-15 name-record length (currently 12) % 16-17 first-name language code (ISO-639) % 18-19 first-name country code (ISO-3166) % 20-23 first-name length % 24-27 first-name offset % 28-(28+12n) [n should be (n - 1) - rfp] % additional name records, if any % (28+12n)-end [n should be (n - 1) - rfp] % Unicode characters (2 bytes each) % Allocate space in output array and initialize to zero first_unicode_character_offset = 16 + 12*numel(description); nbytes = first_unicode_character_offset; for k = 1 : numel(description) nbytes = nbytes + 2 * numel(description(k).String); end % Two bytes per Unicode character in each string out = uint8(zeros(1, nbytes)); % Insert signature, number of records, and record length out(1:4) = uint8('mluc'); out(9:12) = longs2bytes(uint32(numel(description))); out(13:16) = longs2bytes(uint32(12)); % Insert "name" records total_unicode_bytes = 0; current = 16; for k = 1:numel(description) out(current + 1 : current + 2) = ... shorts2bytes(uint16(description(k).LanguageCode)); out(current + 3 : current + 4) = ... shorts2bytes(uint16(description(k).CountryCode)); num_bytes = 2 * numel(description(k).String); out(current + 5 : current + 8) = longs2bytes(uint32(num_bytes)); out(current + 9 : current + 12) = ... longs2bytes(uint32(first_unicode_character_offset + total_unicode_bytes)); total_unicode_bytes = total_unicode_bytes + num_bytes; current = current + 12; end % Insert "names" in Unicode for k = 1:numel(description) unibytes = unicode2native(description(k).String, 'utf-16be'); lengthk = length(unibytes); out(current + 1 : current + lengthk) = unibytes; current = current + lengthk; end %------------------------------------------ %%% encode_text_type function out = encode_text_type(textstring) % Clause 6.5.18 (v. 2) or 10.20 (v. 4.2) % 0-3 'text' % 4-7 reserved, must be 0 % 8- string of (data_size - 8) 7-bit ASCII characters, including NULL out = uint8(zeros(1, length(textstring) + 9)); out(1:4) = uint8('text'); out(9:(8 + length(textstring))) = uint8(textstring); out(9 + length(textstring)) = uint8(0); % Unnecessary, but explicit %------------------------------------------ %%% encode_date_time_type function out = encode_date_time_type(dtnumber) % Clause 6.5.5 (v. 2) or 10.7 (v. 4.2) % 0-3 'dtim' % 4-7 reserved, must be 0 % 8-19 DateTimeNumber % Verify that dtnumber is an array of six 16-bit integers out = uint8(zeros(1, 20)); out(1:4) = uint8('dtim'); out(9:20) = encode_date_time_number(dtnumber); %------------------------------------------ %%% encode_crd_info_type function out = encode_crd_info_type(crd_info) % Clause 6.5.2 (v. 2) or 6.5.4 (v. 4.0) % 0-3 'crdi' % 4-7 reserved, must be 0 % 8-11 PostScript product name character count, uint32 % PostScript product name, 7-bit ASCII % Rendering intent 0 CRD name character count, uint32 % Rendering intent 0 CRD name, 7-bit ASCII % Rendering intent 1 CRD name character count, uint32 % Rendering intent 1 CRD name, 7-bit ASCII % Rendering intent 2 CRD name character count, uint32 % Rendering intent 2 CRD name, 7-bit ASCII % Rendering intent 3 CRD name character count, uint32 % Rendering intent 3 CRD name, 7-bit ASCII % Verify that psproductname is a string and that crdnames is % a cell array of strings, of length 4. psproductname = crd_info.PostScriptProductName; crdnames = crd_info.RenderingIntentCRDNames; % Allocate space required, including NULL terminators lenp = length(psproductname) + 1; lencrd = zeros(1, 4); for k = 1:4 lencrd(k) = length(crdnames{k}) + 1; end out = uint8(zeros(1, 28 + lenp + sum(lencrd))); % Insert signature, lengths, and names out(1:4) = uint8('crdi'); last = 8; % 4 bytes reserved (= 0) out((last + 1):(last + 4)) = longs2bytes(uint32(lenp)); last = last + 4; out((last + 1):(last + lenp - 1)) = uint8(psproductname); out(last + lenp) = uint8(0); last = last + lenp; for k = 1:4 out((last + 1):(last + 4)) = longs2bytes(uint32(lencrd(k))); last = last + 4; out((last + 1):(last + lencrd(k) - 1)) = uint8(crdnames{k}); out(last + lencrd(k)) = uint8(0); last = last + lencrd(k); end %------------------------------------------ %%% encode_date_time_number function out = encode_date_time_number(dtn) % Clause 5.3.1 (v. 2) and 5.1.1 (v. 4.2) out = shorts2bytes(uint16(dtn)); %------------------------------------------ %%% bump -- add zeros to byte array to reach % next 32-bit boundary function tag = bump(tag) padding = mod(-length(tag), 4); if padding ~= 0 tag = [tag, uint8(zeros(1, padding))]; end %------------------------------------------ %%% shorts2bytes function bytes = shorts2bytes(shorts) % Convert signed to unsigned if isa(shorts, 'int16') ushorts = uint16(zeros(size(shorts))); negs = find(shorts < 0); nonnegs = find(shorts >= 0); two16 = double(intmax('uint16')) + 1.0; base16 = ones(size(shorts)) * two16; ushorts(nonnegs) = uint16(shorts(nonnegs)); ushorts(negs) = uint16(double(shorts(negs)) + base16(negs)); shorts = ushorts; end numshorts = numel(shorts); shorts = reshape(shorts, 1, numshorts); bytes = uint8(zeros(2, numshorts)); bytes(1, :) = uint8(bitshift(shorts, -8)); bytes(2, :) = uint8(bitand(shorts, 255)); bytes = reshape(bytes, 1, 2 * numshorts); %------------------------------------------ %%% longs2bytes function bytes = longs2bytes(longs) % Convert signed to unsigned if isa(longs, 'int32') ulongs = uint32(zeros(size(longs))); negs = find(longs < 0); nonnegs = find(longs >= 0); two32 = double(intmax('uint32')) + 1.0; base32 = ones(size(longs)) * two32; ulongs(nonnegs) = uint32(longs(nonnegs)); ulongs(negs) = uint32(double(longs(negs)) + base32(negs)); longs = ulongs; end numlongs = numel(longs); longs = reshape(longs, 1, numlongs); bytes = uint8(zeros(4, numlongs)); bytes(1, :) = uint8(bitshift(longs, -24)); bytes(2, :) = uint8(bitand(bitshift(longs, -16), 255)); bytes(3, :) = uint8(bitand(bitshift(longs, -8), 255)); bytes(4, :) = uint8(bitand(longs, 255)); bytes = reshape(bytes, 1, 4 * numlongs); %------------------------------------------ %%% fwrite_check function fwrite_check(fid, a, precision) count = fwrite(fid, a, precision); if count ~= numel(a) pos = ftell(fid) - count; fclose(fid); error(message('images:iccwrite:fileWriteFailed', n, pos)) end
github
wangsuyuan/Imageprocesingtoobox-master
ntsc2rgb.m
.m
Imageprocesingtoobox-master/colorspaces/ntsc2rgb.m
2,732
utf_8
54f4fadb9dc61419dff96920bfaa7a8f
function varargout = ntsc2rgb(varargin) %NTSC2RGB Convert NTSC color values to RGB color space. % RGBMAP = NTSC2RGB(YIQMAP) converts the M-by-3 NTSC % (television) values in the colormap YIQMAP to RGB color % space. If YIQMAP is M-by-3 and contains the NTSC luminance % (Y) and chrominance (I and Q) color components as columns, % then RGBMAP is an M-by-3 matrix that contains the red, green, % and blue values equivalent to those colors. Both RGBMAP and % YIQMAP contain intensities in the range 0.0 to 1.0. The % intensity 0.0 corresponds to the absence of the component, % while the intensity 1.0 corresponds to full saturation of the % component. % % RGB = NTSC2RGB(YIQ) converts the NTSC image YIQ to the % equivalent truecolor image RGB. % % Class Support % ------------- % The input image or colormap must be of class double. The % output is of class double. % % Example % ------- % Convert RGB image to NTSC and back. % % RGB = imread('board.tif'); % NTSC = rgb2ntsc(RGB); % RGB2 = ntsc2rgb(NTSC); % % See also RGB2NTSC, RGB2IND, IND2RGB, IND2GRAY. % Copyright 1992-2010 The MathWorks, Inc. A = parse_inputs(varargin{:}); T = [1.0 0.956 0.621; 1.0 -0.272 -0.647; 1.0 -1.106 1.703]; threeD = (ndims(A)==3); % Determine if input includes a 3-D array. if threeD % A is YIQ, M-by-N-by-3 m = size(A,1); n = size(A,2); A = reshape(A(:),m*n,3)*T'; % Make sure the rgb values are between 0.0 and 1.0 A = max(0,A); d = find(any(A'>1)); A(d,:) = A(d,:) ./ (max(A(d,:), [], 2) * ones(1,3)); A = reshape(A,m,n,3); else % A is YIQMAP, M-by-3 A = A*T'; % Make sure the rgb values are between 0.0 and 1.0 A = max(0,A); d = find(any(A'>1)); A(d,:) = A(d,:) ./ (max(A(d,:), [], 2) * ones(1,3)); end % Output if nargout < 2,% RGBMAP = NTSC2RGB(YIQMAP) varargout{1} = A; else error(message('images:ntsc2rgb:wrongNumberOfOutputArguments', nargout)) end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Function: parse_inputs % function A = parse_inputs(varargin) narginchk(1,1); % ntsc2rgb(YIQ) or ntsc2rgb(YIQMAP) A = varargin{1}; %no logical if islogical(A) error(message('images:ntsc2rgb:invalidType')) end % Check validity of the input parameters. A is converted to double because YIQ % colorspace can contain negative values. if ndims(A)==2 % Check colormap if ( size(A,2)~=3 || size(A,1) < 1 ) error(message('images:ntsc2rgb:invalidYIQMAP')) end if ~isa(A,'double') warning(message('images:ntsc2rgb:rangeYIQMAP')); A = im2double(A); end elseif ndims(A)==3 && size(A,3)==3 % Check YIQ A = im2double(A); else error(message('images:ntsc2rgb:invalidSize')) end
github
wangsuyuan/Imageprocesingtoobox-master
makecform.m
.m
Imageprocesingtoobox-master/colorspaces/makecform.m
40,214
utf_8
cc693b52b96528419278ee0160c717a7
function c = makecform(varargin) %MAKECFORM Create a color transformation structure. % C = MAKECFORM(TYPE) creates the color transformation structure, C, % that defines the color space conversion specified by TYPE. To % perform the transformation, pass the color transformation structure % as an argument to the APPLYCFORM function. TYPE should be one of % these strings: % % 'lab2lch' 'lch2lab' 'upvpl2xyz' 'xyz2upvpl' % 'uvl2xyz' 'xyz2uvl' 'xyl2xyz' 'xyz2xyl' % 'xyz2lab' 'lab2xyz' 'srgb2xyz' 'xyz2srgb' % 'srgb2lab' 'lab2srgb' 'srgb2cmyk' 'cmyk2srgb' % % (The color space table below defines these abbreviations.) % % For the xyz2lab and lab2xyz transforms, you can optionally specify the value % of the reference white point. Use the syntax C = % MAKECFORM(TYPE,'WhitePoint',WP), where WP is a 1-by-3 vector of XYZ values % scaled so that Y = 1. The default is whitepoint('ICC'). You can use the % WHITEPOINT function to create the WP vector. % % For the srgb2lab, lab2srgb, srgb2xyz, and xyz2srgb transforms, you can % optionally specify the adapted white point using the syntax C = % MAKECFORM(TYPE, 'AdaptedWhitePoint', WP). As above, WP is a row vector % of XYZ values scaled so that Y = 1. If not specified, the default % adapated white point is whitepoint('ICC'). NOTE: To get answers % consistent with some published sRGB equations, specify % whitepoint('D65') for the adapted white point. % % The srgb2cmyk and cmyk2srgb transforms convert data between sRGB % IEC61966-2.1 and "Specifications for Web Offset Publications" (SWOP) % CMYK. You can optionally specify the rendering intent for this type of % transform. Use the syntax: % % C = MAKECFORM('srgb2cmyk', 'RenderingIntent', INTENT) % C = MAKECFORM('cmyk2srgb', 'RenderingIntent', INTENT) % % where INTENT must be one of these strings: % % 'AbsoluteColorimetric' 'Perceptual' % 'RelativeColorimetric' 'Saturation' % % 'Perceptual' is the default rendering intent. See the MAKECFORM % reference page for more information about rendering intents. % % C = MAKECFORM('adapt', 'WhiteStart', WPS, 'WhiteEnd', WPE, 'AdaptModel', % MODELNAME) creates a linear chromatic-adaptation transform. WPS and % WPE are row vectors of XYZ values, scaled so that Y = 1, specifying % the starting and ending white points. MODELNAME is either 'vonKries' % or 'Bradford' and specifies the type of chromatic-adaptation model to % be employed. If 'AdaptModel' is not specified, it defaults to % 'Bradford'. % % C = MAKECFORM('icc', SRC_PROFILE, DEST_PROFILE) creates a color % transformation based on two ICC profiles. SRC_PROFILE and % DEST_PROFILE are ICC profile structures returned by ICCREAD. % % C = MAKECFORM('icc', SRC_PROFILE, DEST_PROFILE, % 'SourceRenderingIntent', SRC_INTENT, 'DestRenderingIntent', % DEST_INTENT) creates a color transformation based on two ICC color % profiles. SRC_INTENT and DEST_INTENT specify the rendering intent % corresponding to the source and destination profiles. (See the table % above for the list of rendering intent strings.) 'Perceptual' is the % default rendering intent for both source and destination. % % CFORM = MAKECFORM('clut', PROFILE, LUTTYPE) creates a color transform % based on a Color Lookup Table (CLUT) contained in an ICC color % profile. PROFILE is an ICC profile structure returned by ICCREAD. % LUTTYPE specifies which CLUT in the PROFILE structure is to be used. % It may be one of these strings: % % 'AToB0' 'AToB1' 'AToB2' 'AToB3' 'BToA0' % 'BToA1' 'BToA2' 'BToA3' 'Gamut' 'Preview0' % 'Preview1' 'Preview2' % % and defaults to 'AToB0'. % % CFORM = MAKECFORM('mattrc', MATTRC, 'Direction', DIR) creates a color % transform based on the structure MATTRC, containing an RGB-to-XYZ % matrix and RGB Tone Reproduction Curves. MATTRC is typically the % 'MatTRC' field of an ICC profile structure returned by ICCREAD, based % on tags contained in an ICC color profile. DIR is either 'forward' or % 'inverse' and specifies whether the MatTRC is to be applied in the % forward (RGB to XYZ) or inverse (XYZ to RGB) direction. % % CFORM = MAKECFORM('mattrc', PROFILE, 'Direction', DIR) creates a color % transform based on the 'MatTRC' field of the given ICC profile % structure PROFILE. DIR is either 'forward' or 'inverse' and specifies % whether the MatTRC is to be applied in the forward (RGB to XYZ) or % inverse (XYZ to RGB) direction. % % CFORM = MAKECFORM('mattrc', PROFILE, 'Direction', DIR, % 'RenderingIntent', INTENT) is similar, but adds the option of % specifying the rendering intent. INTENT must be one of the strings: % % 'RelativeColorimetric' [default] % 'AbsoluteColorimetric' % % When 'AbsoluteColorimetric' is specified, the colorimetry is referenced % to a perfect diffuser, rather than to the Media White Point of the % profile. % % CFORM = MAKECFORM('graytrc', PROFILE, 'Direction', DIR) creates a % monochrome transform based on a single-channel Tone Reproduction % Curve contained as the 'GrayTRC' field of the ICC profile structure % PROFILE. DIR is either 'forward' or 'inverse' and specifies whether % the transform is to be applied in the forward (device to PCS) or % inverse (PCS to device) direction. ("Device" here refers to the % grayscale signal communicating with the monochrome device. "PCS" is % the Profile Connection Space of the ICC profile and can be either XYZ % or Lab, depending on the 'ConnectionSpace' field in PROFILE.Header.) % % CFORM = MAKECFORM('graytrc', PROFILE, 'Direction', DIR, % 'RenderingIntent', INTENT) is similar, but adds the option of % specifying the rendering intent. INTENT must be one of the strings: % % 'RelativeColorimetric' [default] % 'AbsoluteColorimetric' % % When 'AbsoluteColorimetric' is specified, the colorimetry is referenced % to a perfect diffuser, rather than to the Media White Point of the % profile. % % CFORM = MAKECFORM('named', PROFILE, SPACE) creates a transform % from color names to color-space coordinates. PROFILE must be % a profile structure for a Named Color profile (with a NamedColor2 % field). SPACE is either 'PCS' or 'Device'. The 'PCS' option is % always available and will return Lab or XYZ coordinates, depending % on the 'ConnectionSpace' field in PROFILE.Header, in 'double' % format. The 'Device' option, when active, will return device % coordinates, the dimension depending on the 'ColorSpace' field % in PROFILE.Header, also in 'double' format. % % For more information about 'clut' transformations, see Section 6.5.7 % of ICC.1:2001-04 (Version 2) or Section 6.5.9 of ICC.1:2001-12 (Version 4). % For more information about 'mattrc' transformations, see Section 6.3.1.2 % ICC.1:2001-04 or ICC.1:2001-12. These specifications are available % at www.color.org. % % % Color space abbreviations % ------------------------- % % Abbreviation Description % % xyz 1931 CIE XYZ tristimulus values (2 degree observer) % xyl 1931 CIE xyY chromaticity values (2 degree observer) % uvl 1960 CIE uvL values % upvpl 1976 CIE u'v'L values % lab 1976 CIE L*a*b* values % lch Polar transformation of L*a*b* values; c = chroma % and h = hue % srgb Standard computer monitor RGB values % (IEC 61966-2-1) % % Example % ------- % Convert RGB image to L*a*b*, assuming input image is sRGB. % % rgb = imread('peppers.png'); % cform = makecform('srgb2lab'); % lab = applycform(rgb, cform); % % See also APPLYCFORM, LAB2DOUBLE, LAB2UINT8, LAB2UINT16, WHITEPOINT, % XYZ2DOUBLE, XYZ2UINT16, ISICC, ICCREAD, ICCWRITE. % Copyright 2002-2010 The MathWorks, Inc. % Poe % Author: Scott Gregory, Toshia McCabe 10/18/02 narginchk(1, Inf); valid_strings = {'lab2lch', 'lch2lab', ... 'upvpl2xyz', 'xyz2upvpl',... 'uvl2xyz', 'xyz2uvl', ... 'xyl2xyz', 'xyz2xyl', ... 'xyz2lab', 'lab2xyz', ... 'srgb2xyz', 'xyz2srgb', ... 'srgb2lab', 'lab2srgb', ... 'srgb2cmyk', 'cmyk2srgb', ... 'clut', 'mattrc', 'graytrc', 'icc', 'named', 'adapt', ... 'makeabsolute', 'makeblackfix'}; transform_type = validatestring(varargin{1}, valid_strings, mfilename, ... 'TRANSFORMTYPE', 1); switch lower(transform_type) case {'lab2lch', 'lch2lab', 'upvpl2xyz', 'xyz2upvpl',... 'uvl2xyz', 'xyz2uvl', 'xyl2xyz', 'xyz2xyl'} c = make_simple_cform(varargin{:}); case {'xyz2lab', 'lab2xyz'} c = make_xyz2lab_or_lab2xyz_cform(varargin{:}); case 'clut' c = make_clut_cform(varargin{2:end}); case 'mattrc' c = make_mattrc_cform(varargin{2:end}); case 'graytrc' c = make_graytrc_cform(varargin{2:end}); case 'named' c = make_named_cform(varargin{2:end}); case 'icc' c = make_icc_cform(varargin{2:end}); case 'adapt' c = make_adapt_cform(varargin{:}); case 'makeabsolute' c = make_absolute_cform(varargin{2:end}); case 'makeblackfix' c = make_blackpoint_cform(varargin{2:end}); case {'srgb2xyz', 'xyz2srgb'} c = make_srgb2xyz_or_xyz2srgb_cform(varargin{:}); case 'srgb2lab' c = make_srgb2lab_cform(varargin{:}); case 'lab2srgb' c = make_lab2srgb_cform(varargin{:}); case 'srgb2cmyk' c = make_srgb2swop_cform(varargin{:}); case 'cmyk2srgb' c = make_swop2srgb_cform(varargin{:}); end %------------------------------------------------------------ function c = make_simple_cform(varargin) % Build a simple cform structure % Check for valid input narginchk(1, 1); validateattributes(varargin{1},{'char'},{'nonempty'},mfilename,'TRANSFORMTYPE',1); xform = lower(varargin{1}); % Construct a look up table for picking atomic functions cinfo = {'lab2lch', @lab2lch, 'lab','lch'; 'lch2lab', @lch2lab,'lch','lab'; 'upvpl2xyz', @upvpl2xyz,'upvpl','xyz'; 'xyz2upvpl',@xyz2upvpl,'xyz','upvpl'; 'uvl2xyz', @uvl2xyz, 'uvl', 'xyz'; 'xyz2uvl', @xyz2uvl,'xyz','uvl'; 'xyl2xyz', @xyl2xyz,'xyl','xyz'; 'xyz2xyl', @xyz2xyl,'xyz','xyl'}; persistent function_table; if isempty(function_table) for k = 1:size(cinfo,1) s.function = cinfo{k,2}; s.in_space = cinfo{k,3}; s.out_space = cinfo{k,4}; function_table.(cinfo{k,1}) = s; end end t = function_table.(xform); c = assigncform(t.function,t.in_space,t.out_space,'double',struct); %---------------------------------------------------------- function c = make_xyz2lab_or_lab2xyz_cform(varargin) wp = parseWPInputs('WhitePoint', varargin{:}); cdata.whitepoint = wp; % Construct a look up table for picking atomic functions cinfo = {'lab2xyz', @lab2xyz, 'lab','xyz'; 'xyz2lab', @xyz2lab,'xyz','lab'}; persistent labxyz_function_table; if isempty(labxyz_function_table) for k = 1:size(cinfo,1) s.function = cinfo{k,2}; s.in_space = cinfo{k,3}; s.out_space = cinfo{k,4}; labxyz_function_table.(cinfo{k,1}) = s; end end xform = lower(varargin{1}); t = labxyz_function_table.(xform); c = assigncform(t.function,t.in_space,t.out_space,'double',cdata); %---------------------------------------------------------- function c = make_srgb2swop_cform(varargin) % Check input args narginchk(1, 3); if nargin == 2 error(message('images:makecform:wrongNumInputs')); end % Set default rendering intents args.renderingintent = 'perceptual'; % Get Rendering intent information if it's given valid_property_strings = {'renderingintent'}; valid_value_strings = {'perceptual','relativecolorimetric', 'saturation',... 'absolutecolorimetric'}; if nargin > 1 prop_string = validatestring(varargin{2}, valid_property_strings, ... mfilename, 'PARAM', 2); value_string = validatestring(varargin{3}, valid_value_strings, ... mfilename, 'PARAM', 3); args.(prop_string) = value_string; end sRGB_profile = load_sRGB_profile(); swop_profile = load_swop_profile(); c = makecform('icc', sRGB_profile, swop_profile, 'SourceRenderingIntent',... args.renderingintent, 'DestRenderingIntent',args.renderingintent); %---------------------------------------------------------- function c = make_swop2srgb_cform(varargin) % Check input args narginchk(1, 3); if nargin == 2 error(message('images:makecform:wrongNumInputs')); end % Set default rendering intents args.renderingintent = 'perceptual'; % Get Rendering intent information if it's given valid_property_strings = {'renderingintent'}; valid_value_strings = {'perceptual','relativecolorimetric', 'saturation',... 'absolutecolorimetric'}; if nargin > 1 prop_string = validatestring(varargin{2}, valid_property_strings, ... mfilename, 'PARAM', 2); value_string = validatestring(varargin{3}, valid_value_strings, ... mfilename, 'PARAM', 3); args.(prop_string) = value_string; end sRGB_profile = load_sRGB_profile(); swop_profile = load_swop_profile(); c = makecform('icc', swop_profile, sRGB_profile, 'SourceRenderingIntent',... args.renderingintent, 'DestRenderingIntent',args.renderingintent); %---------------------------------------------------------- function c = make_srgb2lab_cform(varargin) wp = parseWPInputs('AdaptedWhitePoint', varargin{:}); srgb2xyz = makecform('srgb2xyz', 'AdaptedWhitePoint', wp); xyz2lab = makecform('xyz2lab', 'WhitePoint', wp); cdata.cforms = {srgb2xyz, xyz2lab}; c = assigncform(@applycformsequence, 'rgb', 'lab', 'double', cdata); %---------------------------------------------------------- function c = make_lab2srgb_cform(varargin) wp = parseWPInputs('AdaptedWhitePoint', varargin{:}); xyz2srgb = makecform('xyz2srgb', 'AdaptedWhitePoint', wp); lab2xyz = makecform('lab2xyz', 'WhitePoint', wp); cdata.forms = {lab2xyz, xyz2srgb}; c = assigncform(@applycformsequence, 'lab', 'rgb', 'double', cdata); %------------------------------------ function wp = parseWPInputs(param_name, varargin) narginchk(2, 4); switch nargin case 2 wp = whitepoint; case 3 error(message('images:makecform:paramValueIncomplete')) case 4 valid_strings = {param_name}; wp = parseWPInput(varargin{2}, varargin{3}, valid_strings, 'WP', 2); end %------------------------------------ function wp = parseWPInput(propname, propvalue, valid_strings, varname, varpos) narginchk(5, 5); if isempty(propname) || isempty(propvalue) wp = whitepoint; else validatestring(propname, valid_strings, mfilename, 'PROPERTYNAME', varpos); wp = propvalue; validateattributes(wp, {'double'}, ... {'real', '2d', 'nonsparse', 'finite', 'row', 'positive'}, ... mfilename, varname, varpos + 1); if size(wp, 2) ~= 3 error(message('images:makecform:invalidWhitePointData')) end end %------------------------------------------------------------ function c = make_clut_cform(profile,luttype) narginchk(1, 2); if nargin < 2 luttype = 'AToB0'; end % Check for valid input arguments if ~isicc(profile) error(message('images:makecform:invalidProfileNotICC')) end valid_luttag_strings = {'AToB0','AToB1','AToB2','AToB3','BToA0','BToA1','BToA2',.... 'BToA3','Gamut','Preview0','Preview1','Preview2'}; luttype = validatestring(luttype, lower(valid_luttag_strings), ... mfilename, 'LUTTYPE', 3); % Handle Abstract Profile as special case if strcmp(profile.Header.DeviceClass, 'abstract') luttype = 'atob0'; end % Since absolute rendering uses the rel. colorimetric tag, re-assign % luttype and set a flag. is_a2b3 = false; is_b2a3 = false; L = length(luttype); if strncmpi(luttype,'atob3',L) luttype = 'atob1'; is_a2b3 = true; elseif strncmpi(luttype,'btoa3',L) luttype = 'btoa1'; is_b2a3 = true; end % Get case sensitive luttag string luttype_idx = strmatch(luttype,lower(valid_luttag_strings),'exact'); luttype = valid_luttag_strings{luttype_idx}; % Check that the profile actually has the luttag if ~isfield(profile,luttype) error(message('images:makecform:invalidLutTag')) end c_fcn = @applyclut; luttag = profile.(luttype); cdata.luttag = luttag; % Figure out input/output colorspaces based on the name of the luttag starts_in_pcs = {'BToA0','BToA1','BToA2','BToA3','Gamut'}; starts_in_device_space = {'AToB0','AToB1','AToB2','AToB3'}; starts_and_ends_in_pcs = {'Preview0','Preview1','Preview2'}; switch luttype case starts_in_pcs inputcolorspace = profile.Header.ConnectionSpace; outputcolorspace = profile.Header.ColorSpace; case starts_in_device_space inputcolorspace = profile.Header.ColorSpace; outputcolorspace = profile.Header.ConnectionSpace; case starts_and_ends_in_pcs inputcolorspace = profile.Header.ConnectionSpace; outputcolorspace = inputcolorspace; end % Special case: Abstract Profile has A2B0, but starts and ends in PCS. if strcmp(profile.Header.DeviceClass, 'abstract') inputcolorspace = outputcolorspace; % PCS -> PCS end if strcmpi(inputcolorspace, 'xyz') cdata.isxyzin = true; else cdata.isxyzin = false; end if strcmpi(outputcolorspace, 'xyz') cdata.isxyzout = true; else cdata.isxyzout = false; end % Set up encoding if luttag.MFT == 1 % mft1 encoding = 'uint8'; elseif luttag.MFT <= 4 % mft2, mAB , mBA encoding = 'uint16'; else error(message('images:makecform:unsupportedTagType')) end % Make a sequence of cforms if they ask for absolute rendering if is_a2b3 % First insert the clut clut_cform = assigncform(c_fcn,inputcolorspace, outputcolorspace,encoding,cdata); seq_cdata.sequence.clut_cform = clut_cform; % Then insert the makeabsolute cform absolute_cform = makecform('makeabsolute',profile.Header.ConnectionSpace,'double',... profile.MediaWhitePoint,whitepoint); seq_cdata.sequence.convert_absolute = absolute_cform; % Make an icc sequence c = assigncform(@applyiccsequence,inputcolorspace,outputcolorspace,'uint16',seq_cdata); elseif is_b2a3 % First insert the makeabsolute cform clut_cform = assigncform(c_fcn,inputcolorspace, outputcolorspace,encoding,cdata); absolute_cform = makecform('makeabsolute',profile.Header.ConnectionSpace,'double',... whitepoint,profile.MediaWhitePoint); seq_cdata.sequence.convert_absolute = absolute_cform; % Then insert the clut seq_cdata.sequence.clut_cform = clut_cform; % Make an icc sequence c = assigncform(@applyiccsequence,inputcolorspace,outputcolorspace,'uint16',seq_cdata); else % Just make a clut cform c = assigncform(c_fcn, inputcolorspace, outputcolorspace, encoding, cdata); end % ------------------------------------------------------------ function c = make_mattrc_cform(varargin) narginchk(3, 5); % Check Profile or MatTRC argument if isicc(varargin{1}) pf = varargin{1}; if isfield(pf, 'MatTRC') && isstruct(pf.MatTRC) mattrc = pf.MatTRC; else error(message('images:makecform:missingMattrc')) end elseif isstruct(varargin{1}) mattrc = varargin{1}; pf = []; else error(message('images:makecform:invalidArgument')) end % Replace v. 4 fieldnames with v. 2 fieldnames if isfield(mattrc, 'RedMatrixColumn') mattrc.RedColorant = mattrc.RedMatrixColumn; end if isfield(mattrc, 'GreenMatrixColumn') mattrc.GreenColorant = mattrc.GreenMatrixColumn; end if isfield(mattrc, 'BlueMatrixColumn') mattrc.BlueColorant = mattrc.BlueMatrixColumn; end if ~is_valid_mattrc(mattrc) error(message('images:makecform:invalidMattrc')) end % Check direction arguments valid_propname_strings = {'direction'}; valid_propvalue_strings = {'forward', 'inverse'}; validatestring(varargin{2}, valid_propname_strings, ... mfilename, 'PROPERTYNAME', 2); direction = validatestring(varargin{3}, valid_propvalue_strings, ... mfilename, 'PROPERTYVALUE', 3); % Check (optional) rendering-intent arguments if nargin == 4 error(message('images:makecform:paramValueIncomplete')) elseif nargin > 4 valid_propname_strings = {'renderingintent'}; valid_propvalue_strings = {'relativecolorimetric', ... 'absolutecolorimetric'}; validatestring(varargin{4}, valid_propname_strings, ... mfilename, 'PROPERTYNAME', 4); intent = validatestring(varargin{5}, valid_propvalue_strings, ... mfilename, 'PROPERTYVALUE', 5); else intent = 'relativecolorimetric'; end % Assign correct atomic function and color spaces, % depending on direction. if strcmp(direction, 'forward') c_fcn = @applymattrc_fwd; space_in = 'rgb'; space_out ='xyz'; else c_fcn = @applymattrc_inv; space_in = 'xyz'; space_out = 'rgb'; end cdata.MatTRC = mattrc; % Make a sequence of cforms for absolute rendering if strcmpi(intent, 'absolutecolorimetric') if isempty(pf) error(message('images:makecform:absoluteRequiresProfile')) else mwp = pf.MediaWhitePoint; end mattrc_cform = assigncform(c_fcn, space_in, space_out, 'double', cdata); if strcmpi(direction, 'forward') % mattrc followed by makeabsolute seq_cdata.sequence.mattrc_cform = mattrc_cform; absolute_cform = makecform('makeabsolute', 'XYZ', 'double',... mwp, whitepoint); seq_cdata.sequence.convert_absolute = absolute_cform; else % makeabsolute followed by mattrc absolute_cform = makecform('makeabsolute', 'XYZ','double',... whitepoint, mwp); seq_cdata.sequence.convert_absolute = absolute_cform; seq_cdata.sequence.mattrc_cform = mattrc_cform; end % Make "icc" sequence c = assigncform(@applyiccsequence, space_in, space_out, ... 'uint16', seq_cdata); else % Make simple mattrc cform c = assigncform(c_fcn, space_in, space_out, 'double', cdata); end %------------------------------------------------------------ function c = make_graytrc_cform(varargin) narginchk(3, 5); pf = varargin{1}; if ~isicc(pf) error(message('images:makecform:invalidProfileNotICC')) end if ~isfield(pf, 'GrayTRC') error(message('images:makecform:missingGraytrc')) else graytrc = pf.GrayTRC; end invalidGraytrc = isempty(graytrc) || ... ~(isa(graytrc, 'uint16') || isa(graytrc, 'struct')); if invalidGraytrc error(message('images:makecform:invalidGraytrc')) end % Check direction arguments valid_propname_strings = {'direction'}; valid_propvalue_strings = {'forward', 'inverse'}; validatestring(varargin{2}, valid_propname_strings, ... mfilename, 'PROPERTYNAME', 2); direction = validatestring(varargin{3}, valid_propvalue_strings, ... mfilename, 'PROPERTYVALUE', 3); % check (optional) rendering-intent arguments if nargin == 4 error(message('images:makecform:paramValueIncomplete')) elseif nargin > 4 valid_propname_strings = {'renderingintent'}; valid_propvalue_strings = {'relativecolorimetric', ... 'absolutecolorimetric'}; validatestring(varargin{4}, valid_propname_strings, ... mfilename, 'PROPERTYNAME', 4); intent = validatestring(varargin{5}, valid_propvalue_strings, ... mfilename, 'PROPERTYVALUE', 5); else intent = 'relativecolorimetric'; end % Assign correct atomic function and color spaces, % depending on direction. if strcmp(direction, 'forward') c_fcn = @applygraytrc_fwd; space_in = 'gray'; space_out = pf.Header.ConnectionSpace; else c_fcn = @applygraytrc_inv; space_in = pf.Header.ConnectionSpace; space_out = 'gray'; end cdata.GrayTRC = graytrc; cdata.ConnectionSpace = pf.Header.ConnectionSpace; % Make a sequence of cforms for absolute rendering if strcmpi(intent, 'absolutecolorimetric') graytrc_cform = assigncform(c_fcn, space_in, space_out, 'double', cdata); mwp = pf.MediaWhitePoint; if strcmpi(direction, 'forward') % graytrc followed by makeabsolute seq_cdata.sequence.graytrc_cform = graytrc_cform; absolute_cform = makecform('makeabsolute', cdata.ConnectionSpace, ... 'double', mwp, whitepoint); seq_cdata.sequence.convert_absolute = absolute_cform; else % makeabsolute followed by graytrc absolute_cform = makecform('makeabsolute', cdata.ConnectionSpace, ... 'double', whitepoint, mwp); seq_cdata.sequence.convert_absolute = absolute_cform; seq_cdata.sequence.graytrc_cform = graytrc_cform; end % Make "icc" sequence c = assigncform(@applyiccsequence, space_in, space_out, ... 'uint16', seq_cdata); else % Make simple graytrc cform c = assigncform(c_fcn, space_in, space_out, 'double', cdata); end %------------------------------------------------------------ function c = make_named_cform(varargin) narginchk(1, 2); pf = varargin{1}; if ~isfield(pf, 'NamedColor2') error(message('images:makecform:missingNamedColor2')) elseif ~isfield(pf.NamedColor2, 'NameTable') error(message('images:makecform:missingNameTable')) else cdata.NameTable = pf.NamedColor2.NameTable; end cdata.Space = varargin{2}; c_fcn = @applynamedcolor; space_in = 'char'; if strcmpi(cdata.Space, 'pcs') space_out = pf.Header.ConnectionSpace; elseif strcmpi(cdata.Space, 'device') space_out = pf.Header.ColorSpace; else error(message('images:makecform:invalidInputData')) end c = assigncform(c_fcn, space_in, space_out, 'name', cdata); %------------------------------------------------------------ function c = make_icc_cform(varargin) narginchk(2, 6); % Set default rendering intents args.sourcerenderingintent ='perceptual'; args.destrenderingintent = 'perceptual'; % Get rendering intent information if it's given valid_property_strings = {'sourcerenderingintent', 'destrenderingintent'}; valid_value_strings = {'perceptual', 'relativecolorimetric', 'saturation',... 'absolutecolorimetric'}; if nargin > 2 for k=3:2:nargin prop_string = validatestring(varargin{k}, valid_property_strings, ... mfilename, 'PROPERTYNAME', k); value_string = validatestring(varargin{k+1}, valid_value_strings, ... mfilename, 'PROPERTYVALUE', k+1); args.(prop_string) = value_string; end end source_intent_num = int2str(strmatch(args.sourcerenderingintent,valid_value_strings)-1); dest_intent_num = int2str(strmatch(args.destrenderingintent,valid_value_strings)-1); % Get the source profile source_pf = varargin{1}; if ~isicc(source_pf) error(message('images:makecform:invalidSourceProfile')) end if strcmp(source_pf.Header.DeviceClass, 'device link') error(message('images:makecform:invalidSourceProfileDeviceLink')) end % Get the destination profile dest_pf = varargin{2}; if ~isicc(dest_pf) error(message('images:makecform:invalidDestinationProfile')) end if strcmp(dest_pf.Header.DeviceClass, 'device link') error(message('images:makecform:invalidDestinationProfileDeviceLink')) end % Flags that are used later to determine connection space source_isMatTRC = false; dest_isMatTRC = false; % Select transform from source profile according to priority rule first_try = strcat('AToB', source_intent_num); second_try = strcat('MatTRC'); if isfield(source_pf, first_try) source_cform = makecform('clut', source_pf, first_try); elseif strcmp(first_try, 'AToB3') && isfield(source_pf, 'AToB1') source_cform = makecform('clut', source_pf, 'AToB1'); elseif isfield(source_pf, 'AToB0') % fallback strategy: perceptual source_cform = makecform('clut', source_pf, 'AToB0'); elseif isfield(source_pf, second_try) source_isMatTRC = true; source_cform = makecform('mattrc',source_pf.(second_try),'Direction','forward'); elseif isfield(source_pf, 'GrayTRC') source_cform = makecform('graytrc', source_pf, 'Direction', 'forward'); else error(message('images:makecform:missingAToBxMatTRCGrayTRC')) end % Select transform from destination profile according to priority rule first_try = strcat('BToA', dest_intent_num); second_try = strcat('MatTRC'); if isfield(dest_pf,first_try) dest_cform = makecform('clut', dest_pf, first_try); elseif strcmp(first_try, 'BToA3') && isfield(dest_pf, 'BToA1') dest_cform = makecform('clut', dest_pf, 'BToA1'); elseif isfield(dest_pf, 'BToA0') dest_cform = makecform('clut', dest_pf, 'BToA0'); elseif strcmp(dest_pf.Header.DeviceClass, 'abstract') && ... isfield(dest_pf, 'AToB0') dest_cform = makecform('clut', dest_pf, 'AToB0'); elseif isfield(dest_pf,second_try) dest_isMatTRC = true; dest_cform = makecform('mattrc',dest_pf.(second_try),'Direction','inverse'); elseif isfield(dest_pf, 'GrayTRC') dest_cform = makecform('graytrc', dest_pf, 'Direction', 'inverse'); else error(message('images:makecform:invalidDestProfile')) end % Set flags for absolute-colorimetric rendering. % Make sure the user didn't ask for absolute on the source and relative on % the destination profile. In any event, if the destination is absolute, % the entire path is absolute. source_absolute = strncmp(args.sourcerenderingintent, ... 'absolutecolorimetric',... length(args.sourcerenderingintent)); dest_absolute = strncmp(args.destrenderingintent, ... 'absolutecolorimetric',... length(args.destrenderingintent)); if source_absolute && ~dest_absolute error(message('images:makecform:invalidRenderingIntents')) else path_is_absolute = dest_absolute; end % Check to see if PCS's match. If not, the PCS's will have to be % reconciled with a third cform that connects the two. source_pcs_is_xyz = source_isMatTRC || ... strcmp(deblank(lower(source_pf.Header.ConnectionSpace)), 'xyz'); dest_pcs_is_xyz = dest_isMatTRC || ... strcmp(deblank(lower(dest_pf.Header.ConnectionSpace)), 'xyz'); needs_gendermender = (source_pcs_is_xyz ~= dest_pcs_is_xyz); % Check for mismatch in PCS interpretation due to profile version mismatch % (non-colorimetric intents only). Reference-medium black point has Y = 0 % in Version 2 (and preceding) and has Y = 0.0034731 in Version 4. L = length(args.destrenderingintent); if strncmp(args.destrenderingintent, 'perceptual', L) || ... strncmp(args.destrenderingintent, 'saturation', L) source_version = sscanf(source_pf.Header.Version(1), '%d%'); dest_version = sscanf(dest_pf.Header.Version(1), '%d%'); if source_version <= 2 && dest_version > 2 upconvert_blackpoint = 1; % convert version 2 to version 4 elseif source_version > 2 && dest_version <= 2 upconvert_blackpoint = -1; % convert version 4 to version 2 else upconvert_blackpoint = 0; % no mismatch, no conversion end else upconvert_blackpoint = 0; % colorimetric intent, no conversion end % Now construct the sequence of cforms to be packed into the cdata % of this main cform. The sequence might require some xyz2lab or lab2xyz % cforms to accommodate a mismatch in PCSs between the profiles. In % addition, a 'makeabsolute' cform may be inserted if the user asks for % the absolute rendering intent. % Put the source profile first in the sequence. It's always first. cdata.sequence.source = source_cform; % Set sequence encoding to fixed value of 'uint16'. MathWorks developers - % see correspondence from Bob Poe in devel/ip/ipt/tech_refs/makecform. sequence_encoding = 'uint16'; % Do PCS corrections preferentially in XYZ, as needed. if source_pcs_is_xyz % Insert a cform to convert to absolute if needed. if path_is_absolute absolute_cform = makecform('makeabsolute', 'xyz', 'double',... source_pf.MediaWhitePoint, dest_pf.MediaWhitePoint); cdata.sequence.convert_absolute = absolute_cform; % Insert a cform to convert black point if needed. elseif upconvert_blackpoint ~= 0 fix_black_cform = makecform('makeblackfix', 'xyz', 'double', ... upconvert_blackpoint); cdata.sequence.fix_black = fix_black_cform; end end % Insert a lab2xyz or xyz2lab if needed if needs_gendermender if source_pcs_is_xyz fix_pcs_cform = makecform('xyz2lab', 'whitepoint', whitepoint); else fix_pcs_cform = makecform('lab2xyz', 'whitepoint', whitepoint); end cdata.sequence.fix_pcs = fix_pcs_cform; % Do PCS corrections preferentially in XYZ, as needed. if dest_pcs_is_xyz % Insert a cform to convert to absolute if needed. if path_is_absolute absolute_cform = makecform('makeabsolute', 'xyz', 'double',... source_pf.MediaWhitePoint,dest_pf.MediaWhitePoint); cdata.sequence.convert_absolute = absolute_cform; % Insert a cform to convert black point if needed. elseif upconvert_blackpoint ~= 0 fix_black_cform = makecform('makeblackfix', 'xyz', 'double', ... upconvert_blackpoint); cdata.sequence.fix_black = fix_black_cform; end end end % If neither PCS is XYZ, resort to Lab conversions as needed. if ~source_pcs_is_xyz && ~dest_pcs_is_xyz % Insert absolute conversion if needed. if path_is_absolute absolute_cform = makecform('makeabsolute', 'lab', 'double',... source_pf.MediaWhitePoint,dest_pf.MediaWhitePoint); cdata.sequence.convert_absolute = absolute_cform; % Insert black-point conversion if needed. elseif upconvert_blackpoint ~= 0 fix_black_cform = makecform('makeblackfix', 'lab', 'double', ... upconvert_blackpoint); cdata.sequence.fix_black = fix_black_cform; end end % Insert the destination profile into the sequence. cdata.sequence.destination = dest_cform; % Assign c_fcn c_fcn = @applyiccsequence; % Make the main cform c = assigncform(c_fcn,source_pf.Header.ColorSpace,dest_pf.Header.ColorSpace,... sequence_encoding,cdata); %------------------------------------------------------------ function c = make_adapt_cform(varargin) % Check input args: narginchk(5, 7); % Get white-point XYZs, starting and ending: wps = parseWPInput(varargin{2}, varargin{3}, {'WhiteStart'}, 'WPS', 2); wpe = parseWPInput(varargin{4}, varargin{5}, {'WhiteEnd'}, 'WPE', 4); % Get chromatic-adaptation-model name: if nargin < 6 adapttype = 'bradford'; else validatestring(varargin{6}, {'AdaptModel'}, mfilename, 'PROPERTYNAME', 6); if nargin < 7 adapttype = 'bradford'; else adapttype = validatestring(varargin{7}, {'VonKries' 'Bradford'}, ... mfilename, 'MODELNAME', 7); end end % Get adaptation-model matrix (XYZ -> primaries): if strcmpi(adapttype, 'Bradford') chad = [ 0.8951 0.2664 -0.1614; ... -0.7502 1.7135 0.0367; ... 0.0389 -0.0685 1.0296 ]; elseif strcmpi(adapttype, 'VonKries') chad = [ 0.40024 0.70760 -0.08081; ... -0.22630 1.16532 0.04570; ... 0.0 0.0 0.91822 ]; else error(message('images:makecform:AdaptModelNotSupported', adapttype)) end % Convert white points from XYZ to primaries: rgbs = wps * chad'; rgbe = wpe * chad'; % Construct chromatic-adaptation matrix: rgbscale = diag(rgbe ./ rgbs); cdata.adapter = chad \ rgbscale * chad; % Construct cform: c = assigncform(@applychad, 'XYZ', 'XYZ', 'double', cdata); %------------------------------------------------------------ function c = make_absolute_cform(cspace,encoding,source_wp,dest_wp) % This is a private cform. It is only constructed under the hood. No doc for % this type of cform needed. cdata.colorspace = cspace; cdata.source_whitepoint = source_wp; cdata.dest_whitepoint = dest_wp; c = assigncform(@applyabsolute,cspace,cspace,encoding,cdata); %------------------------------------------------------------ function c = make_blackpoint_cform(cspace, encoding, upconvert_blackpoint) % This is a private cform. It is only constructed under the hood. No doc for % this type of cform needed. cdata.colorspace = cspace; cdata.upconvert = upconvert_blackpoint; c = assigncform(@applyblackpoint, cspace, cspace, encoding, cdata); %------------------------------------------------------------ function c = make_srgb2xyz_or_xyz2srgb_cform(varargin) wp = parseWPInputs('AdaptedWhitePoint', varargin{:}); sRGB_profile = load_sRGB_profile(); if strcmpi(varargin{1}, 'srgb2xyz') direction = 'forward'; else direction = 'inverse'; end main_cform = makecform('mattrc', sRGB_profile.MatTRC, 'Direction', direction); if isequal(wp, whitepoint('D50')) c = main_cform; else if strcmp(direction, 'forward') adapt = makecform('adapt', 'WhiteStart', whitepoint('D50'), ... 'WhiteEnd', wp, ... 'AdaptModel', 'Bradford'); cdata.cforms = {main_cform, adapt}; c = assigncform(@applycformsequence, 'rgb', 'xyz', 'double', cdata); else adapt = makecform('adapt', 'WhiteStart', wp, ... 'WhiteEnd', whitepoint('D50'), ... 'AdaptModel', 'Bradford'); cdata.cforms = {adapt, main_cform}; c = assigncform(@applycformsequence, 'xyz', 'rgb', 'double', cdata); end end % ------------------------------------------------------------ function c = assigncform(c_func,space_in,space_out,encoding,cdata) % make the cform struct c.c_func = c_func; c.ColorSpace_in = space_in; c.ColorSpace_out = space_out; c.encoding = encoding; c.cdata = cdata; % ------------------------------------------------------------ function out = is_valid_mattrc(mattrc) has_redc = isfield(mattrc,'RedColorant'); has_greenc = isfield(mattrc,'GreenColorant'); has_bluec = isfield(mattrc,'BlueColorant'); has_redtrc = isfield(mattrc,'RedTRC'); has_greentrc = isfield(mattrc,'GreenTRC'); has_bluetrc = isfield(mattrc,'BlueTRC'); if (has_redc && has_greenc && has_bluec && has_redtrc && has_greentrc ... && has_bluetrc) out = true; % Check data types if isempty(mattrc.RedColorant) || ~isa(mattrc.RedColorant,'double') out = false; elseif isempty(mattrc.GreenColorant) || ~isa(mattrc.GreenColorant,'double') out = false; elseif isempty(mattrc.BlueColorant) || ~isa(mattrc.BlueColorant,'double') out = false; elseif isempty(mattrc.RedTRC) || (~isa(mattrc.RedTRC,'uint16') && ~isa(mattrc.RedTRC,'struct')) out = false; elseif isempty(mattrc.GreenTRC) || (~isa(mattrc.GreenTRC,'uint16') && ~isa(mattrc.GreenTRC,'struct')) out = false; elseif isempty(mattrc.BlueTRC) || (~isa(mattrc.BlueTRC,'uint16') && ~isa(mattrc.BlueTRC,'struct')) out = false; end else out = false; end % ------------------------------------------------------------ function out = load_sRGB_profile() persistent sRGB_profile if isempty(sRGB_profile) sRGB_profile = iccread('sRGB.icm'); end out = sRGB_profile; % ------------------------------------------------------------ function out = load_swop_profile() persistent swop_profile if isempty(swop_profile) swop_profile = iccread('swopcmyk.icm'); end out = swop_profile;
github
wangsuyuan/Imageprocesingtoobox-master
rgb2ntsc.m
.m
Imageprocesingtoobox-master/colorspaces/rgb2ntsc.m
2,155
utf_8
c1817a124ab55d7f48380db742b39eda
function varargout = rgb2ntsc(varargin) %RGB2NTSC Convert RGB color values to NTSC color space. % YIQMAP = RGB2NTSC(RGBMAP) converts the M-by-3 RGB values in RGBMAP to NTSC % colorspace. YIQMAP is an M-by-3 matrix that contains the NTSC luminance % (Y) and chrominance (I and Q) color components as columns that are % equivalent to the colors in the RGB colormap. % % YIQ = RGB2NTSC(RGB) converts the truecolor image RGB to the equivalent % NTSC image YIQ. % % Class Support % ------------- % RGB can be uint8, uint16, int16, double, or single. RGBMAP can be double. % The output is double. % % Examples % -------- % I = imread('board.tif'); % J = rgb2ntsc(I); % % map = jet(256); % newmap = rgb2ntsc(map); % % See also NTSC2RGB, RGB2IND, IND2RGB, IND2GRAY. % Copyright 1992-2010 The MathWorks, Inc. A = parse_inputs(varargin{:}); T = [1.0 0.956 0.621; 1.0 -0.272 -0.647; 1.0 -1.106 1.703].'; [so(1) so(2) thirdD] = size(A); if thirdD == 1,% A is RGBMAP, M-by-3 colormap A = A/T; else % A is truecolor image RBG A = reshape(reshape(A,so(1)*so(2),thirdD)/T,so(1),so(2),thirdD); end; % Output if nargout < 2,% YIQMAP = RGB2NTSC(RGBMAP) varargout{1} = A; else error(message('images:rgb2ntsc:wrongNumberOfOutputArguments', nargout)); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Function: parse_inputs % function A = parse_inputs(varargin) narginchk(1,1); % rgb2ntsc(RGB) or rgb2ntsc(RGBMAP) A = varargin{1}; %no logical if islogical(A) error(message('images:rgb2ntsc:invalidType')) end % Check validity of the input parameters. A is converted to double because YIQ % colorspace can contain negative values. if ndims(A)==2 % Check colormap if ( size(A,2)~=3 || size(A,1) < 1 ) error(message('images:rgb2ntsc:invalidColormap')) end if ~isa(A,'double') warning(message('images:rgb2ntsc:colormapRange')) A = im2double(A); end elseif ndims(A)==3 % Check RGB if size(A,3)~=3 error(message('images:rgb2ntsc:invalidTruecolorImage')) end A = im2double(A); else error(message('images:rgb2ntsc:invalidSize')) end
github
wangsuyuan/Imageprocesingtoobox-master
iccfind.m
.m
Imageprocesingtoobox-master/colorspaces/iccfind.m
2,347
utf_8
c8d16b35ecb58d37c771a8ad23299421
function [profiles, descriptions] = iccfind(directory, pattern) %ICCFIND Search for ICC profiles by description. % [PROFILES, DESCRIPTIONS] = ICCFIND(DIRECTORY, PATTERN) searches for all % of the ICC profiles in the specified DIRECTORY with a given PATTERN in % their Description fields. PROFILES is a cell array of profile % structures. DESCRIPTIONS is a cell array of matching Description % fields. ICCFIND performs case-insensitive pattern matching. % % [PROFILES, DESCRIPTIONS] = ICCFIND(DIRECTORY) returns all of the % profiles and their descriptions for the given directory. % % Note: % % To improve performance, ICCFIND caches copies of the ICC profiles in % memory. Adding or modifying profiles may not change the results of % ICCFIND. Issuing the "clear functions" command will clear the % cache. % % Examples: % % % (1) Get all of the ICC profiles in the default location. % profiles = iccfind(iccroot); % % % (2) Find the profiles whose descriptions contain "RGB". % [profiles, descriptions] = iccfind(iccroot, 'rgb'); % % See also ICCREAD, ICCROOT, ICCWRITE. % Copyright 1993-2011 The MathWorks, Inc. % Process input arguments. narginchk(1, 2) % Get all of the profiles from the specified directory. allProfiles = iccProfileCache(directory); allDescriptions = getDescriptions(allProfiles); % If no pattern was given, return all profiles. if (nargin == 1) profiles = allProfiles; descriptions = allDescriptions; return end % Find all of the profiles with the given pattern in their description. matchIndices = strfind(lower(allDescriptions), lower(pattern)); descriptions = {}; profiles = {}; for idx = 1:numel(matchIndices) if (~isempty(matchIndices{idx})) % Store matching profiles in the output. descriptions{end + 1} = allDescriptions{idx}; profiles{end + 1} = allProfiles{idx}; end end % For readability return a columnar cell array. descriptions = descriptions'; profiles = profiles'; function allDescriptions = getDescriptions(allProfiles) %getDescriptions Return a cell array of the profiles' descriptions. allDescriptions = cell(numel(allProfiles), 1); for idx = 1:numel(allProfiles) allDescriptions{idx} = allProfiles{idx}.Description.String; end
github
wangsuyuan/Imageprocesingtoobox-master
ycbcr2rgb.m
.m
Imageprocesingtoobox-master/colorspaces/ycbcr2rgb.m
4,415
utf_8
bd91bb3c97671f4fc9756eca73a1f0c9
function rgb = ycbcr2rgb(varargin) %YCBCR2RGB Convert YCbCr color values to RGB color space. % RGBMAP = YCBCR2RGB(YCBCRMAP) converts the YCbCr values in the colormap % YCBCRMAP to the RGB color space. If YCBCRMAP is M-by-3 and contains the % YCbCr luminance (Y) and chrominance (Cb and Cr) color values as columns, % then RGBMAP is an M-by-3 matrix that contains the red, green, and blue % values equivalent to those colors. % % RGB = YCBCR2RGB(YCBCR) converts the YCbCr image to the equivalent % truecolor image RGB. % % Class Support % ------------- % If the input is a YCbCr image, it can be of class uint8, uint16, or % double; the output image is of the same class as the input image. If the % input is a colormap, the input and output colormaps are both of class % double. % % Example % ------- % Convert image from RGB space to YCbCr space and back. % % rgb = imread('board.tif'); % ycbcr = rgb2ycbcr(rgb); % rgb2 = ycbcr2rgb(ycbcr); % % See also NTSC2RGB, RGB2NTSC, RGB2YCBCR. % Copyright 1993-2010 The MathWorks, Inc. % References: % Charles A. Poynton, "A Technical Introduction to Digital Video", % John Wiley & Sons, Inc., 1996, p. 175-176 % % Rec. ITU-R BT.601-5, "STUDIO ENCODING PARAMETERS OF DIGITAL TELEVISION % FOR STANDARD 4:3 AND WIDE-SCREEN 16:9 ASPECT RATIOS", % (1982-1986-1990-1992-1994-1995), Section 3.5. ycbcr = parse_inputs(varargin{:}); isColormap = false; %must reshape colormap to be m x n x 3 for transformation if ndims(ycbcr) == 2 isColormap = true; colors = size(ycbcr,1); ycbcr = reshape(ycbcr, [colors 1 3]); end % This matrix comes from a formula in Poynton's, "Introduction to % Digital Video" (p. 176, equations 9.6 and 9.7). % T is from equation 9.6: ycbcr = T * rgb + offset; T = [65.481 128.553 24.966;... -37.797 -74.203 112; ... 112 -93.786 -18.214]; % We can rewrite the equation in terms of ycbcr which is % T ^-1 * (ycbcr - offset) = rgb. This is equation 9.7 in the book. Tinv = T^-1; % Tinv = [0.00456621 0. 0.00625893;... % 0.00456621 -0.00153632 -0.00318811;... % 0.00456621 0.00791071 0.] offset = [16;128;128]; % The formula Tinv * (ycbcr - offset) = rgb converts 8-bit YCbCr data to a RGB % image that is scaled between 0 and one. For each class type (double,uint8, % uint16), we must calculate scaling factors for Tinv and offset so that % the input image is scaled between 0 and 255, and so that the output image is % in the range of the respective class type. scaleFactor.double.T = 255; % scale input so it is in range [0 255]. scaleFactor.double.offset = 1; % output already in range [0 1]. scaleFactor.uint8.T = 255; % scale output so it is in range [0 255]. scaleFactor.uint8.offset = 255; % scale output so it is in range [0 255]. scaleFactor.uint16.T = 65535/257; % scale input so it is in range [0 255] % (65535/257 = 255), % and scale output so it is in range % [0 65535]. scaleFactor.uint16.offset = 65535; % scale output so it is in range [0 65535]. % The formula Tinv * (ycbcr - offset) = rgb is rewritten as % scaleFactorForT*Tinv*ycbcr - scaleFactorForOffset*Tinv*offset = rgb. % To use imlincomb, we rewrite the formula as T * ycbcr - offset, where % T and offset are defined below. classIn = class(ycbcr); T = scaleFactor.(classIn).T * Tinv; offset = scaleFactor.(classIn).offset * Tinv * offset; rgb = zeros(size(ycbcr),classIn); for p = 1:3 rgb(:,:,p) = imlincomb(T(p,1),ycbcr(:,:,1),T(p,2),ycbcr(:,:,2), ... T(p,3),ycbcr(:,:,3),-offset(p)); end if isColormap rgb = reshape(rgb, [colors 3 1]); end if isa(rgb,'double') rgb = min(max(rgb,0.0),1.0); end %%% %Parse Inputs %%% function X = parse_inputs(varargin) narginchk(1,1); X = varargin{1}; if ndims(X) == 2 validateattributes(X,{'uint8','uint16','double'},{'real' 'nonempty'}, ... mfilename,'MAP',1); if (size(X,2) ~=3 || size(X,1) < 1) error(message('images:ycbcr2rgb:invalidSizeForColormap')) end elseif ndims(X) == 3 validateattributes(X,{'uint8','uint16','double'},{'real'},mfilename,'RGB',1); if (size(X,3) ~=3) error(message('images:ycbcr2rgb:invalidTruecolorImage')) end else error(message('images:ycbcr2rgb:invalidInputSize')) end
github
wangsuyuan/Imageprocesingtoobox-master
applycform.m
.m
Imageprocesingtoobox-master/colorspaces/applycform.m
5,745
utf_8
58e0ec6842bc76e39002893354a82217
function out = applycform(in,c) %APPLYCFORM Apply device-independent color space transformation. % B = APPLYCFORM(A, C) converts the color values in A to the color space % specified in the color transformation structure, C. The color % transformation structure specifies various parameters of the % transformation. See MAKECFORM for details. % % If A is two-dimensional, APPLYCFORM interprets each row in A as a color % unless the color transformation structure contains a grayscale ICC % profile (see Note for this case). A may have 1 or more columns, % depending on the input color space. B has the same number of rows and % 1 or more columns, depending on the output color space. (The ICC spec % currently supports up to 15-channel device spaces.) % % If A is three-dimensional, APPLYCFORM interprets each row-column % location as a color, and SIZE(A, 3) may be 1 or more, depending on the % input color space. B has the same number of rows and columns as A, and % SIZE(B, 3) is 1 or more, depending on the output color space. % % Note % ---- % If the color transformation structure C contains a grayscale ICC % profile, APPLYCFORM interprets each pixel in A as a color. A can have % any number of columns. B has the same size as A. % % Class Support % ------------- % A is a real, nonsparse array of class uint8, uint16, or double or a % string. A is only a string if C was created with the following syntax: % % C = makecform('named', profile, space) % % B has the same class as A unless the output color space is XYZ. Since % there is no standard 8-bit representation of XYZ values, B is of class % uint16 if the input is of class uint8. % % Example % ------- % Convert RGB image to L*a*b*, assuming input image is sRGB. % % rgb = imread('peppers.png'); % cform = makecform('srgb2lab'); % lab = applycform(rgb, cform); % % See also MAKECFORM, LAB2DOUBLE, LAB2UINT8, LAB2UINT16, WHITEPOINT, % XYZ2DOUBLE, XYZ2UINT16. % Copyright 2002-2010 The MathWorks, Inc. % Original Authors: Scott Gregory, Toshia McCabe 10/18/02 % Check color transformation structure check_cform(c); % Handle color-name data as special case if ischar(in) if strcmp(c.encoding, 'name') cdata = struct2cell(c.cdata)'; out = c.c_func(in, cdata{:}); return; else error(message('images:applycform:invalidNamedColorCform')); end end % Check to make sure IN is of correct class and attributes validateattributes(in,{'double','uint8','uint16'}, ... {'real','nonsparse','finite'},'applycform','IN',1); % Get dimensions of input data, then rearrange data so that columns % correspond to color channels. Each row is a color vector. [num_rows input_color_dim] = check_input_image_dimensions(in, c); num_input_color_channels = size(in, input_color_dim); columndata = reshape(in, [], num_input_color_channels); % Check the encoding of the data against what's expected % in the atomic functions and convert the data appropriately % to the right encoding. input_encoding = class(in); columndata = encode_color(columndata, c.ColorSpace_in,... input_encoding, c.encoding); % Get arguments to atomic function from c.cdata cdata = struct2cell(c.cdata)'; % Call the function with the argument list state = warning('off', 'images:encode_color:outputEncodingIgnored'); try out = c.c_func(columndata, cdata{:}); catch ME % We want to restore warning state even if the function errors warning(state) rethrow(ME); end warning(state); % Make sure output encoding is the same as input encoding. % The only exception occurs when uint8 data are processed through % a cform that results in PCS XYZ. In this case, the result % will be uint16 XYZ values, since there is no uint8 encoding % defined for XYZ. if ~strcmp(class(out), input_encoding) if strcmpi(c.ColorSpace_out, 'xyz') && ... ~strcmpi(input_encoding, 'double') out = encode_color(out, 'xyz', lower(class(out)), 'uint16'); else out = encode_color(out, lower(c.ColorSpace_out), ... lower(class(out)), input_encoding); end end % Reshape the output data if needed to restore input geometry if input_color_dim == 3 && ~strcmpi(c.ColorSpace_in, 'gray') out = reshape(out, num_rows, [], size(out,2)); end %-------------------------------------------------------------------------- function [nrows color_dim] = check_input_image_dimensions(in, c) nrows = size(in, 1); if ndims(in) == 2 color_dim = 2; if strcmpi(c.ColorSpace_in, 'gray') %special case: only 1 color channel;size(2dImage,3) is 1 color_dim = 3; end elseif ndims(in) == 3 color_dim = 3; else error(message('images:applycform:wrongDataDimensions')); end %-------------------------------------------------------------------------- function check_cform(c) if isstruct(c) proper_fields = isfield(c, ... {'c_func', 'ColorSpace_in', 'ColorSpace_out', 'encoding', 'cdata'}); if all(proper_fields) bad_c_func = isempty(c.c_func) || ~isa(c.c_func,'function_handle'); isStringInvalid = @(stringValue) isempty(stringValue) || ~ischar(stringValue); bad_ColorSpace_in = isStringInvalid(c.ColorSpace_in); bad_ColorSpace_out = isStringInvalid(c.ColorSpace_out); bad_encoding = isStringInvalid(c.encoding); bad_cdata = isempty(c.cdata) || ~isstruct(c.cdata); bad_data = any([bad_c_func, bad_ColorSpace_in, bad_ColorSpace_out, bad_encoding, bad_cdata]); else bad_data = true; end else bad_data = true; end if bad_data error(message('images:applycform:invalidCform')); end
github
wangsuyuan/Imageprocesingtoobox-master
iccread.m
.m
Imageprocesingtoobox-master/colorspaces/iccread.m
54,080
utf_8
f0e7a81484e12539e0c6849c6ab93e62
function s = iccread(filename) %ICCREAD Read ICC color profile. % P = ICCREAD(FILENAME) reads the International Color Consortium (ICC) % color profile data from the file specified by FILENAME. The file can % be either an ICC profile file or a TIFF file containing an embedded % ICC profile. ICCREAD returns the profile information in the % structure P, which can be used by MAKECFORM and APPLYCFORM to compute % color space transformations. P can also be written to a new % ICC profile file by ICCWRITE. Both Version 2 and Version 4 % of the ICC specification are supported. % % The reference page for ICCREAD has additional information about the % fields of the structure P. For complete details, see the % specifications ICC.1:2001-04 for Version 2 and ICC.1:2001-12 % for Version 4.0 or ICC.1:2004-10 for Version 4.2.0.0 (available % at www.color.org). % % Example % ------- % Read in the sRGB profile. % % P = iccread('sRGB.icm'); % % See also ISICC, ICCWRITE, MAKECFORM, APPLYCFORM. % Copyright 2002-2013 The MathWorks, Inc. % Check input argument narginchk(1,1); validateattributes(filename,{'char'},{'nonempty'},'iccread','FILENAME',1); % Check to see that FILENAME is actually a file that exists if exist(filename,'file') ~= 2 % Look in the system's ICC profile repository. try repository = iccroot; catch repository = ''; end if (exist(fullfile(repository, filename), 'file')) filename = fullfile(iccroot, filename); else error(message('images:iccread:fileNotFound')) end end if istif(filename) info = imfinfo(filename); if ~isfield(info,'ICCProfileOffset') error(message('images:iccread:noProfileInTiffFile')) end start = info.ICCProfileOffset; elseif isiccprof(filename) start = 0; else error(message('images:iccread:unrecognizedFileType')) end % "All profile data must be encoded as big-endian." Clause 6 [fid,msg] = fopen(filename,'r','b'); if (fid < 0) error(message('images:iccread:errorOpeningProfile', filename, msg)); end s = iccread_embedded(fid, start); fclose(fid); s.Filename = filename; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function tf = isiccprof(filename) tf = false; fid = fopen(filename, 'r', 'b'); if (fid < 0) fclose(fid); return; end [~, count] = fread(fid, 3, 'uint32'); if count ~= 3 fclose(fid); return; end [device_class_code, count] = fread(fid, 4, 'uchar'); if count ~= 4 fclose(fid); return; end valid_device_classes = get_device_classes; if any(strcmp(char(device_class_code'), valid_device_classes(:, 1))) tf = true; end fclose(fid); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function tf = istif(filename) fid = fopen(filename, 'r', 'ieee-le'); if (fid < 0) tf = false; else sig = fread(fid, 4, 'uint8'); fclose(fid); tf = isequal(sig, [73; 73; 42; 0]) | isequal(sig, [77; 77; 0; 42]); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function s = iccread_embedded(fid, start) % ICCREAD_EMBEDDED(FID, START) reads ICC profile data using the file % identifier FID, starting at byte offset location START, as measured % from the beginning of the file. fseek_check(fid, start, 'bof'); s.Header = read_header(fid); version = sscanf(s.Header.Version(1), '%d%'); % Skip past header -- 128 bytes (Clause 6.1) fseek_check(fid, start + 128, 'bof'); % Use fixed length of header % Read the Tag Table tag_count = fread_check(fid, 1, 'uint32'); tag_table = cell(tag_count,3); for k = 1:tag_count tag_table{k,1} = char(fread_check(fid, 4, '*uint8'))'; tag_table{k,2} = fread_check(fid, 1, 'uint32'); tag_table{k,3} = fread_check(fid, 1, 'uint32'); end s.TagTable = tag_table; % Build up a list of defined public tags public_tagnames = get_public_tagnames(version); mattrc_tagnames = get_mattrc_tagnames(version); private_tags = cell(0,0); has_mattrc = false; % Go through each tag in the tag table for k = 1:size(s.TagTable,1) signature = deblank(s.TagTable{k,1}); offset = s.TagTable{k,2}; data_size = s.TagTable{k,3}; pub_idx = strmatch(signature,public_tagnames,'exact'); mattrc_idx = strmatch(signature,mattrc_tagnames,'exact'); % Check to see if the tag is public, a mattrc tag, or private if ~isempty(pub_idx) % A public tag is found tagname = public_tagnames{pub_idx, 2}; s.(tagname) = get_public_tag(fid, signature, offset + start, ... data_size, version, s.Header.ConnectionSpace, tagname); elseif ~isempty(mattrc_idx) % A Mattrc element is found... and the MatTRC struct will % now be generated or appended. has_mattrc = true; tagname = mattrc_tagnames{mattrc_idx, 2}; MatTRC.(tagname) = get_public_tag(fid, signature, offset + start, ... data_size, version, s.Header.ConnectionSpace, tagname); else % The tag is a private tag data = get_private_tag(fid,offset+start,data_size); current_row = size(private_tags,1)+1; private_tags{current_row,1} = signature; private_tags{current_row,2} = data; end end % Generate the MatTRC field if has_mattrc s.MatTRC = MatTRC; end % Populate the private tags s.PrivateTags = private_tags; % Verify the checksum if present and nonzero. if isfield(s.Header, 'ProfileID') && any(s.Header.ProfileID) fseek_check(fid, start, 'bof'); bytes = fread_check(fid, s.Header.Size, '*uint8'); % See clause 6.1.13. The checksum is computed after setting bytes % 44-47 (indexed from 0), 64-67, and 84-99 to 0. bytes([45:48 65:68 85:100]) = 0; digest = compute_md5(bytes); if ~isequal(digest, s.Header.ProfileID) warning(message('images:iccread:badChecksum')); end end %------------------------------------------ function header = read_header(fid) % Clause 6.1.1 - Profile size header.Size = fread_check(fid, 1, 'uint32'); % Clause 6.1.2 - CMM Type header.CMMType = char(fread_check(fid, 4, 'uint8'))'; % Clause 6.1.3 - Profile Version % Byte 0: Major Revision in BCD % Byte 1: Minor Revision & Bug Fix Revision in each nibble in BCD % Byte 2: Reserved; expected to be 0 % Byte 3: Reserved; expected to be 0 version_bytes = fread_check(fid, 4, 'uint8'); major_version = version_bytes(1); % Minor version and bug fix version are in the two nibbles % of the second version byte. minor_version = bitshift(version_bytes(2), -4); bugfix_version = bitand(version_bytes(2), 15); header.Version = sprintf('%d.%d.%d', major_version, minor_version, ... bugfix_version); % Clause 6.1.4 - Profile/Device Class signature % Profile/Device Class Signature % ------------ --------- % Input Device profile 'scnr' % Display Device profile 'mntr' % Output Device profile 'prtr' % DeviceLink profile 'link' % ColorSpace Conversion profile 'spac' % Abstract profile 'abst' % Named Color profile 'nmcl' device_classes = get_device_classes(major_version); device_class_char = char(fread_check(fid, 4, '*uint8'))'; idx = strmatch(device_class_char, device_classes(:, 1), 'exact'); if isempty(idx) fclose(fid); error(message('images:iccread:invalidProfileClass')) end header.DeviceClass = device_classes{idx, 2}; % Clause 6.1.5 - Color Space signature % Four-byte string, although some signatures have a blank % space at the end. Translate into more readable string. colorspaces = get_colorspaces(major_version); signature = char(fread_check(fid, 4, '*uint8'))'; idx = strmatch(signature, colorspaces(:, 1), 'exact'); if isempty(idx) fclose(fid); error(message('images:iccread:invalidColorSpaceSignature')); else header.ColorSpace = colorspaces{idx, 2}; end % Clause 6.1.6 - Profile connection space signature % Either 'XYZ ' or 'Lab '. However, for a DeviceLink % profile, the connection space signature is taken from the % colorspace signatures table. signature = char(fread_check(fid, 4, '*uint8'))'; if strcmp(header.DeviceClass, 'device link') idx = strmatch(signature, colorspaces(:, 1), 'exact'); if isempty(idx) fclose(fid); error(message('images:iccread:invalidConnectionSpaceSignature')); else header.ConnectionSpace = colorspaces{idx, 2}; end else switch signature case 'XYZ ' header.ConnectionSpace = 'XYZ'; case 'Lab '; header.ConnectionSpace = 'Lab'; otherwise fclose(fid); error(message('images:iccread:invalidConnectionSpaceSignature')); end end date_time_num = read_date_time_number(fid); n = datenum(date_time_num(1), date_time_num(2), date_time_num(3), ... date_time_num(4), date_time_num(5), date_time_num(6)); header.CreationDate = datestr(n,0); header.Signature = char(fread_check(fid, 4, '*uint8'))'; if ~strcmp(header.Signature, 'acsp') fclose(fid); error(message('images:iccread:invalidFileSignature')); end % Clause 6.1.7 - Primary platform signature % Four characters, though one code ('SGI ') ends with a blank space. % Zeros if there is no primary platform. signature = char(fread_check(fid, 4, '*uint8'))'; if isequal(double(signature), [0 0 0 0]) header.PrimaryPlatform = 'none'; else switch signature case 'APPL' header.PrimaryPlatform = 'Apple'; case 'MSFT' header.PrimaryPlatform = 'Microsoft'; case 'SGI ' header.PrimaryPlatform = 'SGI'; case 'SUNW' header.PrimaryPlatform = 'Sun'; case 'TGNT' header.PrimaryPlatform = 'Taligent'; otherwise header.PrimaryPlatform = signature; warning(message('images:iccwrite:invalidPrimaryPlatform')) end end % Clause 6.1.8 - Profile flags % Flags containing CMM hints. The least-significant 16 bits are reserved % by ICC, which currently defines position 0 as "0 if not embedded profile, % 1 if embedded profile" and position 1 as "1 if profile cannot be used % independently of embedded color data, otherwise 0." header.Flags = fread_check(fid, 1, 'uint32'); header.IsEmbedded = bitget(header.Flags, 1) == 1; header.IsIndependent = bitget(header.Flags, 2) == 0; % Clause 6.1.9 - Device manufacturer and model header.DeviceManufacturer = char(fread_check(fid, 4, '*uint8'))'; header.DeviceModel = char(fread_check(fid, 4, '*uint8'))'; % Clause 6.1.10 - Attributes % Device setup attributes, such as media type. The least-significant 32 % bits of this 64-bit value are reserved for ICC, which currently defines % bit positions 0 and 1. % UPDATE FOR ICC:1:2001-0 Clause 6.1.10 -- Bit positions 2 and 3 % POSITION 2: POSITIVE=0, NEGATIVE=1 % POSITION 3: COLOR=0, BLACK AND WHT=1 fseek_check(fid, 4, 'cof'); header.Attributes = fread_check(fid, 1, 'uint32')'; header.IsTransparency = bitget(header.Attributes, 1) == 1; header.IsMatte = bitget(header.Attributes, 2) == 1; header.IsNegative = bitget(header.Attributes, 3) == 1; header.IsBlackandWhite = bitget(header.Attributes, 4) == 1; % Clause 6.1.11 - Rendering intent value = fread_check(fid, 1, 'uint32'); % Only check the first two bits. value = bitand(value, 3); switch value case 0 header.RenderingIntent = 'perceptual'; case 1 header.RenderingIntent = 'relative colorimetric'; case 2 header.RenderingIntent = 'saturation'; case 3 header.RenderingIntent = 'absolute colorimetric'; end % Clause 6.1 - Table 9 header.Illuminant = read_xyz_number(fid); % Clause 6.1.12 - Profile creator header.Creator = char(fread_check(fid, 4, '*uint8'))'; % Clause 6.1.13 (v. 4) - Profile ID if major_version > 2 header.ProfileID = fread_check(fid, 16, '*uint8')'; end %------------------------------------------ % Read public Tags function out = get_public_tag(fid, signature, offset, data_size, ... version, pcs, tagname) lut_types = {'A2B0','A2B1','A2B2','B2A0','B2A1','B2A2',... 'gamt','pre0','pre1','pre2'}; xyz_types = {'bkpt','bXYZ','gXYZ','lumi','rXYZ','wtpt'}; curve_types = {'bTRC','gTRC','kTRC','rTRC'}; text_desc_types = {'desc','dmdd','dmnd','scrd','vued'}; non_interpreted_types = {'bfd ','devs',... 'psd0','psd1','psd2','psd3',... 'ps2s','ps2i','scrn'}; text_types = {'targ'}; if version <= 2 text_types = [text_types, {'cprt'}]; non_interpreted_types = [non_interpreted_types, {'ncol'}]; else text_desc_types = [text_desc_types, {'cprt'}]; % non_interpreted_types = [non_interpreted_types, {'clrt'}]; end switch signature case lut_types % See Clauses 6.4.* (v. 2) and 9.2.* (v. 4.2) out = read_lut_type(fid, offset, data_size, version, tagname); case xyz_types % Clauses 6.4.* (v. 2) and 9.2.* (v. 4.2) out = read_xyz_type(fid, offset, data_size, tagname); case curve_types % Clauses 6.4.* (v. 2) and 9.2.* (v. 4.2) out = read_curve_type(fid, offset, data_size, version, tagname); case text_desc_types % Clauses 6.4.* (v. 2) and 9.2.* (v. 4.2) if version <= 2 out = read_text_description_type(fid, offset, data_size, tagname); else out = read_unicode_type(fid, offset, data_size, tagname); end case text_types % Clauses 6.4.* (v. 2) and 9.2.10 (v. 4.2) out = read_text_type(fid, offset, data_size, tagname); case non_interpreted_types % Clauses 6.4.* (v. 2) fseek_check(fid, offset, 'bof'); out = fread_check(fid, data_size, '*uint8')'; case 'calt' % Clause 6.4.9 (v. 2) and 9.2.9 (v. 4.2) out = read_date_time_type(fid, offset, data_size, tagname); case 'chad' % Clause 6.4.11 (v. 2) and 9.2.11 (v. 4.2) out = read_sf32_type(fid, offset, data_size, tagname); case 'chrm' % Clause 9.2.12 (v. 4.2) out = read_chromaticity_type(fid, offset, data_size, tagname); case 'clro' % Clause 9.2.13 (v. 4.2) out = read_colorant_order_type(fid, offset, data_size, tagname); case {'clrt', 'clot'} % Clause 9.2.14 (v. 4.2) out = read_colorant_table_type(fid, offset, data_size, pcs, tagname); case 'crdi' % Clause 6.4.14 (v. 2) or 6.4.16 (v. 4.0) out = read_crd_info_type(fid, offset, data_size, tagname); case 'meas' % Clause 9.2.23 (v. 4.2) out = read_measurement_type(fid, offset, data_size, tagname); case 'ncl2' % Clause 9.2.26 (v. 4.2) out = read_named_color_type(fid, offset, data_size, pcs, tagname); case 'pseq' % Clause 9.2.32 (v. 4.2) out = read_profile_sequence_type(fid, offset, data_size, ... version, tagname); case 'resp' % Clause 9.2.27 (v. 4.2) out = read_response_curve_set16_type(fid, offset, data_size, tagname); case 'tech' % Clause 9.2.35 (v. 4.2) out = read_signature_type(fid, offset, data_size, tagname); case 'view' % Clause 6.4.47 (v. 2) or 9.2.37 (v. 4.2) out = read_viewing_conditions(fid, offset, data_size, tagname); otherwise fseek_check(fid, offset, 'bof'); out = fread_check(fid, data_size, '*uint8')'; end % If there was a problem, treat as uninterpreted if isempty(out) fseek_check(fid, offset, 'bof'); out = fread_check(fid, data_size, '*uint8')'; end %------------------------------------------ % Read private tags function out = get_private_tag(fid,offset,data_size) fseek_check(fid, offset, 'bof'); out = fread_check(fid, data_size, '*uint8')'; %------------------------------------------ %%% read_sf32_type function out = read_sf32_type(fid, offset, data_size, tagname) % Clause 6.5.14 (v. 2) or 10.18 (v. 4.2) % 0-3 'sf32' % 4-7 reserved, must be 0 % 8-n array of s15Fixed16Number values if data_size < 8 warning(message('images:iccread:invalidDataSize', tagname)); out = []; return; end fseek_check(fid, offset, 'bof'); tagtype = char(fread_check(fid, 4, '*uint8'))'; if ~strcmp(tagtype, 'sf32') warning(message('images:iccread:invalidTagTypeWithReference', tagname, '''sf32''', 'Clause 6.5.14 (v. 2) or 6.5.19 (v. 4)')) out = []; return; end fseek_check(fid, offset + 8, 'bof'); num_values = (data_size - 8) / 4; out = fread_check(fid, num_values, 'int32') / 65536; out = reshape(out, 3, num_values/3)'; %------------------------------------------ % read_xyz_number function out = read_xyz_number(fid) % Clause 5.3.10 (v. 2) and 5.1.11 (v. 4.2) % 0-3 CIE X s15Fixed16Number % 4-7 CIE Y s15Fixed16Number % 8-11 CIE Z s15Fixed16Number out = fread_check(fid, 3, 'int32')' / 65536; %------------------------------------------ %%% read_xyz_type function out = read_xyz_type(fid, offset, data_size, tagname) % Clause 6.5.26 (v. 2) or 10.27 (v. 4.2) % 0-3 'XYZ ' % 4-7 reserved, must be 0 % 8-n array of XYZ numbers if data_size < 8 fclose(fid); error(message('images:iccread:invalidTagSize1', tagname)); end fseek_check(fid, offset, 'bof'); xyztype = char(fread_check(fid, 4, '*uint8'))'; if ~strcmp(xyztype, 'XYZ ') fclose(fid); error(message('images:iccread:invalidTagType', tagname, '''XYZ ''')) end fseek_check(fid, offset + 8, 'bof'); num_values = (data_size - 8) / 4; if rem(num_values,3) ~= 0 fclose(fid); error(message('images:iccread:invalidTagSize2', tagname, 'Clauses 5.3.10 and 6.5.26 for v. 2 or 6.5.30 for v. 4')) end out = fread_check(fid, num_values, 'int32') / 65536; out = reshape(out, 3, num_values/3)'; %------------------------------------------ %%% read_chromaticity_type function out = read_chromaticity_type(fid, offset, data_size, tagname) % Clause 10.2 (v. 4.2) % 0-3 'chrm' % 4-7 reserved, must be 0 % 8-9 number of device channels % 10-11 encoded phosphor/colorant type % 12-19 CIE xy coordinates of 1st channel % 20-end CIE xy coordinates of remaining channels if data_size < 12 fclose(fid); error(message('images:iccread:invalidTagSize1', tagname)); end fseek_check(fid, offset, 'bof'); signature = char(fread_check(fid, 4, '*uint8'))'; if ~strcmp(signature, 'chrm') fclose(fid); error(message('images:iccread:invalidTagType', tagname, '''chrm''')) end out = struct('ColorantCode', [], 'ColorantType', [], 'xy', []); fseek_check(fid, offset + 8, 'bof'); numchan = fread_check(fid, 1, 'uint16'); out.xy = zeros(numchan, 2); colorantcode = fread_check(fid, 1, '*uint16'); out.ColorantCode = colorantcode; switch colorantcode case 1 out.ColorantType = 'ITU-R BT.709'; case 2 out.ColorantType = 'SMPTE RP145-1994'; case 3 out.ColorantType = 'EBU Tech.3213-E'; case 4 out.ColorantType = 'P22'; otherwise out.ColorantType = 'unknown'; end for i = 1 : numchan out.xy(i, 1) = fread_check(fid, 1, 'uint32') / 65536.0; out.xy(i, 2) = fread_check(fid, 1, 'uint32') / 65536.0; end %------------------------------------------ %%% read_colorant_order_type function out = read_colorant_order_type(fid, offset, data_size, tagname) % Clause 10.3 (v. 4.2) % 0-3 'clro' % 4-7 reserved, must be 0 % 8-11 number of colorants n % 12 index of first colorant in laydown % 13-end remaining (n - 1) indices, in laydown order if data_size < 12 fclose(fid); error(message('images:iccread:invalidTagSize1', tagname)); end fseek_check(fid, offset, 'bof'); signature = char(fread_check(fid, 4, '*uint8'))'; if ~strcmp(signature, 'clro') fclose(fid); error(message('images:iccread:invalidTagType', tagname, '''clro''')) end fseek(fid, offset + 8, 'bof'); numchan = fread_check(fid, 1, 'uint32'); out = zeros(1, numchan); for i = 1 : numchan out(i) = fread_check(fid, 1, 'uint8'); end %------------------------------------------ %%% read_colorant_table_type function out = read_colorant_table_type(fid, offset, data_size, pcs, tagname) % Clause 10.4 (v. 4.2) % 0-3 'clrt' % 4-7 reserved, must be 0 % 8-11 number of colorants n % 12-43 name of first colorant, NULL terminated % 44-49 PCS values of first colorant as uint16 % 50-end name and PCS values of remaining colorants if data_size < 12 fclose(fid); error(message('images:iccread:invalidTagSize1', tagname)); end fseek_check(fid, offset, 'bof'); signature = char(fread_check(fid, 4, '*uint8'))'; if ~strcmp(signature, 'clrt') fclose(fid); error(message('images:iccread:invalidTagType', tagname, '''clrt''')) end fseek_check(fid, offset + 8, 'bof'); numchan = fread_check(fid, 1, 'uint32'); out = cell(numchan, 2); for i = 1 : numchan name = fread_check(fid, 32, '*uint8')'; out{i, 1} = trim_string(name); % remove trailing zeros pcs16 = fread_check(fid, 3, '*uint16')'; % Convert from uint16 to double out{i, 2} = encode_color(pcs16, pcs, 'uint16', 'double'); end %------------------------------------------ %%% read_curve_type function out = read_curve_type(fid, offset, ~, version, tagname) % Clause 6.5.3 (v. 2) or 10.5 (v. 4.2) % 0-3 'curv' % 4-7 reserved, must be 0 % 8-11 count value, uint32 % 12-end curve values, uint16 % For v. 4 can also be 'para'; see Clause 10.15 (v. 4.2) % Note: Since this function can be called for a curveType % embedded in another tag (lutAtoBType, lutBtoAType), the % data_size field may be invalid -- e.g., zero. Therefore, % there is no check for sufficient size (= 12 + 2n bytes). fseek_check(fid, offset, 'bof'); % Check for curv or para signature curvetype = char(fread_check(fid, 4, '*uint8'))'; if strcmp(curvetype, 'curv') out = uint16(256); % Default: gamma = 1 for empty curve fseek_check(fid, offset + 8, 'bof'); count = fread_check(fid, 1, 'uint32'); if count > 0 out = fread_check(fid, count, '*uint16'); end elseif strcmp(curvetype, 'para') && (version > 2) % New v. 4 type out = struct('FunctionType', [], 'Params', []); fseek_check(fid, offset + 8, 'bof'); out.FunctionType = fread_check(fid, 1, 'uint16'); switch out.FunctionType case 0 n = 1; case 1 n = 3; case 2 n = 4; case 3 n = 5; case 4 n = 7; otherwise error(message('images:iccread:invalidFunctionType', out.FunctionType, tagname)) end fseek_check(fid, offset + 12, 'bof'); out.Params = fread_check(fid, n, 'int32')' / 65536; else fclose(fid); error(message('images:iccread:invalidTagTypeWithReference', tagname, '''curv''', 'Clauses 6.5.3 (v. 2) or 6.5.5 and 6.5.16 (v. 4).')) end %------------------------------------------ %%% Read viewingConditionsType function out = read_viewing_conditions(fid,offset,data_size, tagname) % Clause 6.5.25 (v. 2) or 10.26 (v. 4.2) % 0-3 'view' % 4-7 reserved, must be 0 % 8-19 absolute XYZ for illuminant in cd/m^2 % 20-31 absolute XYZ for surround in cd/m^2 % 32-35 illuminant type if data_size < 36 warning(message('images:iccread:invalidTagSize1', tagname)); out = []; return; end fseek_check(fid, offset, 'bof'); tagtype = char(fread_check(fid, 4, '*uint8'))'; if ~strcmp(tagtype, 'view') warning(message('images:iccread:invalidTagTypeWithReference', tagname, '''view''', 'Clause 6.5.25 (v. 2) or 6.5.29 (v. 4)')) out = []; return; end fseek_check(fid, offset + 8, 'bof'); out.IlluminantXYZ = read_xyz_number(fid); out.SurroundXYZ = read_xyz_number(fid); illum_idx = fread_check(fid,1,'uint32'); illuminant_table = {'Unknown','D50','D65','D93','F2',... 'D55','A','EquiPower','F8'}; out.IlluminantType = illuminant_table{illum_idx+1}; %------------------------------------------ %%% read_lut_type function out = read_lut_type(fid, offset, data_size, version, tagname) % Clauses 6.5.8 and 6.5.7 (v. 2) or 10.9 and 10.8 (v. 4.2) % 0-3 'mft1', 'mft2' % 4-7 reserved, must be 0 % 8 number of input channels, uint8 % 9 number of output channels, uint8 % 10 number of CLUT grid points, uint8 % 11 reserved for padding, must be 0 % 12-47 3-by-3 E matrix, stored row-major, each value s15Fixed16Number % 16-bit LUT type ('mft2'): % 48-49 number of input table entries, uint16 % 50-51 number of output table entries, uint16 % 52-n input tables, uint16 % CLUT values, uint16 % output tables, uint16 % 8-bit LUT type ('mft1'): % 48- input tables, uint8 % CLUT values, uint8 % output tables, uint8 % New v. 4 LUT types, Clauses 10.10 and 10.11 (v. 4.2) % 0-3 'mAB ', 'mBA ' % 4-7 reserved, must be 0 % 8 number of input channels, uint8 % 9 number of output channels, uint8 % 10-11 reserved for padding, must be 0 % 12-15 offset to first B-curve, uint32 % 16-19 offset to 3-by-4 matrix, uint32 % 20-23 offset to first M-curve, uint32 % 24-27 offset to CLUT values, uint32 % 28-31 offset to first A-curve, uint32 % 32-n data: curves stored as 'curv' or 'para' tags, % matrix stored as s15Fixed16Number[12], % CLUT stored as follows: % 0-15 number of grid points in each dimension, uint8 % 16 precision in bytes (1 or 2), uint8 % 17-19 reserved for padding, must be 0 % 20-n CLUT data points, uint8 or uint16 if data_size < 32 fclose(fid); error(message('images:iccread:invalidTagSize1', tagname)); end fseek_check(fid, offset, 'bof'); % Check for signature luttype = char(fread_check(fid, 4, '*uint8'))'; if strcmp(luttype, 'mft1') out.MFT = 1; elseif strcmp(luttype, 'mft2') out.MFT = 2; elseif strcmp(luttype, 'mAB ') && (version > 2) % New v. 4 lut type out.MFT = 3; elseif strcmp(luttype, 'mBA ') && (version > 2) % New v. 4 lut type out.MFT = 4; else fclose(fid); error(message('images:iccread:invalidTagTypeWithReference', tagname, '''mft1'', ''mft2'', ''mAB '' (v. 4), or ''mBA '' (v. 4)', 'Clauses 6.5.7 and 6.5.8 for v. 2 or 6.5.9, 6.5.10, 6.5.11, 6.5.12 for v. 4')) end % Skip past reserved padding bytes fseek_check(fid, 4, 'cof'); num_input_channels = fread_check(fid, 1, 'uint8'); num_output_channels = fread_check(fid, 1, 'uint8'); % Handle older lut8Type and lut16Type if out.MFT < 3 % Unused elements out.PreShaper = []; out.PostMatrix = []; out.PostShaper = []; % Get matrix num_clut_grid_points = fread_check(fid, 1, 'uint8'); fseek_check(fid, 1, 'cof'); % skip padding byte out.PreMatrix = reshape(fread_check(fid, 9, 'int32') / 65536, 3, 3)'; out.PreMatrix(:, 4) = zeros(3, 1); % Get tables if out.MFT == 2 % lut16Type num_input_table_entries = fread_check(fid, 1, 'uint16'); num_output_table_entries = fread_check(fid, 1, 'uint16'); dataformat = '*uint16'; else % lut8Type num_input_table_entries = 256; num_output_table_entries = 256; dataformat = '*uint8'; end itbl = reshape(fread_check(fid, num_input_channels * ... num_input_table_entries, ... dataformat), ... num_input_table_entries, ... num_input_channels); for k = 1 : num_input_channels out.InputTables{k} = itbl(:, k); end clut_size = ones(1, num_input_channels) * num_clut_grid_points; num_clut_elements = prod(clut_size); ndims_clut = num_output_channels; out.CLUT = reshape(fread_check(fid, num_clut_elements * ndims_clut, dataformat), ... ndims_clut, num_clut_elements)'; out.CLUT = reshape( out.CLUT, [ clut_size ndims_clut ]); otbl = reshape(fread_check(fid, num_output_channels * ... num_output_table_entries, ... dataformat), ... num_output_table_entries, ... num_output_channels); for k = 1 : num_output_channels out.OutputTables{k} = otbl(:, k); end else % Handle newer lutAtoBType and lutBtoAType fseek_check(fid, 2, 'cof'); % skip padding bytes boffset = fread_check(fid, 1, 'uint32'); xoffset = fread_check(fid, 1, 'uint32'); moffset = fread_check(fid, 1, 'uint32'); coffset = fread_check(fid, 1, 'uint32'); aoffset = fread_check(fid, 1, 'uint32'); % Get B-curves (required) if boffset == 0 fclose(fid); error(message('images:iccread:invalidLuttagBcurve', tagname)) end if out.MFT == 3 numchan = num_output_channels; else numchan = num_input_channels; end Bcurve = cell(1, numchan); Bcurve{1} = read_curve_type(fid, offset + boffset, 0, version, tagname); for chan = 2 : numchan current = ftell(fid); if mod(current, 4) ~= 0 current = current + 4 - mod(current, 4); end Bcurve{chan} = read_curve_type(fid, current, 0, version, tagname); end % Get PCS-side matrix (optional) if xoffset == 0 PMatrix = []; else fseek_check(fid, offset + xoffset, 'bof'); PMatrix = reshape(fread_check(fid, 9, 'int32') / 65536, 3, 3)'; PMatrix(:, 4) = fread_check(fid, 3, 'int32') / 65536; end % Get M-curves (optional) if moffset == 0 Mcurve = []; elseif xoffset == 0 fclose(fid); error(message('images:iccread:invalidLuttagMatrix', tagname)) else Mcurve = cell(1, numchan); Mcurve{1} = read_curve_type(fid, offset + moffset, 0, version, tagname); for chan = 2 : numchan current = ftell(fid); if mod(current, 4) ~= 0 current = current + 4 - mod(current, 4); end Mcurve{chan} = read_curve_type(fid, current, 0, version, tagname); end end % Get n-dimensional LUT (optional) if coffset == 0 ndlut = []; else fseek(fid, offset + coffset, 'bof'); gridsize = fread(fid, num_input_channels, 'uint8')'; % Reverse order of dimensions for MATLAB clut_size = zeros(1, num_input_channels); for i = 1 : num_input_channels clut_size(i) = gridsize(num_input_channels + 1 - i); end num_clut_elements = prod(clut_size); ndims_clut = num_output_channels; fseek(fid, 16 - num_input_channels, 'cof'); % skip unused channels datasize = fread(fid, 1, 'uint8'); if datasize == 1 dataformat = '*uint8'; elseif datasize == 2 dataformat = '*uint16'; else fclose(fid); error(message('images:iccread:invalidLuttagPrecision', tagname)) end fseek(fid, 3, 'cof'); % skip over padding ndlut = reshape(fread_check(fid, num_clut_elements * ndims_clut, dataformat), ... ndims_clut, num_clut_elements)'; ndlut = reshape(ndlut, [ clut_size ndims_clut ]); end % Get A-curves (optional) if aoffset == 0 Acurve = []; elseif coffset == 0 fclose(fid); error(message('images:iccread:invalidLuttagAcurve', tagname)) else Acurve = cell(1, numchan); Acurve{1} = read_curve_type(fid, offset + aoffset, 0, version, tagname); if out.MFT == 3 numchan = num_input_channels; else numchan = num_output_channels; end for chan = 2 : numchan current = ftell(fid); if mod(current, 4) ~= 0 current = current + 4 - mod(current, 4); end Acurve{chan} = read_curve_type(fid, current, 0, version, tagname); end end % Assemble elements in proper sequence if out.MFT == 3 % lutAtoBType out.PreShaper = []; out.PreMatrix = []; out.InputTables = Acurve; out.CLUT = ndlut; out.OutputTables = Mcurve; out.PostMatrix = PMatrix; out.PostShaper = Bcurve; elseif out.MFT == 4 % lutBtoAType out.PreShaper = Bcurve; out.PreMatrix = PMatrix; out.InputTables = Mcurve; out.CLUT = ndlut; out.OutputTables = Acurve; out.PostMatrix = []; out.PostShaper = []; end end %------------------------------------------ %%% read_measurement_type function out = read_measurement_type(fid, offset, data_size, tagname) % Clause 10.12 (v. 4.2) % 0-3 'meas' % 4-7 reserved, must be 0 % 8-11 encoded standard observer % 12-23 XYZ of measurement backing % 24-27 encoded measurement geometry % 28-31 encoded measurement flare % 32-35 encoded standard illuminant if data_size < 36 warning(message('images:iccread:invalidTagSize1', tagname)); out = []; return; end fseek_check(fid, offset, 'bof'); tagtype = char(fread_check(fid, 4, '*uint8'))'; if ~strcmp(tagtype, 'meas') warning(message('images:iccread:invalidTagTypeWithReference', tagname, '''meas''', 'Clause 10.12 (v. 4.2)')) out = []; return; end out = struct('ObserverCode', [], 'StandardObserver', [], ... 'GeometryCode', [], 'MeasurementGeometry', [], ... 'FlareCode', [], 'MeasurementFlare', [], ... 'IlluminantCode', [], 'StandardIlluminant', [], ... 'MeasurementBacking', []); fseek_check(fid, offset + 8, 'bof'); out.ObserverCode = fread_check(fid, 1, 'uint32'); switch out.ObserverCode case 1 out.StandardObserver = 'CIE 1931'; case 2 out.StandardObserver = 'CIE 1964'; otherwise out.StandardObserver = 'unknown'; end out.MeasurementBacking = read_xyz_number(fid); out.GeometryCode = fread_check(fid, 1, 'uint32'); switch out.GeometryCode case 1 out.MeasurementGeometry = '0/45 or 45/0'; case 2 out.MeasurementGeometry = '0/d or d/0'; otherwise out.MeasurementGeometry = 'unknown'; end out.FlareCode = fread_check(fid, 1, 'uint32'); out.MeasurementFlare = sprintf('%d%%', ... round(double(out.FlareCode) / 655.36)); out.IlluminantCode = fread_check(fid, 1, 'uint32'); switch out.IlluminantCode case 1 out.StandardIlluminant = 'D50'; case 2 out.StandardIlluminant = 'D65'; case 3 out.StandardIlluminant = 'D93'; case 4 out.StandardIlluminant = 'F2'; case 5 out.StandardIlluminant = 'D55'; case 6 out.StandardIlluminant = 'A'; case 7 out.StandardIlluminant = 'E'; case 8 out.StandardIlluminant = 'F8'; otherwise out.StandardIlluminant = 'unknown'; end %------------------------------------------ %%% read_named_color_type function out = read_named_color_type(fid, offset, ~, pcs, tagname) % Clause 10.14 (v. 4.2) % 0-3 'ncl2' (namedColor2Type signature) % 4-7 reserved, must be 0 % 8-11 vendor-specific flag % 12-15 count of named colours (n) % 16-19 number m of device coordinates % 20-51 prefix (including NULL terminator) % 52-83 suffix (including NULL terminator) % 84-115 first colour name (including NULL terminator) % 116-121 first colour's PCS coordinates % 122-(121 + 2m) first colour's device coordinates % . . . and so on for remaining (n - 1) colours fseek_check(fid, offset, 'bof'); tagtype = char(fread_check(fid, 4, '*uint8'))'; if ~strcmp(tagtype, 'ncl2') warning(message('images:iccread:invalidTagTypeWithReference', tagname, '''ncl2''', 'Clause 10.14 (v. 4.2)')) out = []; return; end out = struct('VendorFlag', [], ... 'DeviceCoordinates', [], ... 'Prefix', [], ... 'Suffix', [], ... 'NameTable', []); fseek_check(fid, offset + 8, 'bof'); out.VendorFlag = dec2hex(fread_check(fid, 1, '*uint32')); n = fread_check(fid, 1, 'uint32'); m = fread_check(fid, 1, 'uint32'); out.DeviceCoordinates = m; prefix = fread_check(fid, 32, '*uint8')'; out.Prefix = trim_string(prefix); suffix = fread_check(fid, 32, '*uint8')'; out.Suffix = trim_string(suffix); if m > 0 out.NameTable = cell(n, 3); else out.NameTable = cell(n, 2); % no device coordinates end for i = 1 : n name = fread_check(fid, 32, '*uint8')'; out.NameTable{i, 1} = trim_string(name); pcs16 = fread_check(fid, 3, '*uint16')'; out.NameTable{i, 2} = encode_color(pcs16, pcs, 'uint16', 'double'); if m > 0 dev16 = fread_check(fid, m, '*uint16')'; out.NameTable{i, 3} = encode_color(dev16, ... 'color_n', 'uint16', 'double'); end end %------------------------------------------ %%% read_profile_sequence_type function out = read_profile_sequence_type(fid, offset, data_size, ... version, tagname) % Clause 10.16 (v. 4.2) % 0-3 'pseq' % 4-7 reserved, must be 0 % 8-11 count of profile description structures % 12- profile description structures if data_size < 12 warning(message('images:iccread:invalidTagSize1', tagname)); out = []; return; end fseek_check(fid, offset, 'bof'); tagtype = char(fread_check(fid, 4, '*uint8'))'; if ~strcmp(tagtype, 'pseq') warning(message('images:iccread:invalidTagTypeWithReference', tagname, '''pseq''', 'Clause 10.16 (v. 4.2)')) out = []; return; end fseek_check(fid, offset + 8, 'bof'); n = fread_check(fid, 1, 'uint32'); out = struct('DeviceManufacturer', {}, ... 'DeviceModel', {}, ... 'Attributes', {}, ... 'IsTransparency', {}, ... 'IsMatte', {}, ... 'IsNegative', {}, ... 'IsBlackandWhite', {}, ... 'Technology', {}, ... 'DeviceMfgDesc', {}, ... 'DeviceModelDesc', {}); technologies = get_technologies; for p = 1:n out(p).DeviceManufacturer = char(fread_check(fid, 4, '*uint8'))'; out(p).DeviceModel = char(fread_check(fid, 4, '*uint8'))'; fseek_check(fid, 4, 'cof'); out(p).Attributes = fread_check(fid, 1, 'uint32')'; out(p).IsTransparency = bitget(out(p).Attributes, 1) == 1; out(p).IsMatte = bitget(out(p).Attributes, 2) == 1; out(p).IsNegative = bitget(out(p).Attributes, 3) == 1; out(p).IsBlackandWhite = bitget(out(p).Attributes, 4) == 1; techsig = char(fread_check(fid, 4, '*uint8'))'; if strcmp(techsig, char(uint8([0 0 0 0]))) out(p).Technology = 'Unspecified'; else idx = strmatch(techsig, technologies(:, 1), 'exact'); if isempty(idx) warning(message('images:iccread:invalidTechnologySignature', tagname)) out(p).Technology = techsig; else out(p).Technology = technologies{idx, 2}; end end current = ftell(fid); if version <= 2 out(p).DeviceMfgDesc ... = read_text_description_type(fid, current, 0, 'DeviceMfgDesc'); if isempty(out(p).DeviceMfgDesc) % try v. 4 type out(p).DeviceMfgDesc ... = read_unicode_type(fid, current, 0, 'DeviceMfgDesc'); end else out(p).DeviceMfgDesc ... = read_unicode_type(fid, current, 0, 'DeviceMfgDesc'); if isempty(out(p).DeviceMfgDesc) % try v. 2 type out(p).DeviceMfgDesc ... = read_text_description_type(fid, current, 0, 'DeviceMfgDesc'); end end if isempty(out(p).DeviceMfgDesc) out = []; return; elseif isempty(out(p).DeviceMfgDesc.String) out(p).DeviceMfgDesc.String = 'Unavailable'; end current = ftell(fid); if version <= 2 out(p).DeviceModelDesc ... = read_text_description_type(fid, current, 0, 'DeviceModelDesc'); if isempty(out(p).DeviceModelDesc) % try v. 4 type out(p).DeviceModelDesc = ... read_unicode_type(fid, current, 0, 'DeviceModelDesc'); end else out(p).DeviceModelDesc ... = read_unicode_type(fid, current, 0, 'DeviceModelDesc'); if isempty(out(p).DeviceModelDesc) % try v. 2 type out(p).DeviceModelDesc = ... read_text_description_type(fid, current, 0, 'DeviceModelDesc'); end end if isempty(out(p).DeviceModelDesc) out = []; return; elseif isempty(out(p).DeviceModelDesc.String) out(p).DeviceModelDesc.String = 'Unavailable'; end end %------------------------------------------ %%% read_response_curve_set16_type function out = read_response_curve_set16_type(fid, offset, data_size, ... tagname) % Clause 10.17 (v. 4.2) % 0-3 'rcs2' % 4-7 reserved, must be 0 % 8-9 number of channels n % 10-11 number of measurement types m % 12-(11+4m) array of offsets % (12+4m)-end m response-curve structures if data_size < 12 warning(message('images:iccread:invalidTagSize1', tagname)); out = []; return; end fseek_check(fid, offset, 'bof'); tagtype = char(fread_check(fid, 4, '*uint8'))'; if ~strcmp(tagtype, 'rcs2') warning(message('images:iccread:invalidTagTypeWithReference', tagname, '''rcs2''', 'Clause 10.17 (v. 4.2)')) out = []; return; end fseek_check(fid, offset + 8, 'bof'); numchan = fread_check(fid, 1, 'uint16'); numtypes = fread_check(fid, 1, 'uint16'); soffset = zeros(1, numtypes); for i = 1 : numtypes soffset(i) = fread_check(fid, 1, 'uint32'); end % response-curve structure % 0-3 measurement-type signature % 4-(3+4n) number of measurements for each channel % (4+4n)-(3+16n) XYZ of solid-colorant patches % (4+12n)-end n response arrays emptyInitializer = cell(1,numtypes); out = struct('MeasurementCode', emptyInitializer, ... 'MeasurementType', emptyInitializer, ... 'SolidXYZs', emptyInitializer, ... 'ResponseArray', emptyInitializer); for i = 1 : numtypes fseek(fid, offset + soffset(i), 'bof'); out(i).MeasurementCode = char(fread_check(fid, 4, '*uint8'))'; switch out(i).MeasurementCode case 'StaA' out(i).MeasurementType = 'Status A'; case 'StaE' out(i).MeasurementType = 'Status E'; case 'StaI' out(i).MeasurementType = 'Status I'; case 'StaT' out(i).MeasurementType = 'Status T'; case 'StaM' out(i).MeasurementType = 'Status M'; case 'DN ' out(i).MeasurementType = 'DIN E, no polarizing filter'; case 'DN P' out(i).MeasurementType = 'DIN E, with polarizing filter'; case 'DNN ' out(i).MeasurementType = 'DIN I, no polarizing filter'; case 'DNNP' out(i).MeasurementType = 'DIN I, with polarizing filter'; otherwise out(i).MeasurementType = 'unknown'; end nmeas = zeros(1, numchan); for j = 1 : numchan nmeas(j) = fread_check(fid, 1, 'uint32'); end for j = 1 : numchan out(i).SolidXYZs(j, :) = read_xyz_number(fid); end for j = 1 : numchan out(i).ResponseArray{j} = zeros(nmeas(j), 2); for k = 1 : nmeas(j) out(i).ResponseArray{j}(k, 1) = ... fread_check(fid, 1, 'uint16') / 65535.0; fseek(fid, 2, 'cof'); out(i).ResponseArray{j}(k, 2) = ... fread_check(fid, 1, 'uint32') / 65536.0; end end end %------------------------------------------ %%% read_signature_type function out = read_signature_type(fid, offset, data_size, tagname) % Clause 10.19 (v. 4.2) % 0-3 'sig ' % 4-7 reserved, must be 0 % 8-11 four-byte signature if data_size < 12 warning(message('images:iccread:invalidTagSize1', tagname)); out = []; return; end fseek_check(fid, offset, 'bof'); typesig = char(fread_check(fid, 4, '*uint8'))'; if strcmp(typesig, 'sig ') fseek_check(fid, offset + 8, 'bof'); techsig = char(fread_check(fid, 4, '*uint8'))'; if strmatch(techsig, char(uint8([0 0 0 0]))) out = 'Unspecified'; else technologies = get_technologies; idx = strmatch(techsig, technologies(:, 1), 'exact'); if isempty(idx) warning(message('images:iccread:invalidTechnologySignature', tagname)) out = []; else out = technologies{idx, 2}; end end else warning(message('images:iccread:invalidTagTypeWithReference', tagname, '''sig ''', 'Clause 10.19 (v. 4.2)')) out = []; end %------------------------------------------ %%% read_text_description_type function out = read_text_description_type(fid, offset, data_size, tagname) % Clause 6.5.17 (v. 2 only; replaced by Unicode in v. 4) % 0-3 'desc' % 4-7 reserved, must be 0 % 8-11 ASCII invariant description count, including terminating NULL % 12- ASCII invariant description % followed by optional Unicode and ScriptCode descriptions, which we % preserve. % Note: Since this function can be called for a textDescriptionType % embedded in another tag (profileSequenceDescType), the % data_size field may be invalid -- e.g., zero. Therefore, % there is no check for sufficient size (= 12 bytes). % Check for desc signature fseek_check(fid, offset, 'bof'); chartype = char(fread_check(fid, 4, '*uint8'))'; if strcmp(chartype, 'desc') % read ASCII string fseek_check(fid, offset + 8, 'bof'); count = fread_check(fid, 1, 'uint32'); % ASCII count % count includes the trailing NULL, which we don't need. % Note that profiles have been found in which the expected % trailing NULL is not present, in which case count is 0. out.String = char(fread_check(fid, count, '*uint8'))'; if ~isempty(out.String) % Remove the trailing NULL. out.String = out.String(1:end-1); end % read or construct optional data if data_size > count + 12 % assume data_size correct out.Optional = fread_check(fid, data_size - 12 - count, '*uint8')'; elseif data_size == count + 12 % no optional data out.Optional = uint8(zeros(1, 78)); % supply minimal data else % improper data_size; investigate % read Unicode string out.Optional(1:8) = fread_check(fid, 8, '*uint8')'; unicount = double(out.Optional(5:8)); % Unicode count ucount = bitshift(unicount(1), 24) + bitshift(unicount(2), 16) + ... bitshift(unicount(3), 8) + unicount(4); if ucount > 0 out.Optional(9:8+2*ucount) = fread_check(fid, 2 * ucount, '*uint8')'; end % read ScriptCode string out.Optional(9+2*ucount:78+2*ucount) = ... fread_check(fid, 70, '*uint8')'; end % optional Unicode or ScriptCode data, saved but not interpreted else warning(message('images:iccread:invalidTagTypeWithReference', tagname, '''desc''', 'Clause 6.5.17')) out = []; end %------------------------------------------ %%% read_unicode_type function out = read_unicode_type(fid, offset, ~, tagname) % Clause 10.13 (v. 4.2) % 0-3 'mluc' % 4-7 reserved, must be 0 % 8-11 number of name records that follow (n) % 12-15 name-record length (currently 12) % 16-17 first-name language code (ISO-639) % 18-19 first-name country code (ISO-3166) % 20-23 first-name length % 24-27 first-name offset % 28-(28+12n) [n should be (n - 1) - rfp] % additional name records, if any % (28+12n)-end [n should be (n - 1) - rfp] % Unicode characters (2 bytes each) % Note: Since this function can be called for a multiLocalized- % UnicodeType embedded in another tag (profileSequenceDescType), % the data_size field may be invalid -- e.g., zero. Therefore, % there is no check for sufficient size (= 16 bytes). % Check for mluc signature fseek_check(fid, offset, 'bof'); chartype = char(fread_check(fid, 4, '*uint8'))'; if strcmp(chartype, 'mluc') % New v. 4 type out = read_mluc(fid, offset); else warning(message('images:iccread:invalidTagTypeWithReference', tagname, '''mluc''', 'Clause 6.5.14')) out = []; end %------------------------------------------ %%% read_text_type function out = read_text_type(fid, offset, data_size, tagname) % Clause 6.5.18 (v. 2) or 10.20 (v. 4.2) % 0-3 'text' % 4-7 reserved, must be 0 % 8- string of (data_size - 8) 7-bit ASCII characters, including NULL if data_size < 8 warning(message('images:iccread:invalidTagSize1', tagname)); out = []; return; end fseek_check(fid, offset, 'bof'); tagtype = char(fread_check(fid, 4, '*uint8'))'; if ~strcmp(tagtype, 'text') warning(message('images:iccread:invalidTagTypeWithReference', tagname, '''text''', 'Clause 6.5.18 (v. 2) or 6.5.22 (v. 4)')) out = []; return; end fseek_check(fid, offset + 8, 'bof'); out = char(fread_check(fid, data_size-9, '*uint8'))'; %------------------------------------------ %%% read_date_time_type function out = read_date_time_type(fid, offset, data_size, tagname) % Clause 6.5.5 (v. 2) or 10.7 (v. 4.2) % 0-3 'dtim' % 4-7 reserved, must be 0 % 8-19 DateTimeNumber if data_size < 20 warning(message('images:iccread:invalidTagSize1', tagname)); out = []; return; end fseek_check(fid, offset, 'bof'); tagtype = char(fread_check(fid, 4, '*uint8'))'; if ~strcmp(tagtype, 'dtim') warning(message('images:iccread:invalidTagTypeWithReference', tagname, '''dtim''', 'Clause 6.5.5 (v. 2) or 6.5.7 (v. 4)')) out = []; return; end fseek_check(fid, offset + 8, 'bof'); out = read_date_time_number(fid); %------------------------------------------ %%% read_crd_info_type function out = read_crd_info_type(fid, offset, data_size, tagname) % Clause 6.5.2 (v. 2) or 6.5.4 (v. 4.0) % 0-3 'crdi' % 4-7 reserved, must be 0 % 8-11 PostScript product name character count, uint32 % PostScript product name, 7-bit ASCII % Rendering intent 0 CRD name character count, uint32 % Rendering intent 0 CRD name, 7-bit ASCII % Rendering intent 1 CRD name character count, uint32 % Rendering intent 1 CRD name, 7-bit ASCII % Rendering intent 2 CRD name character count, uint32 % Rendering intent 2 CRD name, 7-bit ASCII % Rendering intent 3 CRD name character count, uint32 % Rendering intent 3 CRD name, 7-bit ASCII if data_size < 12 warning(message('images:iccread:invalidTagSize1', tagname)); out = []; return; end fseek_check(fid, offset, 'bof'); tagtype = char(fread_check(fid, 4, '*uint8'))'; if ~strcmp(tagtype, 'crdi') warning(message('images:iccread:invalidTagTypeWithReference', tagname, '''crdi''', 'Clause 6.5.2 (v. 2) or 6.5.4 (v. 4)')) out = []; return; end fseek_check(fid, offset + 8, 'bof'); count = fread_check(fid, 1, 'uint32'); name = char(fread_check(fid, count, '*uint8'))'; out.PostScriptProductName = name(1:end-1); out.RenderingIntentCRDNames = cell(4,1); for k = 1:4 count = fread_check(fid, 1, 'uint32'); name = char(fread_check(fid, count, '*uint8'))'; out.RenderingIntentCRDNames{k} = name(1:end-1); end %------------------------------------------ %%% read_date_time_number function out = read_date_time_number(fid) % Clause 5.3.1 (v. 2) and 5.1.1 (v. 4.2) out = fread_check(fid, 6, 'uint16'); %--------------------------------------------- %%% read_mluc function mluc = read_mluc(fid, offset) %READ_MLUC Read multiLocalizedUnicodeType tag from ICC profile. % MLUC = READ_MLUC(FID, OFFSET) reads a multiLocalizedUnicodeType tag % located at OFFSET (in bytes from the beginning of the file) using the % file identifier FID. MLUC is a structure array containing the fields: % % String Unicode characters stored as a MATLAB char array. % LanguageCode ISO-639 language code. % CountryCode ISO-3166 country code. % % The number of elements in the structure array is the number of names % stored in the tag. % % See section 6.5.12 of the ICC specification "File Format for Color % Profiles," version 4.1.0. % Skip past first four bytes ('mluc') and second four bytes (all 0). fseek_check(fid, offset + 8, 'bof'); num_names = fread_check(fid, 1, 'uint32'); fread_check(fid, 1, 'uint32'); % Initialize the output structure to fix the desired field order. emptyInitializer = cell(1, num_names); mluc = struct('String', emptyInitializer, ... 'LanguageCode', emptyInitializer, ... 'CountryCode', emptyInitializer); temp = struct('NameLength', emptyInitializer, ... 'NameOffset', emptyInitializer); for k = 1:num_names mluc(k).LanguageCode = fread_check(fid, 1, 'uint16'); mluc(k).CountryCode = fread_check(fid, 1, 'uint16'); % Name length and offset are using for reading in the Unicode % characters, but they aren't needed in the output structure mluc. temp(k).NameLength = fread_check(fid, 1, 'uint32'); temp(k).NameOffset = fread_check(fid, 1, 'uint32'); end for k = 1:num_names fseek_check(fid, offset + temp(k).NameOffset, 'bof'); str = fread_check(fid, temp(k).NameLength, '*uint8'); str = reshape(str, [1 numel(str)]); mluc(k).String = native2unicode(str, 'utf-16be'); end %------------------------------ %%% trim_string function string = trim_string(bytes) if ~strcmp(class(bytes), 'uint8') error(message('images:iccread:invalidInputData')) end endbyte = strfind(bytes, 0); string = char(bytes(1 : endbyte - 1)); %------------------------------ %%% fseek_check function fseek_check(fid, n, origin) if fseek(fid, n, origin) < 0 pos = ftell(fid); fclose(fid); error(message('images:iccread:fseekFailed', n, pos)) end %------------------------------ %%% fread_check function out = fread_check(fid, n, precision) [out,count] = fread(fid, n, precision); if count ~= n pos = ftell(fid) - count; fclose(fid); error(message('images:iccread:fileReadFailed', n, pos)) end
github
wangsuyuan/Imageprocesingtoobox-master
rgb2ycbcr.m
.m
Imageprocesingtoobox-master/colorspaces/@gpuArray/rgb2ycbcr.m
5,800
utf_8
ed436581c4079fe3ce18c0bea32f2ec2
function ycbcr = rgb2ycbcr(varargin) %RGB2YCBCR Convert RGB color values to YCbCr color space. % YCBCRMAP = RGB2YCBCR(MAP) converts the RGB values in MAP to the YCBCR % color space. MAP must be a M-by-3 gpuArray. YCBCRMAP is a M-by-3 % gpuArray that contains the YCBCR luminance (Y) and chrominance % (Cb and Cr) color values as columns. Each row represents the equivalent % color to the corresponding row in the RGB colormap. % % YCBCR = RGB2YCBCR(RGB) converts the truecolor image RGB to the % equivalent image in the YCBCR color space. RGB must be a M-by-N-by-3 % gpuArray. % % If the input gpuArray contains uint8, then YCBCR contains uint8 where Y % is in the range [16 235], and Cb and Cr are in the range [16 240]. If % the input gpuArray contains a double, then Y is in the range % [16/255 235/255] and Cb and Cr are in the range [16/255 240/255]. If % the input gpuArray contains uint16, then Y is in the range [4112 % 60395] and Cb and Cr are in the range [4112 61680]. % % Class Support % ------------- % If the input gpuArray is an RGB image, it can contain uint8, uint16, % single or double. If the input gpuArray is a colormap, then it must % contain single or double. The output has the same class as the input. % % Examples % -------- % Convert RGB image to YCbCr. % % RGB = imread('board.tif'); % YCBCR = rgb2ycbcr(gpuArray(RGB)); % % Convert RGB color space to YCbCr. % % map = jet(256); % newmap = rgb2ycbcr(gpuArray(map)); % % See also NTSC2RGB, RGB2NTSC, GPUARRAY/YCBCR2RGB. % Copyright 1993-2013 The MathWorks, Inc. % References: % C.A. Poynton, "A Technical Introduction to Digital Video", John Wiley % & Sons, Inc., 1996, p. 175 % % Rec. ITU-R BT.601-5, "STUDIO ENCODING PARAMETERS OF DIGITAL TELEVISION % FOR STANDARD 4:3 AND WIDE-SCREEN 16:9 ASPECT RATIOS", % (1982-1986-1990-1992-1994-1995), Section 3.5. rgb = parseInputs(varargin{:}); % Initialize variables isColormap = false; % Reshape colormap to be m x n x 3 for transformation if (ismatrix(rgb)) % Colormap isColormap=true; colors = size(rgb,1); rgb = reshape(rgb, [colors 1 3]); end % This matrix comes from a formula in Poynton's, "Introduction to % Digital Video" (p. 176, equations 9.6). % T is from equation 9.6: ycbcr = origT * rgb + origOffset; origT = [65.481 128.553 24.966;... -37.797 -74.203 112; ... 112 -93.786 -18.214]; origOffset = [16;128;128]; % The formula ycbcr = origT * rgb + origOffset, converts a RGB image in the range % [0 1] to a YCbCr image where Y is in the range [16 235], and Cb and Cr % are in that range [16 240]. For each class type (double,uint8, % uint16), we must calculate scaling factors for origT and origOffset so that % the input image is scaled between 0 and 1, and so that the output image is % in the range of the respective class type. scaleFactor.double.T = 1/255; % scale output so in range [0 1]. scaleFactor.double.offset = 1/255; % scale output so in range [0 1]. scaleFactor.uint8.T = 1/255; % scale input so in range [0 1]. scaleFactor.uint8.offset = 1; % output is already in range [0 255]. scaleFactor.uint16.T = 257/65535; % scale input so it is in range [0 1] % and scale output so it is in range % [0 65535] (255*257 = 65535). scaleFactor.uint16.offset = 257; % scale output so it is in range [0 65535]. scaleFactor.single.T = single(1/255); % scale output so in range [0 1]. scaleFactor.single.offset = single(1/255); % scale output so in range [0 1]. % The formula ycbcr = origT*rgb + origOffset is rewritten as % ycbcr = scaleFactorForT * origT * rgb + scaleFactorForOffset*origOffset. % To use imlincomb, we rewrite the formula as ycbcr = T * rgb + offset, where T and % offset are defined below. classIn = classUnderlying(rgb); if strcmp(classIn,'single') origT = cast(origT,'single'); origOffset = cast(origOffset,'single'); end T = scaleFactor.(classIn).T * origT; offset = scaleFactor.(classIn).offset * origOffset; % Initialize output ycbcr = gpuArray.zeros(size(rgb),classIn); if strcmp(classIn,'uint8') ycbcr = rgb2ycbcrgpumex(rgb); else subR.type = '()'; subR.subs = {':',':',1}; subG.type = '()'; subG.subs = {':',':',2}; subB.type = '()'; subB.subs = {':',':',3}; r = subsref(rgb,subR); g = subsref(rgb,subG); b = subsref(rgb,subB); if ~strcmp(classIn,'single') ||... ~strcmp(classIn,'double') r = cast(r,'double'); g = cast(g,'double'); b = cast(b,'double'); end for p = 1:3 sycbcr.type = '()'; sycbcr.subs = {':',':',p}; TR = T(p,1); TG = T(p,2); TB = T(p,3); offsetp = offset(p); % Use private function lincomb to calculate YCbCr output ycbcr = subsasgn(ycbcr, sycbcr ,... arrayfun(@lincomb,r,g,b,TR,TG,TB,offsetp)); end end if isColormap ycbcr = reshape(ycbcr, [colors 3 1]); end if ~strcmp(classIn,'single') ||... ~strcmp(classIn,'double') ycbcr = cast(ycbcr,classIn); end %%% %Parse Inputs %%% function X = parseInputs(varargin) narginchk(1,1); X = varargin{1}; if ismatrix(X) images.internal.gpu.gpuValidateAttributes(X,{'double','single'},mfilename,'MAP',1); if (size(X,2) ~=3 || size(X,1) < 1) error(message('images:rgb2ycbcr:invalidSizeForColormap')) end elseif ndims(X)==3 images.internal.gpu.gpuValidateAttributes(X,{'uint8','uint16','double','single'},mfilename,'RGB',1); if (size(X,3) ~=3) error(message('images:rgb2ycbcr:invalidTruecolorImage')) end else error(message('images:rgb2ycbcr:invalidInputSize')) end
github
wangsuyuan/Imageprocesingtoobox-master
ycbcr2rgb.m
.m
Imageprocesingtoobox-master/colorspaces/@gpuArray/ycbcr2rgb.m
6,012
utf_8
69a2cde70d14e4eda4fe22a4929b40e4
function rgb = ycbcr2rgb(varargin) %YCBCR2RGB Convert YCbCr color values to RGB color space. % RGBMAP = YCBCR2RGB(YCBCRMAP) converts the YCbCr values in the colormap % YCBCRMAP to the RGB color space. If YCBCRMAP is an M-by-3 gpuArray and % contains the YCbCr luminance (Y) and chrominance (Cb and Cr) color % values as columns, then RGBMAP is an M-by-3 gpuArray that contains the % red, green, and blue values equivalent to those colors. % % RGB = YCBCR2RGB(YCBCR) converts the YCbCr gpuArray image to the % equivalent truecolor gpuArray image RGB. % % Class Support % ------------- % If the input is a YCbCr gpuArray image, it can contain uint8, uint16, % single or double; the output image contains the same class as the input % image. If the input is a colormap, the input and output gpuArray % colormaps can contain single or double. % % Example % ------- % Convert a gpuArray image from RGB space to YCbCr space and back. % % rgb = gpuArray(imread('board.tif')); % ycbcr = rgb2ycbcr(rgb); % rgb2 = ycbcr2rgb(ycbcr); % % See also NTSC2RGB, RGB2NTSC, GPUARRAY/RGB2YCBCR. % Copyright 1993-2013 The MathWorks, Inc. % References: % Charles A. Poynton, "A Technical Introduction to Digital Video", % John Wiley & Sons, Inc., 1996, p. 175-176 % % Rec. ITU-R BT.601-5, "STUDIO ENCODING PARAMETERS OF DIGITAL TELEVISION % FOR STANDARD 4:3 AND WIDE-SCREEN 16:9 ASPECT RATIOS", % (1982-1986-1990-1992-1994-1995), Section 3.5. ycbcr = parseInputs(varargin{:}); classIn = classUnderlying(ycbcr); if strcmp(classIn,'uint8') rgb = ycbcr2rgbgpumex(ycbcr); else isColormap = false; %must reshape colormap to be m x n x 3 for transformation if ismatrix(ycbcr) isColormap = true; colors = size(ycbcr,1); ycbcr = reshape(ycbcr, [colors 1 3]); end % This matrix comes from a formula in Poynton's, "Introduction to % Digital Video" (p. 176, equations 9.6 and 9.7). % T is from equation 9.6: ycbcr = T * rgb + offset; T = [65.481 128.553 24.966;... -37.797 -74.203 112; ... 112 -93.786 -18.214]; % We can rewrite the equation in terms of ycbcr which is % T ^-1 * (ycbcr - offset) = rgb. This is equation 9.7 in the book. Tinv = T^-1; % Tinv = [0.00456621 0. 0.00625893;... % 0.00456621 -0.00153632 -0.00318811;... % 0.00456621 0.00791071 0.] offset = [16;128;128]; % The formula Tinv * (ycbcr - offset) = rgb converts 8-bit YCbCr data to a RGB % image that is scaled between 0 and one. For each class type (double,single, % uint8,uint16), we must calculate scaling factors for Tinv and offset so that % the input image is scaled between 0 and 255, and so that the output image is % in the range of the respective class type. scaleFactor.double.T = 255; % scale input so it is in range [0 255]. scaleFactor.double.offset = 1; % output already in range [0 1]. scaleFactor.uint8.T = 255; % scale output so it is in range [0 255]. scaleFactor.uint8.offset = 255; % scale output so it is in range [0 255]. scaleFactor.uint16.T = 65535/257; % scale input so it is in range [0 255] % (65535/257 = 255), % and scale output so it is in range % [0 65535]. scaleFactor.uint16.offset = 65535; % scale output so it is in range [0 65535]. scaleFactor.single.T = single(255); % scale output so in range [0 1]. scaleFactor.single.offset = single(1); % scale output so in range [0 1]. % The formula Tinv * (ycbcr - offset) = rgb is rewritten as % scaleFactorForT*Tinv*ycbcr - scaleFactorForOffset*Tinv*offset = rgb. % To use lincomb, we rewrite the formula as T * ycbcr - offset, where % T and offset are defined below. if strcmp(classIn,'single') Tinv = cast(Tinv,'single'); offset = cast(offset,'single'); end T = scaleFactor.(classIn).T * Tinv; offset = scaleFactor.(classIn).offset * Tinv * offset; rgb = gpuArray.zeros(size(ycbcr),classIn); subY.type = '()'; subY.subs = {':',':',1}; subCb.type = '()'; subCb.subs = {':',':',2}; subCr.type = '()'; subCr.subs = {':',':',3}; y = subsref(ycbcr,subY); cb = subsref(ycbcr,subCb); cr = subsref(ycbcr,subCr); for p = 1:3 srgb.type = '()'; srgb.subs = {':',':',p}; TY = T(p,1); TCb = T(p,2); TCr = T(p,3); offsetp = -offset(p); if strcmp(classIn,'uint16') % Use private function lincombuint16 to calculate RGB output % for uint16 input rgb = subsasgn(rgb, srgb ,... arrayfun(@lincombuint16,y,cb,cr,TY,TCb,TCr,offsetp)); else % Use private function lincomb to calculate RGB output rgb = subsasgn(rgb, srgb ,... arrayfun(@lincomb,y,cb,cr,TY,TCb,TCr,offsetp)); end end if isColormap rgb = reshape(rgb, [colors 3 1]); end if strcmp(classIn,'double') || ... strcmp(classIn,'single') rgb = min(max(rgb,0.0),1.0); end end %%% %Parse Inputs %%% function X = parseInputs(varargin) narginchk(1,1); X = varargin{1}; if ismatrix(X) images.internal.gpu.gpuValidateAttributes(X,{'double','single','real','nonempty'},... mfilename,'MAP',1); if (size(X,2) ~=3 || size(X,1) < 1) error(message('images:ycbcr2rgb:invalidSizeForColormap')) end elseif ndims(X) == 3 images.internal.gpu.gpuValidateAttributes(X,{'real','uint8','uint16','double','single'},... mfilename,'YCBCR',1); if (size(X,3) ~=3) error(message('images:ycbcr2rgb:invalidTruecolorImage')) end else error(message('images:ycbcr2rgb:invalidInputSize')) end