├── MillionBubbleDataBase └── DownloadData ├── README.md ├── BubFunctions ├── plotellipse.m ├── ImageTrans.m ├── BubInfoExt.m └── ellipsefitting.m ├── LICENSE ├── BubDistribution.m ├── ColorMap ├── README.md ├── LICENSE.TXT ├── brewermap_view.m └── brewermap.m ├── DrawCanvas.m └── Main_ImageGeneration.m /MillionBubbleDataBase/DownloadData: -------------------------------------------------------------------------------- 1 | You can download the data at: 2 | https://data.mendeley.com/datasets/mxnzxzc6v7/1 3 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # BubGAN 2 | Bubble Generative Adversarial Networks (BubGAN) for Bubbly Flow Synthesis. This tool can be used for synthetic bubbly flow generation with your own customized bubbly flow boundary conditions. The single sythetic bubbles ara already pre-generated from the BubGAN algorithm. A total of one million synthetic bubbles are stored in the MillionBubble Data Base with known bubble properties. 3 | 4 | The main script is Main_ImageGeneration.m 5 | 6 | You need to downlaod the MillionBubbleDataBase at: http://dx.doi.org/10.17632/mxnzxzc6v7.1 7 | 8 | # Reference 9 | The related article can be found at https://doi.org/10.1016/j.ces.2019.04.004 or http://arxiv.org/abs/1809.02266 10 | -------------------------------------------------------------------------------- /BubFunctions/plotellipse.m: -------------------------------------------------------------------------------- 1 | function [X,Y] = plotellipse(x, y, a, b, angle, steps) 2 | %# This functions returns points to draw an ellipse 3 | %# 4 | %# @param x X coordinate 5 | %# @param y Y coordinate 6 | %# @param a Semimajor axis 7 | %# @param b Semiminor axis 8 | %# @param angle Angle of the ellipse (in degrees) 9 | %# 10 | 11 | narginchk(5, 6); 12 | if nargin<6, steps = 36; end 13 | 14 | beta = -angle * (pi / 180); 15 | sinbeta = sin(beta); 16 | cosbeta = cos(beta); 17 | 18 | alpha = linspace(0, 360, steps)' .* (pi / 180); 19 | sinalpha = sin(alpha); 20 | cosalpha = cos(alpha); 21 | 22 | X = x + (a * cosalpha * cosbeta - b * sinalpha * sinbeta); 23 | Y = y + (a * cosalpha * sinbeta + b * sinalpha * cosbeta); 24 | 25 | if nargout==1, X = [X Y]; end 26 | end 27 | 28 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Yucheng Fu 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /BubFunctions/ImageTrans.m: -------------------------------------------------------------------------------- 1 | function [I1]=ImageTrans(I,option) 2 | 3 | if strcmp(option,'peel') 4 | if mod(size(I,1),2)==0 5 | R=size(I,1); C=size(I,2); 6 | linearInd=[]; 7 | linearIndPart=[]; 8 | for layer=1:size(I,1)/2 9 | R1=layer; R2=size(I,2)-layer+1; 10 | C1=layer; C2=size(I,1)-layer+1; 11 | Rvec=[R1:1:R2]; 12 | Cvec=[C1:1:C2]; 13 | linearIndA = sub2ind([R C], Rvec(1)*ones(size(Cvec)), Cvec); 14 | linearIndB = sub2ind([R C], Rvec(2:end-1), Cvec(end)*ones(size(Rvec(2:end-1)))); 15 | linearIndC = sub2ind([R C], Rvec(end)*ones(size(Cvec)), flip(Cvec) ); 16 | linearIndD = sub2ind([R C], flip(Rvec(2:end-1)), Cvec(1)*ones(size(Rvec(2:end-1)))); 17 | linearInd=[linearInd linearIndA linearIndB linearIndC linearIndD]; 18 | end 19 | I1=I(linearInd); 20 | I1=reshape(I1,size(I)); 21 | for k=2:2:size(I,1) 22 | I1(:,k)=flip(I1(:,k)); 23 | end 24 | end 25 | end 26 | 27 | 28 | if strcmp(option,'wrap') 29 | if mod(size(I,1),2)==0 30 | for k=2:2:size(I,1) 31 | I(:,k)=flip(I(:,k)); 32 | end 33 | R=size(I,1); C=size(I,2); 34 | linearInd=[]; 35 | linearIndPart=[]; 36 | for layer=1:size(I,1)/2 37 | R1=layer; R2=size(I,2)-layer+1; 38 | C1=layer; C2=size(I,1)-layer+1; 39 | Rvec=[R1:1:R2]; 40 | Cvec=[C1:1:C2]; 41 | linearIndA = sub2ind([R C], Rvec(1)*ones(size(Cvec)), Cvec); 42 | linearIndB = sub2ind([R C], Rvec(2:end-1), Cvec(end)*ones(size(Rvec(2:end-1)))); 43 | linearIndC = sub2ind([R C], Rvec(end)*ones(size(Cvec)), flip(Cvec) ); 44 | linearIndD = sub2ind([R C], flip(Rvec(2:end-1)), Cvec(1)*ones(size(Rvec(2:end-1)))); 45 | linearInd=[linearInd linearIndA linearIndB linearIndC linearIndD]; 46 | end 47 | I1(linearInd)=I; 48 | I1=reshape(I1,size(I)); 49 | end 50 | end 51 | 52 | end 53 | -------------------------------------------------------------------------------- /BubFunctions/BubInfoExt.m: -------------------------------------------------------------------------------- 1 | function [BubInfo boundary]= BubInfoExt(I) 2 | 3 | 4 | %% Extract bubble boundary from the image patch 5 | if size(I,3)==3 6 | I=rgb2gray(I); 7 | end 8 | 9 | bw = im2bw(I); 10 | bw=1-bw; 11 | bwb= bwmorph(bw,'bridge',Inf); 12 | bwb= bwmorph(bwb,'bridge',Inf); 13 | bwb_withhole=bwb; 14 | edgepix=length(find(bwb_withhole==1)); 15 | bwb=imfill(bwb,'holes'); 16 | filledpix=length(find(bwb==1)); 17 | bwb=bwmorph(bwb,'thicken',5); 18 | bwb=activecontour(I, bwb, 10, 'edge'); 19 | 20 | fgind=(bwb_withhole==1); 21 | bgind=(bwb_withhole==0); 22 | 23 | FgInt=mean(I(fgind)); 24 | BgInt=mean(I(bgind)); 25 | 26 | 27 | 28 | 29 | [B]=bwboundaries(bwb,8,'noholes'); % choose the longest boundary if there are two or more 30 | if length(B)>1 31 | len=cellfun(@(x) size(x,1),B); 32 | boundary=B{find(len==max(len))}; 33 | else 34 | boundary=B{1}; 35 | end 36 | 37 | tempx=boundary(:,2); 38 | tempy=boundary(:,1); 39 | dx=abs(tempx-circshift(tempx,1)); 40 | dy=abs(tempy-circshift(tempy,1)); 41 | 42 | boundlen=sum(sqrt(dx.^2+dy.^2)); 43 | Psi=4*pi*filledpix/boundlen^2; 44 | 45 | %% Fit the boundary with ellipse to extract orientatin and semi-axes 46 | 47 | [xx yy aa bb para ellipse_t] = ellipsefitting( boundary(:,2),boundary(:,1) ); 48 | 49 | phi=ellipse_t.phi; % convert the rotation angle to [-pi/2 pi/2], which it the angle between long semi-axis and horizontal direction 50 | if aapi/2 56 | phi=phi-pi; 57 | end 58 | end 59 | 60 | [Gmag, Gdir] = imgradient(I); 61 | Gmag=Gmag/8; % normalize the intenstiy gradient to level/pix. 62 | 63 | idx=sub2ind(size(Gmag),boundary(:,2),boundary(:,1)); 64 | indices=sub2ind(size(Gmag),boundary(:,1),boundary(:,2)); 65 | for k=1:length(boundary(:,1)) 66 | blockszie=4; 67 | boundarygradient(k)=max(max( Gmag( max(1,boundary(k,1)-blockszie):min(size(Gmag,1),boundary(k,1)+blockszie), ... 68 | max(1,boundary(k,2)-blockszie):min(size(Gmag,2),boundary(k,2)+blockszie)) )); 69 | end 70 | EdgeGrad=mean(boundarygradient); 71 | 72 | %% Assign to BubInfo var. 73 | 74 | BubInfo=table(single(aa),single(bb), single(phi), single(xx), single(yy), single(bb/aa),... 75 | single(EdgeGrad), single(edgepix/filledpix),single(Psi),... 76 | single(FgInt),single(BgInt),... 77 | 'VariableNames',{'aa','bb','phi','xx','yy','E','EdgeGrad','ER','Psi','FgInt','BgInt'}); 78 | 79 | 80 | end 81 | 82 | 83 | 84 | -------------------------------------------------------------------------------- /BubDistribution.m: -------------------------------------------------------------------------------- 1 | function [BubList]=BubDistribution( ParaImg, Dim) 2 | Height=Dim(1); 3 | Width=Dim(2); 4 | Depth=Dim(3); 5 | ChannelCapacity=Height*Width*Depth; 6 | 7 | 8 | TotalVolume=0; 9 | BubRefSize=ParaImg.BubRefSize; 10 | BubDev=ParaImg.BubDev; 11 | i=0; 12 | 13 | while TotalVolumea 29 | temp=a; 30 | a=b; 31 | b=temp; 32 | end 33 | phi=pi/2*(0.5-rand); 34 | TotalVolume=TotalVolume+4/3*pi*a*b*c; 35 | BubList(i).a=a; 36 | BubList(i).b=b; 37 | BubList(i).c=c; 38 | BubList(i).phi=phi; 39 | end 40 | 41 | temp= struct2table(BubList); 42 | temp=table2array(temp); 43 | a_avg=mean(temp(:,1)); 44 | b_avg=mean(temp(:,2)); 45 | semi_avg=(a_avg+b_avg)/2; 46 | semi_axes=temp(:,1:3); 47 | 48 | 49 | if ParaImg.DistX.Flag==0 50 | xlist= Width*rand(1,length(BubList)); 51 | else 52 | xlist=SamplefromCounts(ParaImg,length(BubList)); 53 | end 54 | ylist= Height*rand(1,length(BubList)); 55 | zlist= Depth*rand(1,length(BubList)); 56 | loc=[xlist' ylist' zlist']; 57 | 58 | for k=1:length(BubList) % Check if bubble physically touched or overlap together. 59 | if k>1 60 | D1=0; 61 | D2=0; 62 | while min(D1-D2)<0 63 | D1=pdist2(loc(1:k-1,:),semi_axes(k,:),'euclidean'); 64 | D2=max(semi_axes(k-1,:),max(semi_axes(k,:)))*2; 65 | if min(D1-D2)<0 66 | loc(k,2)=semi_avg+(Height-2*semi_avg)*rand; 67 | loc(k,3)=semi_avg+(Depth-2*semi_avg)*rand; 68 | end 69 | end 70 | end 71 | end 72 | 73 | for k=1:length(BubList) 74 | BubList(k).xx=loc(k,1); 75 | BubList(k).yy=loc(k,2); 76 | BubList(k).zz=loc(k,3); 77 | end 78 | end 79 | 80 | %% Sample Location of bubble number density distribtion 81 | function [Loc]=SamplefromCounts(ParaImg,nSample) 82 | 83 | LocinPix=[ParaImg.pixtomm/2:ParaImg.pixtomm:ParaImg.Width-ParaImg.pixtomm/2]; 84 | CountsinPix=interp1(ParaImg.DistX.Loc,ParaImg.DistX.Counts,LocinPix,'linear','extrap'); 85 | CountsinPix=CountsinPix/max(1e-20,min(CountsinPix)); 86 | CountsinPixcum=cumsum(CountsinPix); 87 | CP=floor(rand(1,nSample)*CountsinPixcum(end)); 88 | for k=1:nSample 89 | Loc(k)=LocinPix(find(CP(k)<=CountsinPixcum,1)); 90 | end 91 | end 92 | -------------------------------------------------------------------------------- /ColorMap/README.md: -------------------------------------------------------------------------------- 1 | BrewerMap 2 | ========= 3 | 4 | The complete palette of ColorBrewer colormaps for MATLAB. Simple selection by scheme name and map length. 5 | 6 | 7 | One function provides the complete selection of the ColorBrewer colorschemes, especially intended for mapping and plots with attractive, distinguishable colors. 8 | 9 | Simple to use: only the the colormap length and the colorscheme name are needed to select and define an output colormap. The colorscheme can be preselected by the user, after which only the colormap length is required to define an output colormap. 10 | 11 | The function can be used as a drop-in replacement for the inbuilt colormap functions and it is compatible with all MATLAB functions that require a colormap. The function consists of just one M-file that provides all of the ColorBrewer colorschemes (no mat file, no third party files, no file-clutter!). Downsampling or interpolation of the nodes occurs automatically, if required (interpolation occurs within the Lab colorspace). As an option, the colormap can be returned reversed. 12 | 13 | Calling brewermap('plot') creates a figure that displays all of the ColorBrewer colorschemes. 14 | 15 | This product includes color specifications and designs developed by Cynthia Brewer (http://colorbrewer.org/). See the ColorBrewer website for further information about each colorscheme, colorblind suitability, licensing, and citations. 16 | 17 | ### Examples ### 18 | 19 | % Plot a scheme's RGB values: 20 | rgbplot(brewermap(9,'Blues')) % standard 21 | rgbplot(brewermap(9,'*Blues')) % reversed 22 | 23 | % View information about a colorscheme: 24 | [~,num,typ] = brewermap(0,'Paired') 25 | num = 12 26 | typ = 'Qualitative' 27 | 28 | % Multiline plot using matrices: 29 | N = 6; 30 | axes('ColorOrder',brewermap(N,'Pastel2'),'NextPlot','replacechildren') 31 | X = linspace(0,pi*3,1000); 32 | Y = bsxfun(@(x,n)n*sin(x+2*n*pi/N), X.', 1:N); 33 | plot(X,Y, 'linewidth',4) 34 | 35 | % Multiline plot in a loop: 36 | N = 6; 37 | set(0,'DefaultAxesColorOrder',brewermap(N,'Accent')) 38 | X = linspace(0,pi*3,1000); 39 | Y = bsxfun(@(x,n)n*sin(x+2*n*pi/N), X.', 1:N); 40 | for n = 1:N 41 | plot(X(:),Y(:,n), 'linewidth',4); 42 | hold all 43 | end 44 | 45 | % New colors for the COLORMAP example: 46 | load spine 47 | image(X) 48 | colormap(brewermap([],'YlGnBu')) 49 | 50 | % New colors for the SURF example: 51 | [X,Y,Z] = peaks(30); 52 | surfc(X,Y,Z) 53 | colormap(brewermap([],'RdYlGn')) 54 | axis([-3,3,-3,3,-10,5]) 55 | 56 | % New colors for the CONTOURCMAP example: 57 | brewermap('PuOr'); % preselect the colorscheme. 58 | load topo 59 | load coast 60 | figure 61 | worldmap(topo, topolegend) 62 | contourfm(topo, topolegend); 63 | contourcmap('brewermap', 'Colorbar','on', 'Location','horizontal',... 64 | 'TitleString','Contour Intervals in Meters'); 65 | plotm(lat, long, 'k') 66 | 67 | ### Note ### 68 | 69 | Note that the function BREWERMAP: 70 | * Consists of just one convenient M-file (no .mat files or file clutter). 71 | * No third-party file dependencies. 72 | * Interpolates in the Lab colorspace. 73 | * Requires just the standard ColorBrewer scheme name to select the colorscheme. 74 | * Supports all ColorBrewer colorschemes. 75 | * Outputs a MATLAB standard N-by-3 numeric RGB array. 76 | * Default length is the standard MATLAB default colormap length (same length as the current colormap). 77 | * Is compatible with all MATLAB functions that use colormaps (eg: CONTOURCMAP). 78 | * Includes the option to reverse the colormap color sequence. 79 | * Does not break ColorBrewer's Apache license conditions! 80 | -------------------------------------------------------------------------------- /DrawCanvas.m: -------------------------------------------------------------------------------- 1 | function [ImageCanvas,ImgLabel]=DrawCanvas(BubList,ParaImg,BubImage,BubInfo,SelectBubRange) 2 | ImageCanvas=ParaImg.ImageCanvas; 3 | 4 | for k=1:size(BubList,2) 5 | disp([' Generating bubble ', num2str(k),' of ', num2str(size(BubList,2))]) 6 | RandBubNum=randi([1 SelectBubRange]); 7 | patchimage = BubImage(:,:,RandBubNum); 8 | [patchBubInfo patchboundary]=BubInfoExt(patchimage); 9 | [patchimage patchBubInfo patchboundary mask mask1 mask2 ratio]=patchscale(patchimage, patchBubInfo, patchboundary, BubList(k).a/ParaImg.pixtomm); 10 | 11 | % center (xxg yyg) and boundary (xg yg) in global canvas with pixel unit 12 | xg=patchboundary(:,2)+BubList(k).xx/ParaImg.pixtomm-patchBubInfo.xx; 13 | yg=patchboundary(:,1)+BubList(k).yy/ParaImg.pixtomm-patchBubInfo.yy; 14 | xxg=BubList(k).xx/ParaImg.pixtomm; 15 | yyg=BubList(k).yy/ParaImg.pixtomm; 16 | 17 | % apply boundary physical restriction on x direction 18 | [xxg, yyg, xg,yg]=phyrestriction(ParaImg.ImageCanvas,xxg, yyg, xg,yg, 'x'); 19 | %[xxg, yyg, xg,yg]=phyrestriction(ParaImg.ImageCanvas,xxg, yyg, xg,yg, 'y'); 20 | 21 | locx=round(xxg-patchBubInfo.xx)+1; 22 | locx1=locx+size(patchimage,1)-1; 23 | locy=round(yyg-patchBubInfo.yy)+1; 24 | locy1=locy+size(patchimage,1)-1; 25 | patchloc=[locx locx1 locy locy1]; 26 | 27 | 28 | [ImageCanvas, patchimage, mask, mask1, mask2, patchloc]=patchcrop(ImageCanvas, patchimage, mask, mask1, mask2, patchloc); 29 | ImgLabel(k).BubInfo=patchBubInfo; 30 | ImgLabel(k).boundary=[yg xg]; 31 | ImgLabel(k).xx=xxg; 32 | ImgLabel(k).yy=yyg; 33 | ImgLabel(k).resolution=ParaImg.pixtomm; 34 | ImgLabel(k).patchimage=patchimage; 35 | end 36 | end 37 | 38 | 39 | 40 | 41 | 42 | 43 | %% Fine physical restriction 44 | function [xcenter, ycenter, x,y]=phyrestriction(ImageCanvas,xcenter, ycenter, x,y, direction) 45 | if strcmp(direction,'x')==1 46 | if max(x(:))>size(ImageCanvas,2) 47 | xcenter=xcenter- (max(x(:))-size(ImageCanvas,2)); 48 | x=x-(max(x(:))-size(ImageCanvas,2)); 49 | end 50 | if min(x(:))<0 51 | xcenter=xcenter+1-min(x(:)); 52 | x=x+1-min(x(:)); 53 | end 54 | end 55 | if strcmp(direction,'y')==1 56 | if max(y(:))>size(ImageCanvas,1) 57 | ycenter=ycenter- (max(y(:))-size(ImageCanvas,1)); 58 | y=y-(max(y(:))-size(ImageCanvas,1)); 59 | end 60 | if min(y(:))<0 61 | ycenter=ycenter+1- min(y(:)); 62 | y=y+1-min(y(:)); 63 | end 64 | end 65 | end 66 | 67 | 68 | %% patchscale scale the patch to given size 69 | function [patchimage patchBubInfo patchboundary mask mask1 mask2 ratio]=patchscale(patchimage, patchBubInfo, patchboundary, Bubsize) 70 | % Bubsize is the given size for bubble generation. The 64 by 64 pixel 71 | % bubble image from million-bubble database should be scaled to the 72 | % given size. 73 | % Bubsize should be given in pixel. 74 | 75 | ratio=Bubsize/patchBubInfo.aa; 76 | patchpix=size(patchimage,1)*ratio; 77 | patchimage=imresize(patchimage, [patchpix patchpix]); 78 | patchBubInfo.aa = patchBubInfo.aa*ratio; 79 | patchBubInfo.bb = patchBubInfo.bb*ratio; 80 | patchBubInfo.xx = patchBubInfo.xx*ratio; 81 | patchBubInfo.yy = patchBubInfo.yy*ratio; 82 | patchboundary=double(patchboundary*ratio); 83 | mask=poly2mask(patchboundary(:,2),patchboundary(:,1),size(patchimage,1),size(patchimage,2)); 84 | mask1=bwmorph(mask,'thicken',1); 85 | mask2=bwmorph(mask,'thicken',2)- bwmorph(mask,'thicken',0); 86 | end 87 | 88 | %% patchcrop: crops the patch parts which is outside the ImageCanvas and then paint it 89 | function [ImageCanvas, patchimage, mask, mask1, mask2, patchloc]=patchcrop(ImageCanvas, patchimage, mask, mask1, mask2, patchloc) 90 | dx=0; dx1=0; dy=0; dy1=0; 91 | locx=patchloc(1); 92 | locx1=patchloc(2); 93 | locy=patchloc(3); 94 | locy1=patchloc(4); 95 | if locx<=0 96 | dx=1-locx; 97 | locx=locx+dx; 98 | mask1=mask1(:,1+dx:end); 99 | mask2=mask2(:,1+dx:end); 100 | patchimage=patchimage(:,1+dx:end); 101 | end 102 | if locx1>size(ImageCanvas,2) 103 | dx1=locx1-size(ImageCanvas,2); 104 | locx1=locx1-dx1; 105 | mask1=mask1(:,1:end-dx1); 106 | mask2=mask2(:,1:end-dx1); 107 | patchimage=patchimage(:,1:end-dx1); 108 | end 109 | if locy<=0 110 | dy=1-locy; 111 | locy=locy+dy; 112 | mask1=mask1(1+dy:end,:); 113 | mask2=mask2(1+dy:end,:); 114 | patchimage=patchimage(1+dy:end,:); 115 | end 116 | if locy1>size(ImageCanvas,1) 117 | dy1=locy1-size(ImageCanvas,1); 118 | locy1=locy1-dy1; 119 | mask1=mask1(1:end-dy1,:); 120 | mask2=mask2(1:end-dy1,:); 121 | patchimage=patchimage(1:end-dy1,:); 122 | end 123 | 124 | maskcanvas1=boolean(zeros(size(ImageCanvas))); 125 | maskcanvas1(locy:locy1,locx:locx1)=mask1; 126 | maskcanvas2=boolean(zeros(size(ImageCanvas))); 127 | maskcanvas2(locy:locy1,locx:locx1)=mask2; 128 | patchimage=patchimage+uint8(double(mode(ImageCanvas(maskcanvas1)))-double(mode(patchimage(:)))); % adjust bubble intensity according to surrounding background(ImageCanvas) 129 | ImageCanvas(maskcanvas1)=patchimage(mask1); 130 | ImageCanvas=regionfill(ImageCanvas,maskcanvas2); 131 | 132 | end 133 | 134 | 135 | 136 | -------------------------------------------------------------------------------- /Main_ImageGeneration.m: -------------------------------------------------------------------------------- 1 | clc 2 | clearvars -except BubImage 3 | close all 4 | warning off 5 | %Set the plot parameters********************************** 6 | nF=1; 7 | set(0,'DefaultFigureUnits','pixels','DefaultFigurePosition',[0 0 round(nF*800) round(nF*800)]) 8 | set(0,'DefaultFigureColor',[1 1 1]) 9 | set(0,'DefaultAxesUnits','normalized','DefaultAxesPosition',[0.13 0.13 0.75 0.8]) 10 | %set(0,'DefaultAxesXTickMode','manual','DefaultAxesYTickMode','manual') 11 | set(0,'DefaultAxesTickLength',[0.02 0.02]) 12 | set(0,'DefaultAxesXMinorTick','off','DefaultAxesYMinorTick','off') 13 | set(0,'DefaultAxesLineWidth',ceil(1.5),'DefaultAxesFontName','Arial',... 14 | 'DefaultAxesFontSize',ceil(30),'DefaultAxesBox','on') 15 | set(0,'DefaultLineLineWidth',ceil(1.5),'DefaultLineMarkerSize',ceil(8)) 16 | set(0,'DefaulttextFontName','Arial','DefaulttextFontSize',26) 17 | %Set the plot parameters********************************** 18 | 19 | rng(10) % for reproducibility 20 | addpath ./BubFunctions 21 | addpath ./ColorMap 22 | 23 | InputFolder=['.\MillionBubbleDataBase\']; 24 | 25 | if ~exist('BubImage','var') 26 | load([InputFolder,'MillionBub.mat']) % load million bubble image database 27 | end 28 | SelectBubRange=1000000; % choose from 1:1000000 images 29 | load([InputFolder,'Synthetic_BubInfo.mat']) % Corresponding bubble information 30 | 31 | ImageGenNum=1; % Generating image number 32 | SaveFlag=1; % Do not save data 33 | 34 | %% Parameter setup for bubbly flow generation 35 | %% Setup interested simulation domain 36 | ParaImg.Depth=10; % mm 37 | ParaImg.Width=30; % mm 38 | ParaImg.Height=60; % mm 39 | ParaImg.VoidFraction=0.1; %[-] The void fraction is calculated by estimating third axis along camera optical axis is same to the short axis in 2D projection 40 | ParaImg.pixtomm=0.05; % mm/pix Image Resolution 41 | ParaImg.bckgrdint=183; 42 | ParaImg.TotVol=ParaImg.Depth*ParaImg.Width*ParaImg.Height; % mm^3 43 | 44 | %% Bubble size distribution 45 | ParaImg.BubRefSize=3.5; % Bubble mean diameter 46 | ParaImg.BubSizeMode='uniform'; % uniform or Gaussian 47 | ParaImg.BubDev=1; % If uniform distribution, bubble diameter range from [BubRefSize-BubDev, BubRefSize+BubDev] 48 | % If Gaussian distribution, BubDev serve as standard deviation 49 | 50 | %% Bubble Location distribution along x direction 51 | ParaImg.DistX.Flag=1; 52 | ParaImg.DistX.Loc=[1:1:30]; 53 | ParaImg.DistX.Counts(1:30)=10; % uniform density. The value is relative value. 54 | % 55 | % ParaImg.DistX.Counts(1:5)=10; %This is non-uniform bubble density 56 | % ParaImg.DistX.Counts(6:25)=4; 57 | % ParaImg.DistX.Counts(26:30)=10; 58 | 59 | %% Generate Image Canvas 60 | % The Image Canvas can also be loaded from existed background 61 | ImageCanvas=double(ones(round(ParaImg.Height/ParaImg.pixtomm),round(ParaImg.Width/ParaImg.pixtomm)))*ParaImg.bckgrdint; 62 | ImageCanvas=ImageCanvas+2*randn(size(ImageCanvas)); % Add noise 63 | ParaImg.ImageCanvas=uint8(ImageCanvas); 64 | 65 | %% Image Generation 66 | for k=1:ImageGenNum 67 | disp(['Generating the image of ', num2str(k,'%3.f')]) 68 | [BubList]=BubDistribution( ParaImg,[ParaImg.Height, ParaImg.Width, ParaImg.Depth]); % generated bubble parameters 69 | [ImageCanvas_Painted,ImgLabel]=DrawCanvas(BubList,ParaImg,BubImage,BubInfo,SelectBubRange); %draw bubbles on canvas 70 | if SaveFlag 71 | %% Save Generated images and bubble label information 72 | imwrite(ImageCanvas_Painted, sprintf('Image_%03.f.tif', k)); 73 | save( sprintf('Label_%03.f.mat',k),'ImgLabel') 74 | end 75 | end 76 | 77 | %% Display Painted Image 78 | figure, 79 | imshow(ImageCanvas_Painted) 80 | 81 | %% Area Label information plot 82 | 83 | figure, 84 | patch([0 0 size(ImageCanvas_Painted,2) size(ImageCanvas_Painted,2) 0],[0 size(ImageCanvas_Painted,1) size(ImageCanvas_Painted,1) 0 0],[0 0 0],'FaceAlpha',0.2) 85 | hold on 86 | for k=1:length(ImgLabel) 87 | boundary=ImgLabel(k).boundary; 88 | index1=find(boundary(:,2)<0); 89 | index2=find(boundary(:,2)>size(ImageCanvas_Painted,2)); 90 | index3=find(boundary(:,1)<0); 91 | index4=find(boundary(:,1)>size(ImageCanvas_Painted,1)); 92 | boundary([index1 index2 index3 index4],:)=[]; 93 | 94 | area = polyarea(boundary(:,1),boundary(:,2)); 95 | area = area*ImgLabel(k).resolution^2; 96 | patch(boundary(:,2),boundary(:,1),area,'FaceAlpha',1) 97 | plot(ImgLabel(k).xx,ImgLabel(k).yy,'r.') 98 | end 99 | plot([0 0 size(ImageCanvas_Painted,2) size(ImageCanvas_Painted,2) 0],[0 size(ImageCanvas_Painted,1) size(ImageCanvas_Painted,1) 0 0],'k','LineWidth',1) 100 | axis equal 101 | axis off 102 | set(gca, 'YDir','reverse') 103 | colormap(brewermap([],'*Spectral')) 104 | c=colorbar 105 | ylabel(c,'Area $[\mathrm{mm}^2]$','Interpreter','Latex') 106 | if SaveFlag, saveas(gcf,'Bubbly_Labeled_Area.tif'),end 107 | %% Rotation angle Label information plot 108 | figure, 109 | patch([0 0 size(ImageCanvas_Painted,2) size(ImageCanvas_Painted,2) 0],[0 size(ImageCanvas_Painted,1) size(ImageCanvas_Painted,1) 0 0],[0 0 0],'FaceAlpha',0.2) 110 | hold on 111 | for k=1:length(ImgLabel) 112 | boundary=ImgLabel(k).boundary; 113 | index1=find(boundary(:,2)<0); 114 | index2=find(boundary(:,2)>size(ImageCanvas_Painted,2)); 115 | index3=find(boundary(:,1)<0); 116 | index4=find(boundary(:,1)>size(ImageCanvas_Painted,1)); 117 | boundary([index1 index2 index3 index4],:)=[]; 118 | patch(boundary(:,2),boundary(:,1),ImgLabel(k).BubInfo.phi,'FaceAlpha',1) 119 | plot(ImgLabel(k).xx,ImgLabel(k).yy,'r.') 120 | end 121 | plot([0 0 size(ImageCanvas_Painted,2) size(ImageCanvas_Painted,2) 0],[0 size(ImageCanvas_Painted,1) size(ImageCanvas_Painted,1) 0 0],'k','LineWidth',1) 122 | axis equal 123 | axis off 124 | set(gca, 'YDir','reverse') 125 | colormap(brewermap([],'PiYG')) 126 | c=colorbar; 127 | caxis([-pi/2 pi/2]) 128 | ylabel(c,'Rotation angle $\varphi$ [rad] ','Interpreter','Latex') 129 | if SaveFlag, saveas(gcf,'Bubbly_Labeled_phi.tif'),end 130 | 131 | %% Aspect Ratio information plot 132 | figure, 133 | patch([0 0 size(ImageCanvas_Painted,2) size(ImageCanvas_Painted,2) 0],[0 size(ImageCanvas_Painted,1) size(ImageCanvas_Painted,1) 0 0],[0 0 0],'FaceAlpha',0.2) 134 | hold on 135 | for k=1:length(ImgLabel) 136 | boundary=ImgLabel(k).boundary; 137 | index1=find(boundary(:,2)<0); 138 | index2=find(boundary(:,2)>size(ImageCanvas_Painted,2)); 139 | index3=find(boundary(:,1)<0); 140 | index4=find(boundary(:,1)>size(ImageCanvas_Painted,1)); 141 | boundary([index1 index2 index3 index4],:)=[]; 142 | patch(boundary(:,2),boundary(:,1),ImgLabel(k).BubInfo.E,'FaceAlpha',1) 143 | plot(ImgLabel(k).xx,ImgLabel(k).yy,'r.') 144 | end 145 | plot([0 0 size(ImageCanvas_Painted,2) size(ImageCanvas_Painted,2) 0],[0 size(ImageCanvas_Painted,1) size(ImageCanvas_Painted,1) 0 0],'k','LineWidth',1) 146 | axis equal 147 | axis off 148 | set(gca, 'YDir','reverse') 149 | colormap(brewermap([],'*YlOrBr')) 150 | c=colorbar; 151 | caxis([0.5 1]) 152 | ylabel(c,'Aspect ratio $E$ [-] ','Interpreter','Latex') 153 | if SaveFlag, saveas(gcf,'Bubbly_Labeled_E.tif'),end 154 | 155 | %% Bubble Intensity information plot 156 | XCenter=[ImgLabel.xx]'; 157 | YCenter=[ImgLabel.yy]'; 158 | Center=[XCenter YCenter]; 159 | C=zeros(size(ImageCanvas_Painted)); 160 | Sigma = [100 0; 0 100]; 161 | x1 =1:1:600; x2 =1:1:1200; 162 | [X1,X2] = meshgrid(x1,x2); 163 | for k=1:size(XCenter) 164 | mu = [XCenter(k) YCenter(k)]; 165 | F = mvnpdf([X1(:) X2(:)],mu,Sigma); 166 | F = reshape(F,length(x2),length(x1)); 167 | C=C+F; 168 | end 169 | figure, 170 | imagesc(x1,x2,C); 171 | axis equal 172 | axis off 173 | if SaveFlag, saveas(gcf,'Bubbly_Labeled_Intensity.tif'),end 174 | 175 | 176 | -------------------------------------------------------------------------------- /ColorMap/LICENSE.TXT: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | -------------------------------------------------------------------------------- /BubFunctions/ellipsefitting.m: -------------------------------------------------------------------------------- 1 | function [xx yy aa bb para ellipse_t] = ellipsefitting( x,y ) 2 | % 3 | % fit_ellipse - finds the best fit to an ellipse for the given set of points. 4 | % 5 | % Format: ellipse_t = fit_ellipse( x,y,axis_handle ) 6 | % 7 | % Input: x,y - a set of points in 2 column vectors. AT LEAST 5 points are needed ! 8 | % axis_handle - optional. a handle to an axis, at which the estimated ellipse 9 | % will be drawn along with it's axes 10 | % 11 | % Output: ellipse_t - structure that defines the best fit to an ellipse 12 | % a - sub axis (radius) of the X axis of the non-tilt ellipse 13 | % b - sub axis (radius) of the Y axis of the non-tilt ellipse 14 | % phi - orientation in radians of the ellipse (tilt) 15 | % X0 - center at the X axis of the non-tilt ellipse 16 | % Y0 - center at the Y axis of the non-tilt ellipse 17 | % X0_in - center at the X axis of the tilted ellipse 18 | % Y0_in - center at the Y axis of the tilted ellipse 19 | % long_axis - size of the long axis of the ellipse 20 | % short_axis - size of the short axis of the ellipse 21 | % status - status of detection of an ellipse 22 | % 23 | % Note: if an ellipse was not detected (but a parabola or hyperbola), then 24 | % an empty structure is returned 25 | 26 | % ===================================================================================== 27 | % Ellipse Fit using Least Squares criterion 28 | % ===================================================================================== 29 | % We will try to fit the best ellipse to the given measurements. the mathematical 30 | % representation of use will be the CONIC Equation of the Ellipse which is: 31 | % 32 | % Ellipse = a*x^2 + b*x*y + c*y^2 + d*x + e*y + f = 0 33 | % 34 | % The fit-estimation method of use is the Least Squares method (without any weights) 35 | % The estimator is extracted from the following equations: 36 | % 37 | % g(x,y;A) := a*x^2 + b*x*y + c*y^2 + d*x + e*y = f 38 | % 39 | % where: 40 | % A - is the vector of parameters to be estimated (a,b,c,d,e) 41 | % x,y - is a single measurement 42 | % 43 | % We will define the cost function to be: 44 | % 45 | % Cost(A) := (g_c(x_c,y_c;A)-f_c)'*(g_c(x_c,y_c;A)-f_c) 46 | % = (X*A+f_c)'*(X*A+f_c) 47 | % = A'*X'*X*A + 2*f_c'*X*A + N*f^2 48 | % 49 | % where: 50 | % g_c(x_c,y_c;A) - vector function of ALL the measurements 51 | % each element of g_c() is g(x,y;A) 52 | % X - a matrix of the form: [x_c.^2, x_c.*y_c, y_c.^2, x_c, y_c ] 53 | % f_c - is actually defined as ones(length(f),1)*f 54 | % 55 | % Derivation of the Cost function with respect to the vector of parameters "A" yields: 56 | % 57 | % A'*X'*X = -f_c'*X = -f*ones(1,length(f_c))*X = -f*sum(X) 58 | % 59 | % Which yields the estimator: 60 | % 61 | % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 62 | % | A_least_squares = -f*sum(X)/(X'*X) ->(normalize by -f) = sum(X)/(X'*X) | 63 | % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 64 | % 65 | % (We will normalize the variables by (-f) since "f" is unknown and can be accounted for later on) 66 | % 67 | % NOW, all that is left to do is to extract the parameters from the Conic Equation. 68 | % We will deal the vector A into the variables: (A,B,C,D,E) and assume F = -1; 69 | % 70 | % Recall the conic representation of an ellipse: 71 | % 72 | % A*x^2 + B*x*y + C*y^2 + D*x + E*y + F = 0 73 | % 74 | % We will check if the ellipse has a tilt (=orientation). The orientation is present 75 | % if the coefficient of the term "x*y" is not zero. If so, we first need to remove the 76 | % tilt of the ellipse. 77 | % 78 | % If the parameter "B" is not equal to zero, then we have an orientation (tilt) to the ellipse. 79 | % we will remove the tilt of the ellipse so as to remain with a conic representation of an 80 | % ellipse without a tilt, for which the math is more simple: 81 | % 82 | % Non tilt conic rep.: A`*x^2 + C`*y^2 + D`*x + E`*y + F` = 0 83 | % 84 | % We will remove the orientation using the following substitution: 85 | % 86 | % Replace x with cx+sy and y with -sx+cy such that the conic representation is: 87 | % 88 | % A(cx+sy)^2 + B(cx+sy)(-sx+cy) + C(-sx+cy)^2 + D(cx+sy) + E(-sx+cy) + F = 0 89 | % 90 | % where: c = cos(phi) , s = sin(phi) 91 | % 92 | % and simplify... 93 | % 94 | % x^2(A*c^2 - Bcs + Cs^2) + xy(2A*cs +(c^2-s^2)B -2Ccs) + ... 95 | % y^2(As^2 + Bcs + Cc^2) + x(Dc-Es) + y(Ds+Ec) + F = 0 96 | % 97 | % The orientation is easily found by the condition of (B_new=0) which results in: 98 | % 99 | % 2A*cs +(c^2-s^2)B -2Ccs = 0 ==> phi = 1/2 * atan( b/(c-a) ) 100 | % 101 | % Now the constants c=cos(phi) and s=sin(phi) can be found, and from them 102 | % all the other constants A`,C`,D`,E` can be found. 103 | % 104 | % A` = A*c^2 - B*c*s + C*s^2 D` = D*c-E*s 105 | % B` = 2*A*c*s +(c^2-s^2)*B -2*C*c*s = 0 E` = D*s+E*c 106 | % C` = A*s^2 + B*c*s + C*c^2 107 | % 108 | % Next, we want the representation of the non-tilted ellipse to be as: 109 | % 110 | % Ellipse = ( (X-X0)/a )^2 + ( (Y-Y0)/b )^2 = 1 111 | % 112 | % where: (X0,Y0) is the center of the ellipse 113 | % a,b are the ellipse "radiuses" (or sub-axis) 114 | % 115 | % Using a square completion method we will define: 116 | % 117 | % F`` = -F` + (D`^2)/(4*A`) + (E`^2)/(4*C`) 118 | % 119 | % Such that: a`*(X-X0)^2 = A`(X^2 + X*D`/A` + (D`/(2*A`))^2 ) 120 | % c`*(Y-Y0)^2 = C`(Y^2 + Y*E`/C` + (E`/(2*C`))^2 ) 121 | % 122 | % which yields the transformations: 123 | % 124 | % X0 = -D`/(2*A`) 125 | % Y0 = -E`/(2*C`) 126 | % a = sqrt( abs( F``/A` ) ) 127 | % b = sqrt( abs( F``/C` ) ) 128 | % 129 | % And finally we can define the remaining parameters: 130 | % 131 | % long_axis = 2 * max( a,b ) 132 | % short_axis = 2 * min( a,b ) 133 | % Orientation = phi 134 | % 135 | % 136 | 137 | 138 | % initialize 139 | orientation_tolerance = 1e-3; 140 | 141 | % empty warning stack 142 | warning( '' ); 143 | 144 | % prepare vectors, must be column vectors 145 | x = x(:); 146 | y = y(:); 147 | 148 | % remove bias of the ellipse - to make matrix inversion more accurate. (will be added later on). 149 | mean_x = mean(x); 150 | mean_y = mean(y); 151 | x = x-mean_x; 152 | y = y-mean_y; 153 | 154 | % the estimation for the conic equation of the ellipse 155 | X = [x.^2, x.*y, y.^2, x, y ]; 156 | a = sum(X)/(X'*X); 157 | 158 | % check for warnings 159 | if ~isempty( lastwarn ) 160 | disp( 'stopped because of a warning regarding matrix inversion' ); 161 | ellipse_t = []; 162 | return 163 | end 164 | 165 | % extract parameters from the conic equation 166 | [a,b,c,d,e] = deal( a(1),a(2),a(3),a(4),a(5) ); 167 | para=[a,b,c,d,e]; 168 | % remove the orientation from the ellipse 169 | if ( min(abs(b/a),abs(b/c)) > orientation_tolerance ) 170 | 171 | orientation_rad = 1/2 * atan( b/(c-a) ); 172 | cos_phi = cos( orientation_rad ); 173 | sin_phi = sin( orientation_rad ); 174 | [a,b,c,d,e] = deal(... 175 | a*cos_phi^2 - b*cos_phi*sin_phi + c*sin_phi^2,... 176 | 0,... 177 | a*sin_phi^2 + b*cos_phi*sin_phi + c*cos_phi^2,... 178 | d*cos_phi - e*sin_phi,... 179 | d*sin_phi + e*cos_phi ); 180 | [mean_x,mean_y] = deal( ... 181 | cos_phi*mean_x - sin_phi*mean_y,... 182 | sin_phi*mean_x + cos_phi*mean_y ); 183 | else 184 | % save('errortest','x','y') 185 | orientation_rad = 0; 186 | cos_phi = cos( orientation_rad ); 187 | sin_phi = sin( orientation_rad ); 188 | end 189 | 190 | % check if conic equation represents an ellipse 191 | test = a*c; 192 | switch (1) 193 | case (test>0), status = ''; 194 | case (test==0), status = 'Parabola found'; warning( 'fit_ellipse: Did not locate an ellipse' ); 195 | case (test<0), status = 'Hyperbola found'; warning( 'fit_ellipse: Did not locate an ellipse' ); 196 | end 197 | 198 | 199 | % if we found an ellipse return it's data 200 | if (test>0) 201 | 202 | % make sure coefficients are positive as required 203 | if (a<0), [a,c,d,e] = deal( -a,-c,-d,-e ); end 204 | 205 | % final ellipse parameters 206 | X0 = mean_x - d/2/a; 207 | Y0 = mean_y - e/2/c; 208 | F = 1 + (d^2)/(4*a) + (e^2)/(4*c); 209 | [a,b] = deal( sqrt( F/a ),sqrt( F/c ) ); 210 | long_axis = 2*max(a,b); 211 | short_axis = 2*min(a,b); 212 | 213 | % rotate the axes backwards to find the center point of the original TILTED ellipse 214 | R = [ cos_phi sin_phi; -sin_phi cos_phi ]; 215 | P_in = R * [X0;Y0]; 216 | X0_in = P_in(1); 217 | Y0_in = P_in(2); 218 | 219 | % pack ellipse into a structure 220 | ellipse_t = struct( ... 221 | 'a',a,... 222 | 'b',b,... 223 | 'phi',orientation_rad,... 224 | 'X0',X0,... 225 | 'Y0',Y0,... 226 | 'X0_in',X0_in,... 227 | 'Y0_in',Y0_in,... 228 | 'long_axis',long_axis,... 229 | 'short_axis',short_axis,... 230 | 'status','' ); 231 | xx=X0_in; 232 | yy=Y0_in; 233 | aa=a; 234 | bb=b; 235 | 236 | 237 | else 238 | % report an empty structure 239 | ellipse_t = struct( ... 240 | 'a',[],... 241 | 'b',[],... 242 | 'phi',[],... 243 | 'X0',[],... 244 | 'Y0',[],... 245 | 'X0_in',[],... 246 | 'Y0_in',[],... 247 | 'long_axis',[],... 248 | 'short_axis',[],... 249 | 'status',status ); 250 | % fit the points with a circle 251 | xx=mean(x(:)); 252 | yy=mean(y(:)); 253 | r=mean( ((x-xx).^2+(y-yy).^2).^(1/2) ); 254 | aa=r; 255 | bb=r; 256 | para=[]; 257 | 258 | 259 | 260 | end 261 | end 262 | 263 | % check if we need to plot an ellipse with it's axes. 264 | % if (nargin>2) & ~isempty( axis_handle ) & (test>0) 265 | % 266 | % % rotation matrix to rotate the axes with respect to an angle phi 267 | % R = [ cos_phi sin_phi; -sin_phi cos_phi ]; 268 | % 269 | % % the axes 270 | % ver_line = [ [X0 X0]; Y0+b*[-1 1] ]; 271 | % horz_line = [ X0+a*[-1 1]; [Y0 Y0] ]; 272 | % new_ver_line = R*ver_line; 273 | % new_horz_line = R*horz_line; 274 | % 275 | % % the ellipse 276 | % theta_r = linspace(0,2*pi); 277 | % ellipse_x_r = X0 + a*cos( theta_r ); 278 | % ellipse_y_r = Y0 + b*sin( theta_r ); 279 | % rotated_ellipse = R * [ellipse_x_r;ellipse_y_r]; 280 | % 281 | % % draw 282 | % hold_state = get( axis_handle,'NextPlot' ); 283 | % set( axis_handle,'NextPlot','add' ); 284 | % plot( new_ver_line(1,:),new_ver_line(2,:),'r' ); 285 | % plot( new_horz_line(1,:),new_horz_line(2,:),'r' ); 286 | % plot( rotated_ellipse(1,:),rotated_ellipse(2,:),'r' ); 287 | % set( axis_handle,'NextPlot',hold_state ); 288 | % end 289 | -------------------------------------------------------------------------------- /ColorMap/brewermap_view.m: -------------------------------------------------------------------------------- 1 | function [map,scheme] = brewermap_view(N,scheme) 2 | % An interactive figure for ColorBrewer colormap selection. With demo! 3 | % 4 | % (c) 2014 Stephen Cobeldick 5 | % 6 | % View Cynthia Brewer's ColorBrewer colorschemes in a figure. 7 | % 8 | % * Two colorbars give the colorscheme in color and grayscale. 9 | % * A button toggles between 3D-cube and 2D-lineplot of the RGB values. 10 | % * A button toggles an endless cycle through the colorschemes. 11 | % * A button reverses the colormap. 12 | % * 35 buttons select any ColorBrewer colorscheme. 13 | % * Text with the colorscheme's type (Diverging/Qualitative/Sequential) 14 | % * Text with the colorscheme's number of nodes (defining colors). 15 | % 16 | %%% Syntax: 17 | % brewermap_view 18 | % brewermap_view(N) 19 | % brewermap_view(N,scheme) 20 | % brewermap_view([],...) 21 | % brewermap_view({axes/figure handles},...) % see "Adjust External Colormaps" 22 | % [map,scheme] = brewermap_view(...) 23 | % 24 | % Calling the function with an output argument blocks MATLAB execution until 25 | % the figure is deleted: the final colormap and colorscheme are then returned. 26 | % 27 | % See also BREWERMAP CUBEHELIX RGBPLOT COLORMAP COLORMAPEDITOR COLORBAR UICONTROL ADDLISTENER 28 | % 29 | %% Adjust Colormaps of Other Figures or Axes %% 30 | % 31 | %%% Example: 32 | % 33 | % S = load('spine'); 34 | % image(S.X) 35 | % brewermap_view({gca}) 36 | % 37 | % Very useful! Simply provide a cell array of axes or figure handles when 38 | % calling this function, and their colormaps will be updated in real-time: 39 | % note that MATLAB versions <=2010 only support axes handles for this! 40 | % 41 | %% Input and Output Arguments %% 42 | % 43 | %%% Inputs (*=default): 44 | % N = NumericScalar, an integer to define the colormap length. 45 | % = *[], colormap length of one hundred and twenty-eight (128). 46 | % = {axes/figure handles}, their colormaps will be updated by BREWERMAP_VIEW. 47 | % scheme = CharRowVector, a ColorBrewer colorscheme name. 48 | % 49 | %%% Outputs (these block execution until the figure is deleted!): 50 | % map = NumericMatrix, the colormap defined when the figure is closed. 51 | % scheme = CharRowVector, the name of the colorscheme given in . 52 | % 53 | % [map,scheme] = brewermap_view(N,scheme) 54 | 55 | %% Input Wrangling %% 56 | % 57 | persistent H 58 | % 59 | dfn = 128; 60 | xtH = {}; 61 | % Parse colormap size: 62 | if nargin<1 || isnumeric(N)&&isempty(N) 63 | N = dfn; 64 | elseif iscell(N)&&numel(N) 65 | ish = all(1==cellfun('prodofsize',N)&cellfun(@ishghandle,N)); 66 | assert(ish,'Input may be a cell array of scalar axes or figure handles.') 67 | xtH = N; 68 | N = size(colormap(xtH{1}),1); 69 | else 70 | assert(isnumeric(N)&&isscalar(N),'Input must be a scalar numeric.') 71 | assert(isreal(N)&&fix(N)==N&&N>0,'Input must be positive real integer: %g+%gi',N,imag(N)) 72 | N = double(N); 73 | end 74 | % 75 | [mcs,mun,pyt] = brewermap('list'); 76 | % 77 | % Parse colorscheme name: 78 | if nargin<2 79 | scheme = mcs{1+rem(round(now*1e7),numel(mcs))}; 80 | else 81 | assert(ischar(scheme)&&isrow(scheme),'Second input must be a 1xN char.') 82 | end 83 | % Check if a reversed colormap was requested: 84 | isR = strncmp(scheme,'*',1); 85 | scheme = scheme(1+isR:end); 86 | % 87 | %% Create Figure %% 88 | % 89 | % LHS and RHS slider bounds/limits, and slider step sizes: 90 | lbd = 1; 91 | rbd = dfn; 92 | stp = [1,10]; % [minor,major] 93 | % 94 | % Define the 3D cube axis order: 95 | xyz = 'RGB'; 96 | [~,xyz] = ismember(xyz,'RGB'); 97 | % 98 | if isempty(H) || ~ishghandle(H.fig) 99 | % Check brewermap version: 100 | ers = 'The function BREWERMAP returned an unexpected %s.'; 101 | assert(all(35==[numel(mcs),numel(mun),numel(pyt)]),ers,'array size') 102 | tmp = find(any(diff(+char(pyt)),2)); 103 | assert(numel(tmp)==2&&all(tmp==[9;17]),ers,'scheme name sequence') 104 | % 105 | % Create a new figure: 106 | ClBk = struct('bmvChgS',@bmvChgS, 'bmvRevM',@bmvRevM,... 107 | 'bmv2D3D',@bmv2D3D, 'bmvDemo',@bmvDemo, 'bmvSldr',@bmvSldr); 108 | H = bmvPlot(ClBk, xyz, lbd, rbd, stp, mcs); 109 | end 110 | % 111 | set(H.bGrp,'SelectedObject',H.bEig(strcmpi(scheme,mcs))); 112 | set(H.vSld,'Value',max(lbd,min(rbd,N))); 113 | % 114 | bmvUpDt() 115 | % 116 | if nargout 117 | waitfor(H.fig); 118 | else 119 | clear map 120 | end 121 | % 122 | %% Nested Functions %% 123 | % 124 | function bmvUpDt() 125 | % Update all graphics objects in the figure. 126 | % 127 | % Get ColorBrewer colormap and grayscale equivalent: 128 | [map,num,typ] = brewermap(N,[char(42*ones(1,isR)),scheme]); 129 | mag = map*[0.298936;0.587043;0.114021]; 130 | % 131 | % Update colorbar values: 132 | set(H.cbAx, 'YLim', [0,abs(N)+(N==0)]+0.5); 133 | set(H.cbIm(1), 'CData',reshape(map,[],1,3)) 134 | set(H.cbIm(2), 'CData',repmat(mag,[1,1,3])) 135 | % 136 | % Update 2D line / 3D patch values: 137 | if get(H.D2D3, 'Value') % 2D 138 | set(H.ln2D, 'XData',linspace(0,1,abs(N))); 139 | set(H.ln2D, {'YData'},num2cell([map,mag],1).'); 140 | else % 3D 141 | set(H.pt3D,... 142 | 'XData',map(:,xyz(1)),... 143 | 'YData',map(:,xyz(2)),... 144 | 'ZData',map(:,xyz(3)), 'FaceVertexCData',map) 145 | end 146 | % 147 | % Update reverse button: 148 | set(H.bRev, 'Value',isR) 149 | % 150 | % Update warning text: 151 | str = {typ;sprintf('%d Nodes',num)}; 152 | set(H.warn,'String',str); 153 | % 154 | % Update parameter value text: 155 | set(H.vTxt(1), 'String',sprintf('N = %.0f',N)); 156 | % 157 | % Update external axes/figure: 158 | for k = find(cellfun(@ishghandle,xtH)) 159 | colormap(xtH{k},map); 160 | end 161 | % 162 | drawnow() 163 | end 164 | % 165 | function bmv2D3D(h,~) 166 | % Switch between 2D-line and 3D-cube representation. 167 | % 168 | if get(h,'Value') % 2D 169 | set(H.ax3D, 'HitTest','off', 'Visible','off') 170 | set(H.ax2D, 'HitTest','on') 171 | set(H.pt3D, 'Visible','off') 172 | set(H.ln2D, 'Visible','on') 173 | else % 3D 174 | set(H.ax2D, 'HitTest','off') 175 | set(H.ax3D, 'HitTest','on', 'Visible','on') 176 | set(H.ln2D, 'Visible','off') 177 | set(H.pt3D, 'Visible','on') 178 | end 179 | % 180 | bmvUpDt(); 181 | end 182 | % 183 | function bmvChgS(~,e) 184 | % Change the colorscheme. 185 | % 186 | scheme = get(e.NewValue,'String'); 187 | % 188 | bmvUpDt() 189 | end 190 | % 191 | function bmvRevM(h,~) 192 | % Reverse the colormap. 193 | % 194 | isR = get(h,'Value'); 195 | % 196 | bmvUpDt() 197 | end 198 | % 199 | function bmvSldr(~,~) 200 | % Update the slider position. 201 | % 202 | N = round(get(H.vSld,'Value')); 203 | % 204 | bmvUpDt() 205 | end 206 | % 207 | mov = -1; 208 | function bmvDemo(h,~) 209 | % Display all ColorBrewer colorschemes sequentially. 210 | % 211 | cnt = 0; 212 | while ishghandle(h)&&get(h,'Value') 213 | cnt = cnt+1; 214 | % 215 | if cnt==23 216 | cnt = 0; 217 | ids = 1+mod(find(strcmpi(scheme,mcs)),numel(mcs)); 218 | set(H.bGrp,'SelectedObject',H.bEig(ids)); 219 | scheme = mcs{ids}; 220 | end 221 | % 222 | if N<=1 223 | mov = +1; 224 | elseif N>=dfn 225 | mov = -1; 226 | end 227 | N = mov + N; 228 | % 229 | set(H.vSld,'Value',N) 230 | %bmvUpDt(); 231 | % 232 | % Faster/slower: 233 | pause(0.1); 234 | end 235 | % 236 | end 237 | % 238 | end 239 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%brewermap_view 240 | function H = bmvPlot(ClBk, xyz, lbd, rbd, stp, mcs) 241 | % Draw a new figure with RGBplot axes, ColorBar axes, and uicontrol sliders. 242 | % 243 | M = 9; % buttons per column 244 | gap = 0.01; % gaps 245 | bth = 0.04; % demo height 246 | btw = 0.09; % demo width 247 | uih = 0.40; % height of UI control group 248 | cbw = 0.21; % width of both colorbars 249 | axh = 1-uih-2*gap; % axes height 250 | wdt = 1-cbw-2*gap; % axes width 251 | % 252 | H.fig = figure('HandleVisibility','callback', 'Color','white',... 253 | 'IntegerHandle','off', 'NumberTitle','off',... 254 | 'Name','ColorBrewer Interactive ColorScheme Selector',... 255 | 'MenuBar','figure', 'Toolbar','none', 'Tag',mfilename); 256 | % 257 | % Add 2D lineplot: 258 | H.ax2D = axes('Parent',H.fig, 'Position',[gap, uih+gap, wdt, axh],... 259 | 'ColorOrder',[1,0,0; 0,1,0; 0,0,1; 0.6,0.6,0.6], 'HitTest','off',... 260 | 'Visible','off', 'XLim',[0,1], 'YLim',[0,1], 'XTick',[], 'YTick',[]); 261 | H.ln2D = line([0,0,0,0;1,1,1,1],[0,0,0,0;1,1,1,1], 'Parent',H.ax2D, 'Visible','off'); 262 | % 263 | % Add 3D scatterplot: 264 | H.ax3D = axes('Parent',H.fig, 'OuterPosition',[0, uih, wdt+2*gap, 1-uih],... 265 | 'Visible','on', 'XLim',[0,1], 'YLim',[0,1], 'ZLim',[0,1], 'HitTest','on'); 266 | H.pt3D = patch('Parent',H.ax3D, 'XData',[0;1], 'YData',[0;1], 'ZData',[0;1],... 267 | 'Visible','on', 'LineStyle','none', 'FaceColor','none', 'MarkerEdgeColor','none',... 268 | 'Marker','o', 'MarkerFaceColor','flat', 'MarkerSize',10, 'FaceVertexCData',[1,1,0;1,0,1]); 269 | view(H.ax3D,3); 270 | grid(H.ax3D,'on') 271 | lbl = {'Red','Green','Blue'}; 272 | xlabel(H.ax3D,lbl{xyz(1)}) 273 | ylabel(H.ax3D,lbl{xyz(2)}) 274 | zlabel(H.ax3D,lbl{xyz(3)}) 275 | % 276 | % Add warning text: 277 | H.warn = text('Parent',H.ax2D, 'Units','normalized', 'Position',[1,1],... 278 | 'HorizontalAlignment','right', 'VerticalAlignment','top', 'Color','k'); 279 | % 280 | % Add demo button: 281 | H.demo = uicontrol(H.fig, 'Style','togglebutton', 'Units','normalized',... 282 | 'Position',[gap,uih+gap+0*bth,btw,bth], 'String','Demo',... 283 | 'Max',1, 'Min',0, 'Callback',ClBk.bmvDemo); 284 | % Add 2D/3D button: 285 | H.D2D3 = uicontrol(H.fig, 'Style','togglebutton', 'Units','normalized',... 286 | 'Position',[gap,uih+gap+1*bth,btw,bth], 'String','2D / 3D',... 287 | 'Max',1, 'Min',0, 'Callback',ClBk.bmv2D3D); 288 | % Add reverse button: 289 | H.bRev = uicontrol(H.fig, 'Style','togglebutton', 'Units','normalized',... 290 | 'Position',[gap,uih+gap+2*bth,btw,bth], 'String','Reverse',... 291 | 'Max',1, 'Min',0, 'Callback',ClBk.bmvRevM); 292 | % 293 | % Add colorbars: 294 | C(1,1,:) = [1,1,1]; 295 | H.cbAx(1) = axes('Parent',H.fig, 'Visible','off', 'Units','normalized',... 296 | 'Position',[1-cbw/1,gap,cbw/2-gap,1-2*gap], 'YLim',[0.5,1.5],... 297 | 'YDir','reverse', 'HitTest','off'); 298 | H.cbAx(2) = axes('Parent',H.fig, 'Visible','off', 'Units','normalized',... 299 | 'Position',[1-cbw/2,gap,cbw/2-gap,1-2*gap], 'YLim',[0.5,1.5],... 300 | 'YDir','reverse', 'HitTest','off'); 301 | H.cbIm(1) = image('Parent',H.cbAx(1), 'CData',C); 302 | H.cbIm(2) = image('Parent',H.cbAx(2), 'CData',C); 303 | % 304 | % Add parameter slider, listener, and corresponding text: 305 | sv = mean([lbd,rbd],2); 306 | H.vTxt = uicontrol(H.fig,'Style','text', 'Units','normalized',... 307 | 'Position',[gap,uih-bth,btw,bth], 'String','X'); 308 | H.vSld = uicontrol(H.fig,'Style','slider', 'Units','normalized',... 309 | 'Position',[gap,gap,btw,uih-bth], 'Min',lbd(1), 'Max',rbd(1),... 310 | 'SliderStep',stp(1,:)/(rbd(1)-lbd(1)), 'Value',sv(1)); 311 | addlistener(H.vSld, 'Value', 'PostSet',ClBk.bmvSldr); 312 | % 313 | % Add colorscheme button group: 314 | H.bGrp = uibuttongroup('Parent',H.fig, 'BorderType','none', 'Units','normalized',... 315 | 'BackgroundColor','white', 'Position',[2*gap+btw,gap,wdt-btw-gap,uih-gap]); 316 | % Determine button locations: 317 | Z = 1:numel(mcs); 318 | Z = Z+(Z>17); 319 | C = (ceil(Z/M)-1)/4; 320 | R = (M-1-mod(Z-1,M))/M; 321 | % Add colorscheme buttons to group: 322 | for k = numel(mcs):-1:1 323 | H.bEig(k) = uicontrol('Parent',H.bGrp, 'Style','Toggle', 'String',mcs{k},... 324 | 'Unit','normalized', 'Position',[C(k),R(k),1/4,1/M]); 325 | end 326 | set(H.bGrp,'SelectionChangeFcn',ClBk.bmvChgS); 327 | % 328 | drawnow() 329 | % 330 | end 331 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%bmvPlot 332 | % 333 | % Copyright (c) 2017 Stephen Cobeldick 334 | % 335 | % Licensed under the Apache License, Version 2.0 (the "License"); 336 | % you may not use this file except in compliance with the License. 337 | % You may obtain a copy of the License at 338 | % 339 | % http://www.apache.org/licenses/LICENSE-2.0 340 | % 341 | % Unless required by applicable law or agreed to in writing, software 342 | % distributed under the License is distributed on an "AS IS" BASIS, 343 | % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 344 | % See the License for the specific language governing permissions and limitations under the License. 345 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%license -------------------------------------------------------------------------------- /ColorMap/brewermap.m: -------------------------------------------------------------------------------- 1 | function [map,num,typ] = brewermap(N,scheme) 2 | % The complete selection of ColorBrewer colorschemes (RGB colormaps). 3 | % 4 | % (c) 2014 Stephen Cobeldick 5 | % 6 | % Returns any RGB colormap from the ColorBrewer colorschemes, especially 7 | % intended for mapping and plots with attractive, distinguishable colors. 8 | % 9 | %%% Syntax (basic): 10 | % map = brewermap(N,scheme); % Select colormap length, select any colorscheme. 11 | % brewermap('plot') % View a figure showing all ColorBrewer colorschemes. 12 | % schemes = brewermap('list')% Return a list of all ColorBrewer colorschemes. 13 | % [map,num,typ] = brewermap(...); % The current colorscheme's number of nodes and type. 14 | % 15 | %%% Syntax (preselect colorscheme): 16 | % old = brewermap(scheme); % Preselect any colorscheme, return the previous scheme. 17 | % map = brewermap(N); % Use preselected scheme, select colormap length. 18 | % map = brewermap; % Use preselected scheme, length same as current figure's colormap. 19 | % 20 | % See also CUBEHELIX RGBPLOT3 RGBPLOT COLORMAP COLORBAR PLOT PLOT3 SURF IMAGE AXES SET JET LBMAP PARULA 21 | % 22 | %% Color Schemes %% 23 | % 24 | % This product includes color specifications and designs developed by Cynthia Brewer. 25 | % See the ColorBrewer website for further information about each colorscheme, 26 | % colour-blind suitability, licensing, and citations: http://colorbrewer.org/ 27 | % 28 | % To reverse the colormap sequence simply prefix the string token with '*'. 29 | % 30 | % Each colorscheme is defined by a set of hand-picked RGB values (nodes). 31 | % If is greater than the requested colorscheme's number of nodes then: 32 | % * Sequential and Diverging schemes are interpolated to give a larger 33 | % colormap. The interpolation is performed in the Lab colorspace. 34 | % * Qualitative schemes are repeated to give a larger colormap. 35 | % Else: 36 | % * Exact values from the ColorBrewer sequences are returned for all colorschemes. 37 | % 38 | %%% Diverging 39 | % 40 | % Scheme|'BrBG'|'PRGn'|'PiYG'|'PuOr'|'RdBu'|'RdGy'|'RdYlBu'|'RdYlGn'|'Spectral'| 41 | % ------|------|------|------|------|------|------|--------|--------|----------| 42 | % Nodes | 11 | 11 | 11 | 11 | 11 | 11 | 11 | 11 | 11 | 43 | % 44 | %%% Qualitative 45 | % 46 | % Scheme|'Accent'|'Dark2'|'Paired'|'Pastel1'|'Pastel2'|'Set1'|'Set2'|'Set3'| 47 | % ------|--------|-------|--------|---------|---------|------|------|------| 48 | % Nodes | 8 | 8 | 12 | 9 | 8 | 9 | 8 | 12 | 49 | % 50 | %%% Sequential 51 | % 52 | % Scheme|'Blues'|'BuGn'|'BuPu'|'GnBu'|'Greens'|'Greys'|'OrRd'|'Oranges'|'PuBu'| 53 | % ------|-------|------|------|------|--------|-------|------|---------|------| 54 | % Nodes | 9 | 9 | 9 | 9 | 9 | 9 | 9 | 9 | 9 | 55 | % 56 | % Scheme|'PuBuGn'|'PuRd'|'Purples'|'RdPu'|'Reds'|'YlGn'|'YlGnBu'|'YlOrBr'|'YlOrRd'| 57 | % ------|--------|------|---------|------|------|------|--------|--------|--------| 58 | % Nodes | 9 | 9 | 9 | 9 | 9 | 9 | 9 | 9 | 9 | 59 | % 60 | %% Examples %% 61 | % 62 | %%% Plot a scheme's RGB values: 63 | % rgbplot(brewermap(9,'Blues')) % standard 64 | % rgbplot(brewermap(9,'*Blues')) % reversed 65 | % 66 | %%% View information about a colorscheme: 67 | % [~,num,typ] = brewermap(0,'Paired') 68 | % num = 12 69 | % typ = 'Qualitative' 70 | % 71 | %%% Multi-line plot using matrices: 72 | % N = 6; 73 | % axes('ColorOrder',brewermap(N,'Pastel2'),'NextPlot','replacechildren') 74 | % X = linspace(0,pi*3,1000); 75 | % Y = bsxfun(@(x,n)n*sin(x+2*n*pi/N), X(:), 1:N); 76 | % plot(X,Y, 'linewidth',4) 77 | % 78 | %%% Multi-line plot in a loop: 79 | % N = 6; 80 | % set(0,'DefaultAxesColorOrder',brewermap(N,'Accent')) 81 | % X = linspace(0,pi*3,1000); 82 | % Y = bsxfun(@(x,n)n*sin(x+2*n*pi/N), X(:), 1:N); 83 | % for n = 1:N 84 | % plot(X(:),Y(:,n), 'linewidth',4); 85 | % hold all 86 | % end 87 | % 88 | %%% New colors for the COLORMAP example: 89 | % load spine 90 | % image(X) 91 | % colormap(brewermap([],'YlGnBu')) 92 | % 93 | %%% New colors for the SURF example: 94 | % [X,Y,Z] = peaks(30); 95 | % surfc(X,Y,Z) 96 | % colormap(brewermap([],'RdYlGn')) 97 | % axis([-3,3,-3,3,-10,5]) 98 | % 99 | %%% New colors for the CONTOURCMAP example: 100 | % brewermap('PuOr'); % preselect the colorscheme. 101 | % load topo 102 | % load coast 103 | % figure 104 | % worldmap(topo, topolegend) 105 | % contourfm(topo, topolegend); 106 | % contourcmap('brewermap', 'Colorbar','on', 'Location','horizontal',... 107 | % 'TitleString','Contour Intervals in Meters'); 108 | % plotm(lat, long, 'k') 109 | % 110 | %% Input and Output Arguments %% 111 | % 112 | %%% Inputs (*=default): 113 | % N = NumericScalar, N>=0, an integer to define the colormap length. 114 | % = *[], use the length of the current figure's colormap (see COLORMAP). 115 | % = CharRowVector, to preselect this ColorBrewer colorscheme for later use. 116 | % = 'plot', create a figure showing all of the ColorBrewer colorschemes. 117 | % = 'list', return a cell array of strings listing all ColorBrewer colorschemes. 118 | % scheme = CharRowVector, a ColorBrewer colorscheme name. 119 | % = *none, use the preselected colorscheme (must be set previously!). 120 | % 121 | %%% Outputs: 122 | % map = NumericMatrix, size Nx3, a colormap of RGB values between 0 and 1. 123 | % num = NumericScalar, the number of nodes defining the ColorBrewer colorscheme. 124 | % typ = CharRowVector, the colorscheme type: 'Diverging'/'Qualitative'/'Sequential'. 125 | % OR 126 | % schemes = CellOfCharRowVectors, a list of every ColorBrewer colorscheme. 127 | % 128 | % [map,num,typ] = brewermap(*N,*scheme) 129 | % OR 130 | % schemes = brewermap('list') 131 | 132 | %% Input Wrangling %% 133 | % 134 | persistent tok isr 135 | % 136 | str = 'A colorscheme must be preselected before calling without a colorscheme name.'; 137 | % 138 | % The order of names in : case-insensitive sort by type and then by name: 139 | vec = {'BrBG';'PiYG';'PRGn';'PuOr';'RdBu';'RdGy';'RdYlBu';'RdYlGn';'Spectral';'Accent';'Dark2';'Paired';'Pastel1';'Pastel2';'Set1';'Set2';'Set3';'Blues';'BuGn';'BuPu';'GnBu';'Greens';'Greys';'OrRd';'Oranges';'PuBu';'PuBuGn';'PuRd';'Purples';'RdPu';'Reds';'YlGn';'YlGnBu';'YlOrBr';'YlOrRd'}; 140 | % 141 | if nargin==0 % Current figure's colormap length and the preselected colorscheme. 142 | assert(~isempty(tok),str) 143 | [map,num,typ] = bmSample([],isr,tok); 144 | elseif nargin==2 % Input colormap length and colorscheme. 145 | assert(isnumeric(N),'The first argument must be a scalar numeric, or empty.') 146 | assert(ischar(scheme)&&isrow(scheme),'The second argument must be a 1xN char.') 147 | tmp = strncmp('*',scheme,1); 148 | [map,num,typ] = bmSample(N,tmp,bmMatch(vec,scheme(1+tmp:end))); 149 | elseif isnumeric(N) % Input colormap length and the preselected colorscheme. 150 | assert(~isempty(tok),str) 151 | [map,num,typ] = bmSample(N,isr,tok); 152 | else% String 153 | assert(ischar(N)&&isrow(N),'The first argument must be a 1xN char or scalar numeric.') 154 | switch lower(N) 155 | case 'plot' % Plot all colorschemes in a figure. 156 | bmPlotFig(vec) 157 | case 'list' % Return a list of all colorschemes. 158 | [num,typ] = cellfun(@bmSelect,vec,'UniformOutput',false); 159 | num = cat(1,num{:}); 160 | map = vec; 161 | otherwise % Store the preselected colorscheme token. 162 | map = tok; 163 | tmp = strncmp('*',N,1); 164 | tok = bmMatch(vec,N(1+tmp:end)); 165 | [num,typ] = bmSelect(tok); 166 | isr = tmp; % only update |isr| when name is okay. 167 | end 168 | end 169 | % 170 | end 171 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%brewermap 172 | function tok = bmMatch(vec,str) 173 | idx = strcmpi(vec,str); 174 | assert(any(idx),'Colorscheme "%s" is not supported. Check the token tables.',str) 175 | tok = vec{idx}; 176 | end 177 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%bmMatch 178 | function [map,num,typ] = bmSample(N,isr,tok) 179 | % Pick a colorscheme, downsample/interpolate to the requested colormap length. 180 | % 181 | if isempty(N) 182 | N = size(get(gcf,'colormap'),1); 183 | else 184 | assert(isscalar(N)&&isreal(N),'First argument must be a real numeric scalar, or empty.') 185 | end 186 | % 187 | % obtain nodes: 188 | [num,typ,rgb] = bmSelect(tok); 189 | % downsample: 190 | [idx,itp] = bmIndex(N,num,typ,isr); 191 | map = rgb(idx,:); 192 | % interpolate: 193 | if itp 194 | M = [... 195 | +3.2406255,-1.5372080,-0.4986286;... 196 | -0.9689307,+1.8757561,+0.0415175;... 197 | +0.0557101,-0.2040211,+1.0569959]; 198 | wpt = [0.95047,1,1.08883]; % D65 199 | % 200 | map = bmRGB2Lab(map,M,wpt); % optional 201 | % 202 | % Extrapolate a small amount at both ends: 203 | %vec = linspace(0,num+1,N+2); 204 | %map = interp1(1:num,map,vec(2:end-1),'linear','extrap'); 205 | % Interpolation completely within ends: 206 | map = interp1(1:num,map,linspace(1,num,N),'spline'); 207 | % 208 | map = bmLab2RGB(map,M,wpt); % optional 209 | end 210 | % 211 | end 212 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%bmSample 213 | function rgb = bmGammaCor(rgb) 214 | % Gamma correction of sRGB data. 215 | idx = rgb <= 0.0031308; 216 | rgb(idx) = 12.92 * rgb(idx); 217 | rgb(~idx) = real(1.055 * rgb(~idx).^(1/2.4) - 0.055); 218 | end 219 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%bmGammaCor 220 | function rgb = bmGammaInv(rgb) 221 | % Inverse gamma correction of sRGB data. 222 | idx = rgb <= 0.04045; 223 | rgb(idx) = rgb(idx) / 12.92; 224 | rgb(~idx) = real(((rgb(~idx) + 0.055) / 1.055).^2.4); 225 | end 226 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%bmGammaInv 227 | function lab = bmRGB2Lab(rgb,M,wpt) % Nx3 <- Nx3 228 | % Convert a matrix of sRGB values to Lab. 229 | % 230 | %applycform(rgb,makecform('srgb2lab','AdaptedWhitePoint',wpt)) 231 | % 232 | % RGB2XYZ: 233 | xyz = bmGammaInv(rgb) / M.'; 234 | % Remember to include my license when copying my implementation. 235 | % XYZ2Lab: 236 | xyz = bsxfun(@rdivide,xyz,wpt); 237 | idx = xyz>(6/29)^3; 238 | F = idx.*(xyz.^(1/3)) + ~idx.*(xyz*(29/6)^2/3+4/29); 239 | lab(:,2:3) = bsxfun(@times,[500,200],F(:,1:2)-F(:,2:3)); 240 | lab(:,1) = 116*F(:,2) - 16; 241 | % 242 | end 243 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%bmRGB2Lab 244 | function rgb = bmLab2RGB(lab,M,wpt) % Nx3 <- Nx3 245 | % Convert a matrix of Lab values to sRGB. 246 | % 247 | %applycform(lab,makecform('lab2srgb','AdaptedWhitePoint',wpt)) 248 | % 249 | % Lab2XYZ 250 | tmp = bsxfun(@rdivide,lab(:,[2,1,3]),[500,Inf,-200]); 251 | tmp = bsxfun(@plus,tmp,(lab(:,1)+16)/116); 252 | idx = tmp>(6/29); 253 | tmp = idx.*(tmp.^3) + ~idx.*(3*(6/29)^2*(tmp-4/29)); 254 | xyz = bsxfun(@times,tmp,wpt); 255 | % Remember to include my license when copying my implementation. 256 | % XYZ2RGB 257 | rgb = max(0,min(1, bmGammaCor(xyz * M.'))); 258 | % 259 | end 260 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%cbLab2RGB 261 | function bmPlotFig(seq) 262 | % Creates a figure showing all of the ColorBrewer colorschemes. 263 | % 264 | persistent cbh axh 265 | % 266 | xmx = max(cellfun(@bmSelect,seq)); 267 | ymx = numel(seq); 268 | % 269 | if ishghandle(cbh) 270 | figure(cbh); 271 | delete(axh); 272 | else 273 | cbh = figure('HandleVisibility','callback', 'IntegerHandle','off',... 274 | 'NumberTitle','off', 'Name',[mfilename,' Plot'],'Color','white',... 275 | 'MenuBar','figure', 'Toolbar','none', 'Tag',mfilename); 276 | set(cbh,'Units','pixels') 277 | pos = get(cbh,'Position'); 278 | pos(1:2) = pos(1:2) - 123; 279 | pos(3:4) = max(pos(3:4),[842,532]); 280 | set(cbh,'Position',pos) 281 | end 282 | % 283 | axh = axes('Parent',cbh, 'Color','none',... 284 | 'XTick',0:xmx, 'YTick',0.5:ymx, 'YTickLabel',seq, 'YDir','reverse'); 285 | title(axh,['ColorBrewer Color Schemes (',mfilename,'.m)'], 'Interpreter','none') 286 | xlabel(axh,'Scheme Nodes') 287 | ylabel(axh,'Scheme Name') 288 | axf = get(axh,'FontName'); 289 | % 290 | for y = 1:ymx 291 | [num,typ,rgb] = bmSelect(seq{y}); 292 | map = rgb(bmIndex(num,num,typ,false),:); % downsample 293 | for x = 1:num 294 | patch([x-1,x-1,x,x],[y-1,y,y,y-1],1, 'FaceColor',map(x,:), 'Parent',axh) 295 | end 296 | text(xmx+0.1,y-0.5,typ, 'Parent',axh, 'FontName',axf) 297 | end 298 | % 299 | drawnow() 300 | % 301 | end 302 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%bmPlotFig 303 | function [idx,itp] = bmIndex(N,num,typ,isr) 304 | % Ensure exactly the same colors as in the online ColorBrewer colorschemes. 305 | % 306 | itp = N>num; 307 | switch typ 308 | case 'Qualitative' 309 | itp = false; 310 | idx = 1+mod(0:N-1,num); 311 | case 'Diverging' 312 | switch N 313 | case 1 % extrapolated 314 | idx = 8; 315 | case 2 % extrapolated 316 | idx = [4,12]; 317 | case 3 318 | idx = [5,8,11]; 319 | case 4 320 | idx = [3,6,10,13]; 321 | case 5 322 | idx = [3,6,8,10,13]; 323 | case 6 324 | idx = [2,5,7,9,11,14]; 325 | case 7 326 | idx = [2,5,7,8,9,11,14]; 327 | case 8 328 | idx = [2,4,6,7,9,10,12,14]; 329 | case 9 330 | idx = [2,4,6,7,8,9,10,12,14]; 331 | case 10 332 | idx = [1,2,4,6,7,9,10,12,14,15]; 333 | otherwise 334 | idx = [1,2,4,6,7,8,9,10,12,14,15]; 335 | end 336 | case 'Sequential' 337 | switch N 338 | case 1 % extrapolated 339 | idx = 6; 340 | case 2 % extrapolated 341 | idx = [4,8]; 342 | case 3 343 | idx = [3,6,9]; 344 | case 4 345 | idx = [2,5,7,10]; 346 | case 5 347 | idx = [2,5,7,9,11]; 348 | case 6 349 | idx = [2,4,6,7,9,11]; 350 | case 7 351 | idx = [2,4,6,7,8,10,12]; 352 | case 8 353 | idx = [1,3,4,6,7,8,10,12]; 354 | otherwise 355 | idx = [1,3,4,6,7,8,10,11,13]; 356 | end 357 | otherwise 358 | error('The colorscheme type "%s" is not recognized',typ) 359 | end 360 | % 361 | if isr 362 | idx = idx(end:-1:1); 363 | end 364 | % 365 | end 366 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%bmIndex 367 | function [num,typ,rgb] = bmSelect(tok) 368 | % Return the length, type and RGB values of any colorscheme. 369 | % 370 | switch tok % ColorName 371 | case 'BrBG' 372 | rgb = [84,48,5;140,81,10;166,97,26;191,129,45;216,179,101;223,194,125;246,232,195;245,245,245;199,234,229;128,205,193;90,180,172;53,151,143;1,133,113;1,102,94;0,60,48]; 373 | typ = 'Diverging'; 374 | case 'PiYG' 375 | rgb = [142,1,82;197,27,125;208,28,139;222,119,174;233,163,201;241,182,218;253,224,239;247,247,247;230,245,208;184,225,134;161,215,106;127,188,65;77,172,38;77,146,33;39,100,25]; 376 | typ = 'Diverging'; 377 | case 'PRGn' 378 | rgb = [64,0,75;118,42,131;123,50,148;153,112,171;175,141,195;194,165,207;231,212,232;247,247,247;217,240,211;166,219,160;127,191,123;90,174,97;0,136,55;27,120,55;0,68,27]; 379 | typ = 'Diverging'; 380 | case 'PuOr' 381 | rgb = [127,59,8;179,88,6;230,97,1;224,130,20;241,163,64;253,184,99;254,224,182;247,247,247;216,218,235;178,171,210;153,142,195;128,115,172;94,60,153;84,39,136;45,0,75]; 382 | typ = 'Diverging'; 383 | case 'RdBu' 384 | rgb = [103,0,31;178,24,43;202,0,32;214,96,77;239,138,98;244,165,130;253,219,199;247,247,247;209,229,240;146,197,222;103,169,207;67,147,195;5,113,176;33,102,172;5,48,97]; 385 | typ = 'Diverging'; 386 | case 'RdGy' 387 | rgb = [103,0,31;178,24,43;202,0,32;214,96,77;239,138,98;244,165,130;253,219,199;255,255,255;224,224,224;186,186,186;153,153,153;135,135,135;64,64,64;77,77,77;26,26,26]; 388 | typ = 'Diverging'; 389 | case 'RdYlBu' 390 | rgb = [165,0,38;215,48,39;215,25,28;244,109,67;252,141,89;253,174,97;254,224,144;255,255,191;224,243,248;171,217,233;145,191,219;116,173,209;44,123,182;69,117,180;49,54,149]; 391 | typ = 'Diverging'; 392 | case 'RdYlGn' 393 | rgb = [165,0,38;215,48,39;215,25,28;244,109,67;252,141,89;253,174,97;254,224,139;255,255,191;217,239,139;166,217,106;145,207,96;102,189,99;26,150,65;26,152,80;0,104,55]; 394 | typ = 'Diverging'; 395 | case 'Spectral' 396 | rgb = [158,1,66;213,62,79;215,25,28;244,109,67;252,141,89;253,174,97;254,224,139;255,255,191;230,245,152;171,221,164;153,213,148;102,194,165;43,131,186;50,136,189;94,79,162]; 397 | typ = 'Diverging'; 398 | case 'Accent' 399 | rgb = [127,201,127;190,174,212;253,192,134;255,255,153;56,108,176;240,2,127;191,91,23;102,102,102]; 400 | typ = 'Qualitative'; 401 | case 'Dark2' 402 | rgb = [27,158,119;217,95,2;117,112,179;231,41,138;102,166,30;230,171,2;166,118,29;102,102,102]; 403 | typ = 'Qualitative'; 404 | case 'Paired' 405 | rgb = [166,206,227;31,120,180;178,223,138;51,160,44;251,154,153;227,26,28;253,191,111;255,127,0;202,178,214;106,61,154;255,255,153;177,89,40]; 406 | typ = 'Qualitative'; 407 | case 'Pastel1' 408 | rgb = [251,180,174;179,205,227;204,235,197;222,203,228;254,217,166;255,255,204;229,216,189;253,218,236;242,242,242]; 409 | typ = 'Qualitative'; 410 | case 'Pastel2' 411 | rgb = [179,226,205;253,205,172;203,213,232;244,202,228;230,245,201;255,242,174;241,226,204;204,204,204]; 412 | typ = 'Qualitative'; 413 | case 'Set1' 414 | rgb = [228,26,28;55,126,184;77,175,74;152,78,163;255,127,0;255,255,51;166,86,40;247,129,191;153,153,153]; 415 | typ = 'Qualitative'; 416 | case 'Set2' 417 | rgb = [102,194,165;252,141,98;141,160,203;231,138,195;166,216,84;255,217,47;229,196,148;179,179,179]; 418 | typ = 'Qualitative'; 419 | case 'Set3' 420 | rgb = [141,211,199;255,255,179;190,186,218;251,128,114;128,177,211;253,180,98;179,222,105;252,205,229;217,217,217;188,128,189;204,235,197;255,237,111]; 421 | typ = 'Qualitative'; 422 | case 'Blues' 423 | rgb = [247,251,255;239,243,255;222,235,247;198,219,239;189,215,231;158,202,225;107,174,214;66,146,198;49,130,189;33,113,181;8,81,156;8,69,148;8,48,107]; 424 | typ = 'Sequential'; 425 | case 'BuGn' 426 | rgb = [247,252,253;237,248,251;229,245,249;204,236,230;178,226,226;153,216,201;102,194,164;65,174,118;44,162,95;35,139,69;0,109,44;0,88,36;0,68,27]; 427 | typ = 'Sequential'; 428 | case 'BuPu' 429 | rgb = [247,252,253;237,248,251;224,236,244;191,211,230;179,205,227;158,188,218;140,150,198;140,107,177;136,86,167;136,65,157;129,15,124;110,1,107;77,0,75]; 430 | typ = 'Sequential'; 431 | case 'GnBu' 432 | rgb = [247,252,240;240,249,232;224,243,219;204,235,197;186,228,188;168,221,181;123,204,196;78,179,211;67,162,202;43,140,190;8,104,172;8,88,158;8,64,129]; 433 | typ = 'Sequential'; 434 | case 'Greens' 435 | rgb = [247,252,245;237,248,233;229,245,224;199,233,192;186,228,179;161,217,155;116,196,118;65,171,93;49,163,84;35,139,69;0,109,44;0,90,50;0,68,27]; 436 | typ = 'Sequential'; 437 | case 'Greys' 438 | rgb = [255,255,255;247,247,247;240,240,240;217,217,217;204,204,204;189,189,189;150,150,150;115,115,115;99,99,99;82,82,82;37,37,37;37,37,37;0,0,0]; 439 | typ = 'Sequential'; 440 | case 'OrRd' 441 | rgb = [255,247,236;254,240,217;254,232,200;253,212,158;253,204,138;253,187,132;252,141,89;239,101,72;227,74,51;215,48,31;179,0,0;153,0,0;127,0,0]; 442 | typ = 'Sequential'; 443 | case 'Oranges' 444 | rgb = [255,245,235;254,237,222;254,230,206;253,208,162;253,190,133;253,174,107;253,141,60;241,105,19;230,85,13;217,72,1;166,54,3;140,45,4;127,39,4]; 445 | typ = 'Sequential'; 446 | case 'PuBu' 447 | rgb = [255,247,251;241,238,246;236,231,242;208,209,230;189,201,225;166,189,219;116,169,207;54,144,192;43,140,190;5,112,176;4,90,141;3,78,123;2,56,88]; 448 | typ = 'Sequential'; 449 | case 'PuBuGn' 450 | rgb = [255,247,251;246,239,247;236,226,240;208,209,230;189,201,225;166,189,219;103,169,207;54,144,192;28,144,153;2,129,138;1,108,89;1,100,80;1,70,54]; 451 | typ = 'Sequential'; 452 | case 'PuRd' 453 | rgb = [247,244,249;241,238,246;231,225,239;212,185,218;215,181,216;201,148,199;223,101,176;231,41,138;221,28,119;206,18,86;152,0,67;145,0,63;103,0,31]; 454 | typ = 'Sequential'; 455 | case 'Purples' 456 | rgb = [252,251,253;242,240,247;239,237,245;218,218,235;203,201,226;188,189,220;158,154,200;128,125,186;117,107,177;106,81,163;84,39,143;74,20,134;63,0,125]; 457 | typ = 'Sequential'; 458 | case 'RdPu' 459 | rgb = [255,247,243;254,235,226;253,224,221;252,197,192;251,180,185;250,159,181;247,104,161;221,52,151;197,27,138;174,1,126;122,1,119;122,1,119;73,0,106]; 460 | typ = 'Sequential'; 461 | case 'Reds' 462 | rgb = [255,245,240;254,229,217;254,224,210;252,187,161;252,174,145;252,146,114;251,106,74;239,59,44;222,45,38;203,24,29;165,15,21;153,0,13;103,0,13]; 463 | typ = 'Sequential'; 464 | case 'YlGn' 465 | rgb = [255,255,229;255,255,204;247,252,185;217,240,163;194,230,153;173,221,142;120,198,121;65,171,93;49,163,84;35,132,67;0,104,55;0,90,50;0,69,41]; 466 | typ = 'Sequential'; 467 | case 'YlGnBu' 468 | rgb = [255,255,217;255,255,204;237,248,177;199,233,180;161,218,180;127,205,187;65,182,196;29,145,192;44,127,184;34,94,168;37,52,148;12,44,132;8,29,88]; 469 | typ = 'Sequential'; 470 | case 'YlOrBr' 471 | rgb = [255,255,229;255,255,212;255,247,188;254,227,145;254,217,142;254,196,79;254,153,41;236,112,20;217,95,14;204,76,2;153,52,4;140,45,4;102,37,6]; 472 | typ = 'Sequential'; 473 | case 'YlOrRd' 474 | rgb = [255,255,204;255,255,178;255,237,160;254,217,118;254,204,92;254,178,76;253,141,60;252,78,42;240,59,32;227,26,28;189,0,38;177,0,38;128,0,38]; 475 | typ = 'Sequential'; 476 | otherwise 477 | error('Colorscheme "%s" is not supported. Check the token tables.',tok) 478 | end 479 | % 480 | rgb = rgb./255; 481 | % 482 | switch typ 483 | case 'Diverging' 484 | num = 11; 485 | case 'Qualitative' 486 | num = size(rgb,1); 487 | case 'Sequential' 488 | num = 9; 489 | otherwise 490 | error('The colorscheme type "%s" is not recognized',typ) 491 | end 492 | % 493 | end 494 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%bmSelect 495 | % Code and Implementation: 496 | % Copyright (c) 2017 Stephen Cobeldick 497 | % Color Values Only: 498 | % Copyright (c) 2002 Cynthia Brewer, Mark Harrower, and The Pennsylvania State University. 499 | % 500 | % Licensed under the Apache License, Version 2.0 (the "License"); 501 | % you may not use this file except in compliance with the License. 502 | % You may obtain a copy of the License at 503 | % 504 | % http://www.apache.org/licenses/LICENSE-2.0 505 | % 506 | % Unless required by applicable law or agreed to in writing, software 507 | % distributed under the License is distributed on an "AS IS" BASIS, 508 | % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 509 | % See the License for the specific language governing permissions and limitations under the License. 510 | % 511 | % Redistribution and use in source and binary forms, with or without 512 | % modification, are permitted provided that the following conditions are met: 513 | % 514 | % 1. Redistributions as source code must retain the above copyright notice, this 515 | % list of conditions and the following disclaimer. 516 | % 517 | % 2. The end-user documentation included with the redistribution, if any, must 518 | % include the following acknowledgment: "This product includes color 519 | % specifications and designs developed by Cynthia Brewer 520 | % (http://colorbrewer.org/)." Alternately, this acknowledgment may appear in the 521 | % software itself, if and wherever such third-party acknowledgments normally appear. 522 | % 523 | % 4. The name "ColorBrewer" must not be used to endorse or promote products 524 | % derived from this software without prior written permission. For written 525 | % permission, please contact Cynthia Brewer at cbrewer@psu.edu. 526 | % 527 | % 5. Products derived from this software may not be called "ColorBrewer", nor 528 | % may "ColorBrewer" appear in their name, without prior written permission of Cynthia Brewer. 529 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%license --------------------------------------------------------------------------------