├── GRSC ├── EProjSimplex_new.m ├── ERS │ ├── Entropy Rate Superpixel Segmentation │ │ ├── 148089.jpg │ │ ├── 242078.jpg │ │ ├── ERS │ │ │ ├── Edge.h │ │ │ ├── Image.h │ │ │ ├── ImageIO.h │ │ │ ├── MERCCInput.cpp │ │ │ ├── MERCClustering.h │ │ │ ├── MERCDisjointSet.cpp │ │ │ ├── MERCDisjointSet.h │ │ │ ├── MERCEdge.h │ │ │ ├── MERCFunctions.cpp │ │ │ ├── MERCFunctions.h │ │ │ ├── MERCInput.h │ │ │ ├── MERCInputImage.h │ │ │ ├── MERCLazyGreedy.cpp │ │ │ ├── MERCLazyGreedy.h │ │ │ ├── MERCOutput.cpp │ │ │ ├── MERCOutput.h │ │ │ ├── MERCOutputImage.h │ │ │ ├── MHeap.h │ │ │ ├── MList.h │ │ │ ├── MMFunctions.h │ │ │ ├── MSubmodularHeap.h │ │ │ └── mex_ers.cpp │ │ ├── README.txt │ │ ├── demo.fig │ │ ├── demo.m │ │ ├── make.m │ │ ├── mex_ers.mexw64 │ │ ├── random_color.m │ │ └── seg2bmap.m │ └── common │ │ ├── Edge_ratio3.m │ │ ├── class2label.m │ │ ├── confusion_matrix_wei.m │ │ ├── cubseg.m │ │ ├── elm_kernel.m │ │ ├── getlabel.m │ │ ├── label2class.m │ │ ├── label2color2.m │ │ ├── label2noisylabel.m │ │ ├── label_fusion.m │ │ ├── pca.m │ │ ├── randlabelpropagation.m │ │ ├── samplesdivide.m │ │ ├── scaleForSVM.m │ │ └── supSimALL.m ├── Entrop.m ├── EuDist2.m ├── GRSC.m ├── GRSC_main.m ├── InitializeSIGs.m ├── L2_1.m ├── L2_distance_1.m ├── LP.m ├── PridictLabel.m ├── SelectBandFromClusRes.m ├── SpectralClustering.m ├── cal_OA │ ├── KNN_Classifier │ │ └── KNN_Classifier.m │ ├── KSRC_Classifier │ │ ├── KSRC_Classifier.m │ │ ├── RBF.m │ │ ├── README.md │ │ ├── SpRegKL1.m │ │ ├── class_eval.m │ │ ├── class_ker_pred.m │ │ ├── ker_lwm.m │ │ ├── ker_mm.m │ │ ├── line_dat.m │ │ ├── load_data.m │ │ ├── load_train_test.m │ │ ├── mex_pk_lwm.cpp │ │ ├── mex_pk_lwm.mexw64 │ │ ├── mex_pk_mm.cpp │ │ ├── mex_pk_mm.mexw64 │ │ ├── reshape3d_2d.m │ │ ├── set_train_test.m │ │ └── train_test_random_new.m │ ├── LDA_Classifier │ │ └── LDA_Classifier.m │ ├── SVM_Classifier │ │ └── SVM_Classifier.m │ ├── randdivide.m │ ├── test_bs_accu.m │ └── train_test_random_new.m ├── clu_ncut.m ├── constructW_PKN.m ├── datasets │ ├── Indian_pines.mat │ └── Indian_pines_gt.mat ├── eig1.m ├── get_data.m ├── mySVD.m ├── predict.m └── run.m └── README.md /GRSC/EProjSimplex_new.m: -------------------------------------------------------------------------------- 1 | function [x ft] = EProjSimplex_new(v, k) 2 | 3 | % 4 | %% Problem 5 | % 6 | % min 1/2 || x - v||^2 7 | % s.t. x>=0, 1'x=1 8 | % 9 | 10 | if nargin < 2 11 | k = 1; 12 | end; 13 | 14 | ft=1; 15 | n = length(v); 16 | 17 | v0 = v-mean(v) + k/n; 18 | %vmax = max(v0); 19 | vmin = min(v0); 20 | if vmin < 0 21 | f = 1; 22 | lambda_m = 0; 23 | while abs(f) > 10^-10 24 | v1 = v0 - lambda_m; 25 | posidx = v1>0; 26 | npos = sum(posidx); 27 | g = -npos; 28 | f = sum(v1(posidx)) - k; 29 | lambda_m = lambda_m - f/g; 30 | ft=ft+1; 31 | if ft > 100 32 | x = max(v1,0); 33 | break; 34 | end; 35 | end; 36 | x = max(v1,0); 37 | 38 | else 39 | x = v0; 40 | end; -------------------------------------------------------------------------------- /GRSC/ERS/Entropy Rate Superpixel Segmentation/148089.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WangJun2023/GRSC/714a19f3e37e69ad0409a9ad62c04bd70cda425f/GRSC/ERS/Entropy Rate Superpixel Segmentation/148089.jpg -------------------------------------------------------------------------------- /GRSC/ERS/Entropy Rate Superpixel Segmentation/242078.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WangJun2023/GRSC/714a19f3e37e69ad0409a9ad62c04bd70cda425f/GRSC/ERS/Entropy Rate Superpixel Segmentation/242078.jpg -------------------------------------------------------------------------------- /GRSC/ERS/Entropy Rate Superpixel Segmentation/ERS/Edge.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2011, Ming-Yu Liu 3 | 4 | All Rights Reserved 5 | 6 | Permission to use, copy, modify, and distribute this software and 7 | its documentation for any non-commercial purpose is hereby granted 8 | without fee, provided that the above copyright notice appear in 9 | all copies and that both that copyright notice and this permission 10 | notice appear in supporting documentation, and that the name of 11 | the author not be used in advertising or publicity pertaining to 12 | distribution of the software without specific, written prior 13 | permission. 14 | 15 | THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, 16 | INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 17 | ANY PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 18 | ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 19 | WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN 20 | AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING 21 | OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 22 | */ 23 | #ifndef _edge_h_ 24 | #define _edge_h_ 25 | 26 | class Edge 27 | { 28 | public: 29 | int a_; 30 | int b_; 31 | double w_; 32 | double gain_; 33 | inline Edge &operator=(const Edge &rhs); 34 | inline bool operator==(const Edge &other) const; 35 | inline bool operator!=(const Edge &other) const; 36 | inline bool operator>=(const Edge &other) const; 37 | inline bool operator<=(const Edge &other) const; 38 | inline bool operator>(const Edge &other) const; 39 | inline bool operator<(const Edge &other) const; 40 | }; 41 | #endif 42 | 43 | Edge &Edge::operator=(const Edge &rhs) 44 | { 45 | a_ = rhs.a_; 46 | b_ = rhs.b_; 47 | w_ = rhs.w_; 48 | gain_ = rhs.gain_; 49 | return *this; 50 | } 51 | 52 | bool Edge::operator==(const Edge &other) const 53 | { 54 | return w_ == other.w_; 55 | } 56 | 57 | bool Edge::operator!=(const Edge &other) const 58 | { 59 | return w_ != other.w_; 60 | } 61 | 62 | bool Edge::operator>=(const Edge &other) const 63 | { 64 | return w_ >= other.w_; 65 | } 66 | 67 | bool Edge::operator<=(const Edge &other) const 68 | { 69 | return w_ <= other.w_; 70 | } 71 | 72 | bool Edge::operator>(const Edge &other) const 73 | { 74 | return w_ > other.w_; 75 | } 76 | 77 | bool Edge::operator<(const Edge &other) const 78 | { 79 | return w_ < other.w_; 80 | } -------------------------------------------------------------------------------- /GRSC/ERS/Entropy Rate Superpixel Segmentation/ERS/Image.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2011, Ming-Yu Liu 3 | 4 | All Rights Reserved 5 | 6 | Permission to use, copy, modify, and distribute this software and 7 | its documentation for any non-commercial purpose is hereby granted 8 | without fee, provided that the above copyright notice appear in 9 | all copies and that both that copyright notice and this permission 10 | notice appear in supporting documentation, and that the name of 11 | the author not be used in advertising or publicity pertaining to 12 | distribution of the software without specific, written prior 13 | permission. 14 | 15 | THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, 16 | INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 17 | ANY PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 18 | ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 19 | WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN 20 | AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING 21 | OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 22 | */ 23 | 24 | #ifndef _image_h_ 25 | #define _image_h_ 26 | 27 | #include 28 | #include 29 | #include 30 | typedef unsigned char uchar; 31 | 32 | /* use imRef to access Image data. */ 33 | #define imRef(im, x, y) (im->access[y][x]) 34 | 35 | /* use imPtr to get pointer to Image data. */ 36 | #define imPtr(im, x, y) &(im->access[y][x]) 37 | 38 | class RGBMap 39 | { 40 | public: 41 | RGBMap(uchar r,uchar g,uchar b): r_(r),g_(g),b_(b) {}; 42 | RGBMap() {}; 43 | uchar r_, g_, b_; 44 | inline RGBMap& operator=(const RGBMap &rhs); 45 | inline double operator-(const RGBMap &other) const; 46 | }; 47 | 48 | double RGBMap::operator-(const RGBMap &other) const 49 | { 50 | double diff = 0; 51 | diff += abs(1.0*r_ - other.r_); 52 | diff += abs(1.0*g_ - other.g_); 53 | diff += abs(1.0*b_ - other.b_); 54 | return diff; 55 | } 56 | 57 | RGBMap& RGBMap::operator=(const RGBMap &rhs) 58 | { 59 | r_ = rhs.r_, g_ = rhs.g_, b_ = rhs.b_; 60 | return (*this); 61 | } 62 | 63 | 64 | template 65 | class Image 66 | { 67 | public: 68 | 69 | // constructor 70 | inline Image(); 71 | 72 | /* create an Image */ 73 | inline Image(const int width, const int height, const bool init = true); 74 | 75 | /* delete an Image */ 76 | inline ~Image(); 77 | 78 | /* release current image if any */ 79 | inline void Release(); 80 | 81 | inline void Resize(const int width,const int height, const bool init = true); 82 | 83 | 84 | 85 | /* init an Image */ 86 | inline void Init(const T &val); 87 | 88 | /* copy an Image */ 89 | inline Image *Copy() const; 90 | 91 | /* get the width of an Image. */ 92 | inline int width() const { return w; } 93 | 94 | /* get the height of an Image. */ 95 | inline int height() const { return h; } 96 | 97 | // returning a reference to the parituclar location. 98 | inline T& Access(int x,int y) {return access[y][x];}; 99 | 100 | 101 | /* Image data. */ 102 | T *data; 103 | 104 | /* row pointers. */ 105 | T **access; 106 | 107 | 108 | 109 | private: 110 | int w, h; 111 | }; 112 | 113 | 114 | template 115 | Image::Image() 116 | { 117 | w = 0; 118 | h = 0; 119 | data = NULL; 120 | access = NULL; 121 | } 122 | 123 | 124 | template 125 | Image::Image(const int width, const int height, const bool init) 126 | { 127 | w = width; 128 | h = height; 129 | data = new T[w * h]; // allocate space for Image data 130 | access = new T*[h]; // allocate space for row pointers 131 | 132 | // initialize row pointers 133 | for (int i = 0; i < h; i++) 134 | access[i] = data + (i * w); 135 | 136 | if (init) 137 | memset(data, 0, w * h * sizeof(T)); 138 | } 139 | 140 | template 141 | Image::~Image() 142 | { 143 | Release(); 144 | } 145 | 146 | template 147 | void Image::Release() 148 | { 149 | if(data) 150 | delete [] data; 151 | if(access) 152 | delete [] access; 153 | 154 | h = 0; 155 | w = 0; 156 | } 157 | 158 | 159 | template 160 | void Image::Resize(const int width, const int height, const bool init) 161 | { 162 | Release(); 163 | w = width; 164 | h = height; 165 | data = new T[w * h]; // allocate space for Image data 166 | access = new T*[h]; // allocate space for row pointers 167 | 168 | // initialize row pointers 169 | for (int i = 0; i < h; i++) 170 | access[i] = data + (i * w); 171 | 172 | if (init) 173 | memset(data, 0, w * h * sizeof(T)); 174 | } 175 | 176 | template 177 | void Image::Init(const T &val) 178 | { 179 | T *ptr = imPtr(this, 0, 0); 180 | T *end = imPtr(this, w-1, h-1); 181 | while (ptr <= end) 182 | *ptr++ = val; 183 | } 184 | 185 | 186 | template 187 | Image *Image::Copy() const 188 | { 189 | Image *im = new Image(w, h, false); 190 | memcpy(im->data, data, w * h * sizeof(T)); 191 | return im; 192 | } 193 | 194 | #endif 195 | 196 | -------------------------------------------------------------------------------- /GRSC/ERS/Entropy Rate Superpixel Segmentation/ERS/ImageIO.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2011, Ming-Yu Liu 3 | 4 | All Rights Reserved 5 | 6 | Permission to use, copy, modify, and distribute this software and 7 | its documentation for any non-commercial purpose is hereby granted 8 | without fee, provided that the above copyright notice appear in 9 | all copies and that both that copyright notice and this permission 10 | notice appear in supporting documentation, and that the name of 11 | the author not be used in advertising or publicity pertaining to 12 | distribution of the software without specific, written prior 13 | permission. 14 | 15 | THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, 16 | INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 17 | ANY PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 18 | ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 19 | WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN 20 | AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING 21 | OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 22 | */ 23 | 24 | #ifndef _image_io_h_ 25 | #define _image_io_h_ 26 | 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include "Image.h" 32 | 33 | 34 | #define BUF_SIZE 256 35 | 36 | 37 | class pnm_error 38 | { 39 | 40 | }; 41 | 42 | class ImageIO 43 | { 44 | public: 45 | inline static Image *LoadPBM(const char *name); 46 | inline static Image *LoadPGM(const char *name); 47 | inline static Image *LoadPPM(const char *name); 48 | template inline void LoadImage(Image **im, const char *name); 49 | 50 | inline static void SavePBM(Image *im, const char *name); 51 | inline static void SavePGM(Image *im, const char *name); 52 | inline static void SavePPM(Image *im, const char *name); 53 | template inline void SaveImage(Image *im, const char *name); 54 | 55 | private: 56 | 57 | 58 | inline static void read_packed(unsigned char *data, int size, std::ifstream &f); 59 | inline static void write_packed(unsigned char *data, int size, std::ofstream &f); 60 | inline static void pnm_read(std::ifstream &file, char *buf); 61 | }; 62 | 63 | 64 | 65 | void ImageIO::read_packed(unsigned char *data, int size, std::ifstream &f) 66 | { 67 | unsigned char c = 0; 68 | int bitshift = -1; 69 | for (int pos = 0; pos < size; pos++) 70 | { 71 | if (bitshift == -1) 72 | { 73 | c = f.get(); 74 | bitshift = 7; 75 | } 76 | data[pos] = (c >> bitshift) & 1; 77 | bitshift--; 78 | } 79 | } 80 | 81 | void ImageIO::write_packed(unsigned char *data, int size, std::ofstream &f) 82 | { 83 | unsigned char c = 0; 84 | 85 | int bitshift = 7; 86 | for (int pos = 0; pos < size; pos++) 87 | { 88 | c = c | (data[pos] << bitshift); 89 | bitshift--; 90 | if ((bitshift == -1) || (pos == size-1)) 91 | { 92 | f.put(c); 93 | bitshift = 7; 94 | c = 0; 95 | } 96 | } 97 | } 98 | 99 | /* read PNM field, skipping comments */ 100 | void ImageIO::pnm_read(std::ifstream &file, char *buf) 101 | { 102 | char doc[BUF_SIZE]; 103 | char c; 104 | 105 | file >> c; 106 | while (c == '#') 107 | { 108 | file.getline(doc, BUF_SIZE); 109 | file >> c; 110 | } 111 | file.putback(c); 112 | file.width(BUF_SIZE); 113 | file >> buf; 114 | file.ignore(); 115 | } 116 | 117 | Image *ImageIO::LoadPBM(const char *name) 118 | { 119 | char buf[BUF_SIZE]; 120 | 121 | /* read header */ 122 | std::ifstream file(name, std::ios::in | std::ios::binary); 123 | pnm_read(file, buf); 124 | if (strncmp(buf, "P4", 2)) 125 | throw pnm_error(); 126 | 127 | pnm_read(file, buf); 128 | int width = atoi(buf); 129 | pnm_read(file, buf); 130 | int height = atoi(buf); 131 | 132 | /* read data */ 133 | Image *im = new Image(width, height); 134 | for (int i = 0; i < height; i++) 135 | read_packed(imPtr(im, 0, i), width, file); 136 | 137 | return im; 138 | } 139 | 140 | void ImageIO::SavePBM(Image *im, const char *name) 141 | { 142 | int width = im->width(); 143 | int height = im->height(); 144 | std::ofstream file(name, std::ios::out | std::ios::binary); 145 | file << "P4\n" << width << " " << height << "\n"; 146 | for (int i = 0; i < height; i++) 147 | write_packed(imPtr(im, 0, i), width, file); 148 | } 149 | 150 | Image *ImageIO::LoadPGM(const char *name) 151 | { 152 | char buf[BUF_SIZE]; 153 | 154 | /* read header */ 155 | std::ifstream file(name, std::ios::in | std::ios::binary); 156 | pnm_read(file, buf); 157 | if (strncmp(buf, "P5", 2)) 158 | return NULL; 159 | 160 | pnm_read(file, buf); 161 | int width = atoi(buf); 162 | pnm_read(file, buf); 163 | int height = atoi(buf); 164 | 165 | pnm_read(file, buf); 166 | if (atoi(buf) > UCHAR_MAX) 167 | return NULL; 168 | 169 | /* read data */ 170 | Image *im = new Image(width, height); 171 | file.read((char *)imPtr(im, 0, 0), width * height * sizeof(uchar)); 172 | 173 | return im; 174 | } 175 | 176 | void ImageIO::SavePGM(Image *im, const char *name) 177 | { 178 | int width = im->width(); 179 | int height = im->height(); 180 | std::ofstream file(name, std::ios::out | std::ios::binary); 181 | 182 | file << "P5\n" << width << " " << height << "\n" << UCHAR_MAX << "\n"; 183 | file.write((char *)imPtr(im, 0, 0), width * height * sizeof(uchar)); 184 | } 185 | 186 | Image *ImageIO::LoadPPM(const char *name) 187 | { 188 | char buf[BUF_SIZE]; 189 | 190 | /* read header */ 191 | std::ifstream file(name, std::ios::in | std::ios::binary); 192 | pnm_read(file, buf); 193 | if (strncmp(buf, "P6", 2)) 194 | throw pnm_error(); 195 | 196 | pnm_read(file, buf); 197 | int width = atoi(buf); 198 | pnm_read(file, buf); 199 | int height = atoi(buf); 200 | 201 | pnm_read(file, buf); 202 | if (atoi(buf) > UCHAR_MAX) 203 | throw pnm_error(); 204 | 205 | /* read data */ 206 | Image *im = new Image(width, height); 207 | file.read((char *)imPtr(im, 0, 0), width * height * sizeof(RGBMap)); 208 | 209 | return im; 210 | } 211 | 212 | void ImageIO::SavePPM(Image *im, const char *name) 213 | { 214 | int width = im->width(); 215 | int height = im->height(); 216 | std::ofstream file(name, std::ios::out | std::ios::binary); 217 | 218 | file << "P6\n" << width << " " << height << "\n" << UCHAR_MAX << "\n"; 219 | file.write((char *)imPtr(im, 0, 0), width * height * sizeof(RGBMap)); 220 | } 221 | template 222 | void ImageIO::LoadImage(Image **im, const char *name) 223 | { 224 | char buf[BUF_SIZE]; 225 | 226 | /* read header */ 227 | std::ifstream file(name, std::ios::in | std::ios::binary); 228 | pnm_read(file, buf); 229 | if (strncmp(buf, "VLIB", 9)) 230 | throw pnm_error(); 231 | 232 | pnm_read(file, buf); 233 | int width = atoi(buf); 234 | pnm_read(file, buf); 235 | int height = atoi(buf); 236 | 237 | /* read data */ 238 | *im = new Image(width, height); 239 | file.read((char *)imPtr((*im), 0, 0), width * height * sizeof(T)); 240 | } 241 | 242 | template 243 | void ImageIO::SaveImage(Image *im, const char *name) 244 | { 245 | int width = im->width(); 246 | int height = im->height(); 247 | std::ofstream file(name, std::ios::out | std::ios::binary); 248 | 249 | file << "VLIB\n" << width << " " << height << "\n"; 250 | file.write((char *)imPtr(im, 0, 0), width * height * sizeof(T)); 251 | } 252 | 253 | #endif 254 | -------------------------------------------------------------------------------- /GRSC/ERS/Entropy Rate Superpixel Segmentation/ERS/MERCCInput.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2011, Ming-Yu Liu 3 | 4 | All Rights Reserved 5 | 6 | Permission to use, copy, modify, and distribute this software and 7 | its documentation for any non-commercial purpose is hereby granted 8 | without fee, provided that the above copyright notice appear in 9 | all copies and that both that copyright notice and this permission 10 | notice appear in supporting documentation, and that the name of 11 | the author not be used in advertising or publicity pertaining to 12 | distribution of the software without specific, written prior 13 | permission. 14 | 15 | THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, 16 | INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 17 | ANY PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 18 | ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 19 | WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN 20 | AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING 21 | OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 22 | */ 23 | #include "MERCInput.h" 24 | #include 25 | 26 | MERCInput::MERCInput() 27 | { 28 | edges_ = NULL; 29 | } 30 | 31 | MERCInput::~MERCInput() 32 | { 33 | Release(); 34 | } 35 | 36 | void MERCInput::Release() 37 | { 38 | if(edges_) 39 | delete [] edges_; 40 | edges_ = NULL; 41 | } 42 | 43 | void MERCInput::ReadFromMatlab(double *pI,double *pJ,double *pW,int nEdges,int nNodes) 44 | { 45 | nEdges_ = nEdges; 46 | nNodes_ = nNodes; 47 | edges_ = new Edge [nEdges_]; 48 | for(int i=0;i> nNodes_; 67 | file >> nEdges_; 68 | edges_ = new Edge [nEdges_]; 69 | for(int i=0;i>edges_[i].a_>>edges_[i].b_>>edges_[i].w_; 71 | file.close(); 72 | } 73 | 74 | 75 | void MERCInput::Write(const char* filename) 76 | { 77 | std::ofstream file; 78 | file.open(filename); 79 | file.precision(6); 80 | file< 33 | #include 34 | #include 35 | #include 36 | #include 37 | 38 | using namespace std; 39 | 40 | 41 | class MERCClustering 42 | { 43 | public: 44 | 45 | void ClusteringTreeIF(int nVertices,MERCInput &edges,int kernel,double sigma,double lambda,int nC) 46 | { 47 | disjointSet_ = ClusteringTree(nVertices,edges,kernel,sigma,lambda,nC); 48 | }; 49 | 50 | virtual MERCDisjointSet* ClusteringTree(int nVertices,MERCInput &edges,int kernel,double sigma,double lambda,int nC) = 0; 51 | 52 | MERCClustering() 53 | { 54 | disjointSet_ = NULL; 55 | }; 56 | 57 | ~MERCClustering() 58 | { 59 | Release(); 60 | }; 61 | 62 | void Release() 63 | { 64 | if(disjointSet_) 65 | delete disjointSet_; 66 | }; 67 | 68 | MERCDisjointSet *disjointSet_; 69 | 70 | }; 71 | 72 | #endif -------------------------------------------------------------------------------- /GRSC/ERS/Entropy Rate Superpixel Segmentation/ERS/MERCDisjointSet.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2011, Ming-Yu Liu 3 | 4 | All Rights Reserved 5 | 6 | Permission to use, copy, modify, and distribute this software and 7 | its documentation for any non-commercial purpose is hereby granted 8 | without fee, provided that the above copyright notice appear in 9 | all copies and that both that copyright notice and this permission 10 | notice appear in supporting documentation, and that the name of 11 | the author not be used in advertising or publicity pertaining to 12 | distribution of the software without specific, written prior 13 | permission. 14 | 15 | THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, 16 | INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 17 | ANY PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 18 | ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 19 | WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN 20 | AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING 21 | OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 22 | */ 23 | #include "MERCDisjointSet.h" 24 | 25 | 26 | MERCDisjointSet::MERCDisjointSet(int nElements) 27 | { 28 | nElements_ = nElements; 29 | nVertices_ = nElements_; 30 | p_ = new int [nElements_]; 31 | size_ = new int [nElements_]; 32 | lists_ = new MList [nElements_]; 33 | 34 | 35 | int reservedSize = (int)std::sqrt( 1.0*nElements ); 36 | // Initialization with the cluster size and id 37 | for (int i = 0; i < nElements; i++) 38 | { 39 | p_[i] = i; 40 | size_[i] = 1; 41 | lists_[i].PushBack(i); 42 | } 43 | } 44 | 45 | MERCDisjointSet::~MERCDisjointSet() 46 | { 47 | Release(); 48 | } 49 | 50 | void MERCDisjointSet::Release() 51 | { 52 | delete [] p_; 53 | delete [] size_; 54 | delete [] lists_; 55 | p_ = NULL; 56 | size_ = NULL; 57 | lists_ = NULL; 58 | 59 | } 60 | 61 | void MERCDisjointSet::Set(int x,int l) 62 | { 63 | p_[x] = l; 64 | } 65 | 66 | int MERCDisjointSet::Find(int x) 67 | { 68 | // return the cluster ID 69 | return p_[x]; 70 | } 71 | 72 | int MERCDisjointSet::Join(int x, int y) 73 | { 74 | int aID = Find(x); 75 | int bID = Find(y); 76 | 77 | // The size is only maintained for cluster ID. 78 | int aSize = size_[aID]; 79 | int bSize = size_[bID]; 80 | 81 | 82 | int newID,delID; 83 | if( bSize < aSize ) 84 | { 85 | newID = aID; 86 | delID = bID; 87 | } 88 | else 89 | { 90 | newID = bID; 91 | delID = aID; 92 | } 93 | 94 | size_[newID] = aSize+bSize; 95 | size_[delID] = 0; 96 | 97 | MListNode *iter; 98 | for(iter=lists_[delID].first_;iter!=NULL;iter=iter->next_) 99 | p_[iter->data_] = newID; 100 | lists_[newID].Append(lists_[delID]); 101 | 102 | nElements_--; 103 | return newID; 104 | } -------------------------------------------------------------------------------- /GRSC/ERS/Entropy Rate Superpixel Segmentation/ERS/MERCDisjointSet.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2011, Ming-Yu Liu 3 | 4 | All Rights Reserved 5 | 6 | Permission to use, copy, modify, and distribute this software and 7 | its documentation for any non-commercial purpose is hereby granted 8 | without fee, provided that the above copyright notice appear in 9 | all copies and that both that copyright notice and this permission 10 | notice appear in supporting documentation, and that the name of 11 | the author not be used in advertising or publicity pertaining to 12 | distribution of the software without specific, written prior 13 | permission. 14 | 15 | THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, 16 | INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 17 | ANY PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 18 | ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 19 | WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN 20 | AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING 21 | OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 22 | */ 23 | #ifndef m_disjoint_set_h_ 24 | #define m_disjoint_set_h_ 25 | 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include "MList.h" 31 | 32 | 33 | class MERCDisjointSet 34 | { 35 | public: 36 | MERCDisjointSet(int nElements); 37 | ~MERCDisjointSet(); 38 | virtual void Release(); 39 | 40 | // set the pixel x with label l 41 | virtual void Set(int x,int l); 42 | 43 | // find the cluster ID for a given vertex 44 | virtual int Find(int x); 45 | 46 | // joint the cluster contains vertex y and the cluster contains vertex x 47 | virtual int Join(int x,int y); 48 | 49 | // return the cluster size containing the vertex x 50 | int rSize(int x) {return size_[Find(x)];}; 51 | 52 | // return the number of connected components in the set 53 | int rNumSets() const {return nElements_;}; 54 | 55 | // return the total number of vertices in the set 56 | int rNumVertices() const {return nVertices_;}; 57 | 58 | private: 59 | 60 | int *p_; 61 | int *size_; 62 | MList *lists_; 63 | int nElements_; 64 | int nVertices_; 65 | }; 66 | 67 | 68 | 69 | 70 | #endif 71 | 72 | -------------------------------------------------------------------------------- /GRSC/ERS/Entropy Rate Superpixel Segmentation/ERS/MERCEdge.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2011, Ming-Yu Liu 3 | 4 | All Rights Reserved 5 | 6 | Permission to use, copy, modify, and distribute this software and 7 | its documentation for any non-commercial purpose is hereby granted 8 | without fee, provided that the above copyright notice appear in 9 | all copies and that both that copyright notice and this permission 10 | notice appear in supporting documentation, and that the name of 11 | the author not be used in advertising or publicity pertaining to 12 | distribution of the software without specific, written prior 13 | permission. 14 | 15 | THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, 16 | INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 17 | ANY PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 18 | ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 19 | WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN 20 | AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING 21 | OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 22 | */ 23 | #ifndef _m_erc_edge_h_ 24 | #define _m_erc_edge_h_ 25 | 26 | #include 27 | #include 28 | 29 | using namespace std; 30 | 31 | class MERCEdge 32 | { 33 | public: 34 | int a_; 35 | int b_; 36 | double w_; 37 | double gain_; 38 | 39 | inline MERCEdge &operator=(const MERCEdge &rhs); 40 | inline bool operator==(const MERCEdge &other) const; 41 | inline bool operator!=(const MERCEdge &other) const; 42 | inline bool operator>=(const MERCEdge &other) const; 43 | inline bool operator<=(const MERCEdge &other) const; 44 | inline bool operator>(const MERCEdge &other) const; 45 | inline bool operator<(const MERCEdge &other) const; 46 | 47 | inline friend ostream &operator<<(ostream &output,MERCEdge &e); 48 | }; 49 | 50 | 51 | 52 | ostream &operator<<(ostream &output,MERCEdge &e) 53 | { 54 | output<< "(" << e.a_ <<", " << e.b_ <<", " << e.w_ <<", " << e.gain_ <<")"; 55 | return output; 56 | } 57 | 58 | 59 | MERCEdge &MERCEdge::operator=(const MERCEdge &rhs) 60 | { 61 | a_ = rhs.a_; 62 | b_ = rhs.b_; 63 | w_ = rhs.w_; 64 | gain_ = rhs.gain_; 65 | return *this; 66 | } 67 | 68 | bool MERCEdge::operator==(const MERCEdge &other) const 69 | { 70 | return gain_ == other.gain_; 71 | } 72 | 73 | bool MERCEdge::operator!=(const MERCEdge &other) const 74 | { 75 | return gain_ != other.gain_; 76 | } 77 | 78 | bool MERCEdge::operator>=(const MERCEdge &other) const 79 | { 80 | return gain_ >= other.gain_; 81 | } 82 | 83 | bool MERCEdge::operator<=(const MERCEdge &other) const 84 | { 85 | return gain_ <= other.gain_; 86 | } 87 | 88 | bool MERCEdge::operator>(const MERCEdge &other) const 89 | { 90 | return gain_ > other.gain_; 91 | } 92 | 93 | bool MERCEdge::operator<(const MERCEdge &other) const 94 | { 95 | return gain_ < other.gain_; 96 | } 97 | 98 | #endif -------------------------------------------------------------------------------- /GRSC/ERS/Entropy Rate Superpixel Segmentation/ERS/MERCFunctions.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2011, Ming-Yu Liu 3 | 4 | All Rights Reserved 5 | 6 | Permission to use, copy, modify, and distribute this software and 7 | its documentation for any non-commercial purpose is hereby granted 8 | without fee, provided that the above copyright notice appear in 9 | all copies and that both that copyright notice and this permission 10 | notice appear in supporting documentation, and that the name of 11 | the author not be used in advertising or publicity pertaining to 12 | distribution of the software without specific, written prior 13 | permission. 14 | 15 | THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, 16 | INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 17 | ANY PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 18 | ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 19 | WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN 20 | AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING 21 | OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 22 | */ 23 | #include "MERCFunctions.h" 24 | 25 | using namespace std; 26 | 27 | double MERCFunctions::ComputeERGain(double wij,double ci,double cj) 28 | { 29 | double er = ((wij+ci)*log(wij+ci) + (wij+cj)*log(wij+cj) - ci*log(ci) - cj*log(cj) - 2*wij*log(wij) )/log(2.0); 30 | if( er!=er ) 31 | return 0; 32 | else 33 | return er; 34 | } 35 | 36 | double MERCFunctions::ComputeBGain(int nVertices, int si,int sj) 37 | { 38 | double Si = si*1.0/nVertices; 39 | double Sj = sj*1.0/nVertices; 40 | double b = (-(Si+Sj)*log(Si+Sj) + Si*log(Si) + Sj*log(Sj))/log(2.0) + 1.0; 41 | return b; 42 | } 43 | 44 | void MERCFunctions::NormalizeEdgeWeight(MERCInput &edges,double *loop,double wT) 45 | { 46 | int nEdges = edges.nEdges_; 47 | int nVertices = edges.nNodes_; 48 | for(int i=0;i 28 | #include 29 | 30 | // Note the potential numerical error. Don't use a very small sigma value. 31 | class MERCFunctions 32 | { 33 | public: 34 | 35 | // compute the similarity scores 36 | static void ComputeSimilarity(MERCInput &edges,double sigma,int kernel=0); 37 | 38 | // compute the similarity scores with the Gaussian kernel. 39 | static void ComputeSimilarityGaussian(MERCInput &edges,double sigma); 40 | 41 | // compute the initial loop weight 42 | static double* ComputeLoopWeight(int nVertices,MERCInput &edges); 43 | 44 | // compute the total weight in the graph 45 | static double ComputeTotalWeight(double *loop,int nVertices); 46 | 47 | // normalize the edge similarity scores 48 | static void NormalizeEdgeWeight(MERCInput &edges,double *loop,double wT); 49 | 50 | // compute the edge gain in the entropy rate 51 | static double ComputeERGain(double wij,double ci,double cj); 52 | 53 | // compute the edge gain in the balancing term 54 | static double ComputeBGain(int nVertices, int si,int sj); 55 | 56 | }; 57 | 58 | #endif -------------------------------------------------------------------------------- /GRSC/ERS/Entropy Rate Superpixel Segmentation/ERS/MERCInput.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2011, Ming-Yu Liu 3 | 4 | All Rights Reserved 5 | 6 | Permission to use, copy, modify, and distribute this software and 7 | its documentation for any non-commercial purpose is hereby granted 8 | without fee, provided that the above copyright notice appear in 9 | all copies and that both that copyright notice and this permission 10 | notice appear in supporting documentation, and that the name of 11 | the author not be used in advertising or publicity pertaining to 12 | distribution of the software without specific, written prior 13 | permission. 14 | 15 | THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, 16 | INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 17 | ANY PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 18 | ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 19 | WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN 20 | AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING 21 | OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 22 | */ 23 | #ifndef _m_erc_input_h_ 24 | #define _m_erc_input_h_ 25 | 26 | #include 27 | #include 28 | #include "Edge.h" 29 | 30 | using namespace std; 31 | 32 | class MERCInput 33 | { 34 | public: 35 | MERCInput(); 36 | ~MERCInput(); 37 | void Release(); 38 | void Write(const char* filename); 39 | void Read(const char* filename); 40 | void ReadFromMatlab(double *pI,double *pJ,double *pW,int nEdges,int nNodes); 41 | 42 | public: 43 | Edge *edges_; 44 | int nEdges_; 45 | int nNodes_; 46 | 47 | }; 48 | 49 | #endif -------------------------------------------------------------------------------- /GRSC/ERS/Entropy Rate Superpixel Segmentation/ERS/MERCInputImage.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2011, Ming-Yu Liu 3 | 4 | All Rights Reserved 5 | 6 | Permission to use, copy, modify, and distribute this software and 7 | its documentation for any non-commercial purpose is hereby granted 8 | without fee, provided that the above copyright notice appear in 9 | all copies and that both that copyright notice and this permission 10 | notice appear in supporting documentation, and that the name of 11 | the author not be used in advertising or publicity pertaining to 12 | distribution of the software without specific, written prior 13 | permission. 14 | 15 | THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, 16 | INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 17 | ANY PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 18 | ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 19 | WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN 20 | AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING 21 | OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 22 | */ 23 | #ifndef _m_erc_input_image_h_ 24 | #define _m_erc_input_image_h_ 25 | 26 | #include "MERCInput.h" 27 | #include "Image.h" 28 | #include 29 | 30 | using namespace std; 31 | 32 | template 33 | class MERCInputImage: public MERCInput 34 | { 35 | public: 36 | void ReadImage(Image *inputImage); 37 | 38 | int width_; 39 | int height_; 40 | }; 41 | 42 | template 43 | void MERCInputImage::ReadImage(Image *inputImage) 44 | { 45 | width_ = inputImage->width(); 46 | height_ = inputImage->height(); 47 | nNodes_ = width_*height_; 48 | 49 | //cout<Access(x,y) - inputImage->Access(x+1,y))); 62 | num++; 63 | } 64 | 65 | if (y < height_-1) 66 | { 67 | edges_[num].a_ = y * width_ + x; 68 | edges_[num].b_ = (y+1) * width_ + x; 69 | //edges_[num].w_ = DiffGrayImage(image, x, y, x, y+1); 70 | edges_[num].w_ = abs(1.0*(inputImage->Access(x,y) - inputImage->Access(x,y+1))); 71 | num++; 72 | } 73 | 74 | if ((x < width_-1) && (y < height_-1)) 75 | { 76 | edges_[num].a_ = y * width_ + x; 77 | edges_[num].b_ = (y+1) * width_ + (x+1); 78 | //edges_[num].w_ = std::sqrt(2.0)*DiffGrayImage(image, x, y, x+1, y+1); 79 | edges_[num].w_ = sqrt(2.0)*abs(1.0*(inputImage->Access(x,y) - inputImage->Access(x+1,y+1))); 80 | num++; 81 | } 82 | 83 | if ((x < width_-1) && (y > 0)) 84 | { 85 | edges_[num].a_ = y * width_ + x; 86 | edges_[num].b_ = (y-1) * width_ + (x+1); 87 | //edges_[num].w_ = std::sqrt(2.0)*DiffGrayImage(image, x, y, x+1, y-1); 88 | edges_[num].w_ = sqrt(2.0)*abs(1.0*(inputImage->Access(x,y) - inputImage->Access(x+1,y-1))); 89 | num++; 90 | } 91 | } 92 | } 93 | nEdges_ = num; 94 | } 95 | 96 | #endif -------------------------------------------------------------------------------- /GRSC/ERS/Entropy Rate Superpixel Segmentation/ERS/MERCLazyGreedy.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2011, Ming-Yu Liu 3 | 4 | All Rights Reserved 5 | 6 | Permission to use, copy, modify, and distribute this software and 7 | its documentation for any non-commercial purpose is hereby granted 8 | without fee, provided that the above copyright notice appear in 9 | all copies and that both that copyright notice and this permission 10 | notice appear in supporting documentation, and that the name of 11 | the author not be used in advertising or publicity pertaining to 12 | distribution of the software without specific, written prior 13 | permission. 14 | 15 | THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, 16 | INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 17 | ANY PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 18 | ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 19 | WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN 20 | AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING 21 | OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 22 | */ 23 | #include "MERCLazyGreedy.h" 24 | 25 | MERCDisjointSet* MERCLazyGreedy::ClusteringTree(int nVertices,MERCInput &edges,int kernel,double sigma,double lambda,int nC) 26 | { 27 | //LARGE_INTEGER t1, t2, f; 28 | //QueryPerformanceFrequency(&f); 29 | //QueryPerformanceCounter(&t1); 30 | 31 | 32 | int nEdges = edges.nEdges_; 33 | MERCDisjointSet *u = new MERCDisjointSet(nVertices); 34 | 35 | MERCFunctions::ComputeSimilarity(edges,sigma,kernel); 36 | double *loop = MERCFunctions::ComputeLoopWeight(nVertices,edges); 37 | double wT = MERCFunctions::ComputeTotalWeight(loop,nVertices); 38 | MERCFunctions::NormalizeEdgeWeight(edges,loop,wT); 39 | 40 | // 41 | // Compute initial gain and decide the weighting on the balancing term 42 | // 43 | double *erGainArr = new double [nEdges];// gain in entropy rate term 44 | double *bGainArr = new double [nEdges]; // gain in balancing term 45 | double maxERGain=0,maxBGain=1e-20; 46 | for(int i=0;iFind( edges.edges_[i].a_ ); 53 | int b = u->Find( edges.edges_[i].b_ ); 54 | if(a!=b) 55 | bGainArr[i] = MERCFunctions::ComputeBGain(nVertices, u->rSize(a), u->rSize(b) ); 56 | else 57 | bGainArr[i] = 0; 58 | if(erGainArr[i]>maxERGain) 59 | maxERGain = erGainArr[i]; 60 | if(bGainArr[i]>maxBGain) 61 | maxBGain = bGainArr[i]; 62 | } 63 | double balancing = lambda*maxERGain/std::abs(maxBGain); 64 | //double balancing = lambda* log( 1.0*nVertices )/ log( 1.0*nC ); 65 | 66 | /* 67 | std::cout.precision(8); 68 | std::cout.setf(ios::fixed,ios::floatfield); 69 | std::cout<<"maxERGain = "<Find( bestEdge.a_ ); 108 | b = u->Find( bestEdge.b_ ); 109 | 110 | if(a!=b) 111 | { 112 | u->Join(a,b); 113 | cc--; 114 | loop[bestEdge.a_] -= bestEdge.w_; 115 | loop[bestEdge.b_] -= bestEdge.w_; 116 | } 117 | 118 | heap.EasyPartialUpdateTree(u,balancing,loop); 119 | } 120 | 121 | 122 | delete [] loop; 123 | //QueryPerformanceCounter(&t2); 124 | //std::cout.precision(6); 125 | //std::cout< &label,const char *filename) 26 | { 27 | std::ofstream file; 28 | file.open(filename); 29 | 30 | for(int i=0;i MERCOutput::DisjointSetToLabel(MERCDisjointSet *u) 39 | { 40 | int nSegments=0; 41 | int segIndex = 0; 42 | int nVertices = u->rNumVertices(); 43 | std::vector *sarray = new std::vector [nVertices]; 44 | vector labeling(nVertices); 45 | 46 | for (int k=0; kFind(k); 49 | sarray[comp].push_back(k); 50 | } 51 | 52 | for(int k=0;k 0) 55 | { 56 | nSegments++; 57 | } 58 | } 59 | 60 | for(int k=0;k 0) 63 | { 64 | for(unsigned int j=0;j 27 | #include 28 | #include 29 | #include "MERCDisjointSet.h" 30 | using namespace std; 31 | 32 | class MERCOutput 33 | { 34 | public: 35 | 36 | // Convert disjoint the set structure to a label array 37 | static vector DisjointSetToLabel(MERCDisjointSet *u); 38 | 39 | // Store the clustering map 40 | static void StoreClusteringMap(vector &label,const char *filename); 41 | }; 42 | 43 | 44 | 45 | #endif -------------------------------------------------------------------------------- /GRSC/ERS/Entropy Rate Superpixel Segmentation/ERS/MERCOutputImage.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2011, Ming-Yu Liu 3 | 4 | All Rights Reserved 5 | 6 | Permission to use, copy, modify, and distribute this software and 7 | its documentation for any non-commercial purpose is hereby granted 8 | without fee, provided that the above copyright notice appear in 9 | all copies and that both that copyright notice and this permission 10 | notice appear in supporting documentation, and that the name of 11 | the author not be used in advertising or publicity pertaining to 12 | distribution of the software without specific, written prior 13 | permission. 14 | 15 | THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, 16 | INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 17 | ANY PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 18 | ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 19 | WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN 20 | AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING 21 | OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 22 | */ 23 | #ifndef _m_erc_output_image_h_ 24 | #define _m_erc_output_image_h_ 25 | 26 | #include "MERCOutput.h" 27 | #include "Image.h" 28 | #include "ImageIO.h" 29 | 30 | using namespace std; 31 | 32 | class MERCOutputImage: public MERCOutput 33 | { 34 | public: 35 | static void StoreSegmentationMap(vector &label,int width,int height,const char *filename); 36 | 37 | 38 | }; 39 | 40 | void MERCOutputImage::StoreSegmentationMap(vector &label,int width,int height,const char *filename) 41 | { 42 | Image outputImage(width,height); 43 | 44 | RGBMap *color = new RGBMap[width*height]; 45 | 46 | for(int i=0; i 26 | 27 | template 28 | class MHeap 29 | { 30 | public: 31 | 32 | MHeap(); 33 | 34 | // Construct a heap with $length elements 35 | MHeap(int length); 36 | // Construct a heap from an array with $length elements 37 | MHeap(T *inarr,int length); 38 | // Destructor 39 | ~MHeap(); 40 | 41 | // Extract the top element from a max heap 42 | T HeapExtractMax(); 43 | // Extract the top element from a min heap 44 | T HeapExtractMin(); 45 | 46 | void MaxHeapify(int i); 47 | void MinHeapify(int i); 48 | 49 | // Build a max heap 50 | void BuildMaxHeap(); 51 | // Build a min heap 52 | void BuildMinHeap(); 53 | 54 | void HeapSort(); 55 | 56 | int HeapSize() {return nElements_;}; 57 | 58 | bool IsEmpty() { return nElements_==0; }; 59 | 60 | void PrintHeap(const char *filename); 61 | void PrintHeapSort(const char *filename); 62 | 63 | protected: 64 | void Release(); 65 | void HeapSortAscend(); 66 | void HeapSortDescend(); 67 | 68 | int Left(int i) {return (i<<1);}; 69 | int Right(int i) {return (i<<1)+1;}; 70 | int Parent(int i) {return (i>>1);}; 71 | T* pElement(int i) {return array_+i;}; 72 | 73 | // debug function used in developing code 74 | void CheckMaxHeap(); 75 | // debug function used in developing code 76 | void CheckMinHeap(); 77 | 78 | int maxHeap_; 79 | 80 | T *array_; // the container 81 | int length_; // size of the array 82 | int nElements_; // # of elements in the heap 83 | }; 84 | 85 | template 86 | MHeap::MHeap() {}; 87 | 88 | template 89 | MHeap::MHeap(int length) 90 | { 91 | maxHeap_ = 1; // max heap by default 92 | nElements_ = 0; 93 | length_ = length; 94 | array_ = new T [length_+1]; 95 | } 96 | 97 | template 98 | MHeap::MHeap(T *inarr,int length) 99 | { 100 | maxHeap_ = 1; // max heap by default 101 | nElements_ = 0; 102 | length_ = length; 103 | array_ = new T [length_+1]; 104 | for(int i=0;i 109 | MHeap::~MHeap() 110 | { 111 | Release(); 112 | } 113 | 114 | template 115 | T MHeap::HeapExtractMax() 116 | { 117 | if( HeapSize() < 1) 118 | { 119 | std::cout<<"Heap underflow error"< 130 | T MHeap::HeapExtractMin() 131 | { 132 | if( HeapSize() < 1) 133 | { 134 | std::cout<<"Heap underflow error"< 146 | void MHeap::HeapSort() 147 | { 148 | if( maxHeap_ ) 149 | HeapSortAscend(); 150 | else 151 | HeapSortDescend(); 152 | } 153 | 154 | template 155 | void MHeap::HeapSortDescend() 156 | { 157 | BuildMinHeap(); 158 | for(int i=length_;i>=2;i--) 159 | { 160 | // exchange A[1] and A[i] 161 | T tmp; 162 | tmp = array_[1]; 163 | array_[1] = array_[i]; 164 | array_[i] = tmp; 165 | nElements_--; 166 | MinHeapify(1); 167 | } 168 | } 169 | 170 | template 171 | void MHeap::HeapSortAscend() 172 | { 173 | BuildMaxHeap(); 174 | for(int i=length_;i>=2;i--) 175 | { 176 | // exchange A[1] and A[i] 177 | T tmp; 178 | tmp = array_[1]; 179 | array_[1] = array_[i]; 180 | array_[i] = tmp; 181 | nElements_--; 182 | MaxHeapify(1); 183 | } 184 | } 185 | 186 | template 187 | void MHeap::BuildMinHeap() 188 | { 189 | maxHeap_ = 0; 190 | nElements_ = length_; 191 | int hLength = length_/2; 192 | for( int i=hLength; i>=1 ; i--) 193 | MinHeapify(i); 194 | } 195 | 196 | template 197 | void MHeap::BuildMaxHeap() 198 | { 199 | maxHeap_ = 1; 200 | nElements_ = length_; 201 | int hLength = length_/2; 202 | for( int i=hLength; i>=1 ; i--) 203 | MaxHeapify(i); 204 | } 205 | 206 | template 207 | void MHeap::MinHeapify(int i) 208 | { 209 | int left,right,smallest; 210 | 211 | left = Left(i); 212 | right = Right(i); 213 | 214 | if( left <= HeapSize() && array_[left] 233 | void MHeap::MaxHeapify(int i) 234 | { 235 | int left,right,largest; 236 | 237 | left = Left(i); 238 | right = Right(i); 239 | 240 | if( left <= HeapSize() && array_[left]>array_[i] ) 241 | largest = left; 242 | else 243 | largest = i; 244 | 245 | if( right <= HeapSize() && array_[right]>array_[largest] ) 246 | largest = right; 247 | 248 | if( largest != i ) 249 | { 250 | T tmp; 251 | tmp = array_[i]; 252 | array_[i] = array_[largest]; 253 | array_[largest] = tmp; 254 | MaxHeapify(largest); 255 | } 256 | } 257 | 258 | 259 | template 260 | void MHeap::Release() 261 | { 262 | delete [] array_; 263 | } 264 | 265 | template 266 | void MHeap::PrintHeap(const char *filename) 267 | { 268 | std::ofstream file; 269 | file.open(filename); 270 | for(int i=1;i<=HeapSize();i++) 271 | file< 276 | void MHeap::PrintHeapSort(const char *filename) 277 | { 278 | std::ofstream file; 279 | file.open(filename); 280 | for(int i=1;i<=length_;i++) 281 | file< 286 | void MHeap::CheckMaxHeap() 287 | { 288 | 289 | for(int i=1;i<=HeapSize();i++) 290 | { 291 | // check if the left child is no greater than the parent 292 | if(Left(i)<=HeapSize()) 293 | { 294 | if( array_[i] < array_[Left(i)] ) 295 | std::cout<<"Error"< 307 | void MHeap::CheckMinHeap() 308 | { 309 | 310 | for(int i=1;i<=HeapSize();i++) 311 | { 312 | // check if the left child is no greater than the parent 313 | if(Left(i)<=HeapSize()) 314 | { 315 | if( array_[i] > array_[Left(i)] ) 316 | std::cout<<"Error"< array_[Right(i)] ) 322 | std::cout<<"Error"< 27 | class MListNode 28 | { 29 | public: 30 | T data_; 31 | MListNode *next_; 32 | }; 33 | 34 | 35 | template 36 | class MList 37 | { 38 | 39 | public: 40 | MList() { 41 | size_ = 0; 42 | first_ = NULL; 43 | last_ = NULL; 44 | }; 45 | ~MList() 46 | { 47 | Clear(); 48 | }; 49 | 50 | // Clear everything in the list 51 | void Clear(); 52 | 53 | // Push a new node to the end of the list 54 | void PushBack(T &data); 55 | 56 | // Append a list to the end of this list 57 | void Append(MList &other); 58 | //void Append(MList *other); 59 | 60 | // Return the number of elements in the list 61 | unsigned int rSize() {return size_;}; 62 | 63 | // Copy the list 64 | inline MList &operator=(const MList &rhs); 65 | 66 | 67 | MListNode *first_; 68 | MListNode *last_; 69 | unsigned int size_; 70 | }; 71 | 72 | template 73 | MList& MList::operator=(const MList &rhs) 74 | { 75 | MListNode *tmp; 76 | for(tmp=rhs.first_;tmp!=NULL;tmp=tmp->next_) 77 | { 78 | this->PushBack(tmp->data_); 79 | } 80 | return *this; 81 | } 82 | 83 | template 84 | void MList::Append(MList &other) 85 | { 86 | if(size_==0) 87 | { 88 | size_ = other.size_; 89 | first_ = other.first_; 90 | last_ = other.last_; 91 | } 92 | else 93 | { 94 | size_ += other.rSize(); 95 | last_->next_ = other.first_; 96 | last_ = other.last_; 97 | } 98 | 99 | // We should not release the dynamic memory at this place 100 | // since they are appended to the end of the other list. 101 | other.first_ = NULL; 102 | other.last_ = NULL; 103 | other.size_ = 0; 104 | } 105 | 106 | 107 | template 108 | void MList::Clear() 109 | { 110 | if(size_ == 0 ) 111 | return; 112 | 113 | MListNode *node = first_; 114 | while(node!=NULL) 115 | { 116 | // pointer to the next 117 | MListNode *tmp = node->next_; 118 | // delete the current one 119 | delete node; 120 | // link to the next 121 | node = tmp; 122 | } 123 | 124 | first_ = NULL; 125 | last_ = NULL; 126 | size_ = 0; 127 | } 128 | 129 | template 130 | void MList::PushBack(T &data) 131 | { 132 | // copy the content 133 | MListNode *node = new MListNode [1]; 134 | node->data_ = data; 135 | node->next_ = NULL; 136 | 137 | // if the list is empty 138 | if(last_==NULL) 139 | { 140 | // update the first node 141 | first_ = node; 142 | // update the last node 143 | last_ = node; 144 | // increase the size by one 145 | size_++; 146 | } 147 | else 148 | { 149 | // insert to the end of the list 150 | last_->next_ = node; 151 | // update the last node 152 | last_ = node; 153 | // increase the size by one 154 | size_++; 155 | } 156 | } 157 | 158 | 159 | #endif -------------------------------------------------------------------------------- /GRSC/ERS/Entropy Rate Superpixel Segmentation/ERS/MMFunctions.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2011, Ming-Yu Liu 3 | 4 | All Rights Reserved 5 | 6 | Permission to use, copy, modify, and distribute this software and 7 | its documentation for any non-commercial purpose is hereby granted 8 | without fee, provided that the above copyright notice appear in 9 | all copies and that both that copyright notice and this permission 10 | notice appear in supporting documentation, and that the name of 11 | the author not be used in advertising or publicity pertaining to 12 | distribution of the software without specific, written prior 13 | permission. 14 | 15 | THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, 16 | INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 17 | ANY PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 18 | ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 19 | WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN 20 | AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING 21 | OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 22 | */ 23 | #ifndef _m_mfunctions_h_ 24 | #define _m_mfunctions_h_ 25 | 26 | class MMFunctions 27 | { 28 | public: 29 | 30 | // sort the array of elements in ra. 31 | // return the sorted arrary in ra. 32 | template 33 | inline static void Sort(T* ra, int nVec,int ascending=1); 34 | 35 | // sort the array of elements in ra. 36 | // return the sorted arrary in ra. 37 | // also return an arrary containing the origin orders of the sorted elements in ira. 38 | template 39 | inline static void ISort(T* ra, int nVec, int* ira,int ascending=1); 40 | 41 | private: 42 | 43 | template 44 | inline static void Sort_Ascending(T* ra, int nVec); 45 | 46 | template 47 | inline static void Sort_Descending(T* ra, int nVec); 48 | 49 | template 50 | inline static void ISort_Ascending(T* ra, int nVec, int* ira); 51 | 52 | template 53 | inline static void ISort_Descending(T* ra, int nVec, int* ira); 54 | }; 55 | 56 | 57 | template void MMFunctions::Sort(T* ra, int nVec,int ascending) 58 | { 59 | if(ascending) 60 | Sort_Ascending(ra,nVec); 61 | else 62 | Sort_Descending(ra,nVec); 63 | } 64 | 65 | 66 | template void MMFunctions::Sort_Descending(T* ra, int nVec) 67 | { 68 | unsigned long n, l, ir, i, j; 69 | n = nVec; 70 | T rra; 71 | 72 | if (n<2) 73 | return; 74 | l = (n>>1)+1; 75 | ir = n; 76 | for (;;) 77 | { 78 | if (l>1) 79 | { 80 | rra = ra[(--l)-1]; 81 | } 82 | else 83 | { 84 | rra = ra[ir-1]; 85 | ra[ir-1] = ra[1-1]; 86 | if (--ir==1) 87 | { 88 | ra[1-1] = rra; 89 | break; 90 | } 91 | } 92 | i = l; 93 | j = l+l; 94 | while (j<=ir) 95 | { 96 | if (jra[j+1-1]) 97 | j++; 98 | if (rra>ra[j-1]) 99 | { 100 | ra[i-1] = ra[j-1]; 101 | i = j; 102 | j <<= 1; 103 | } 104 | else 105 | j = ir+1; 106 | } 107 | ra[i-1] = rra; 108 | } 109 | } 110 | 111 | template void MMFunctions::Sort_Ascending(T* ra, int nVec) 112 | { 113 | unsigned long n, l, ir, i, j; 114 | n = nVec; 115 | T rra; 116 | 117 | if (n<2) 118 | return; 119 | l = (n>>1)+1; 120 | ir = n; 121 | for (;;) 122 | { 123 | if (l>1) 124 | { 125 | rra = ra[(--l)-1]; 126 | } 127 | else 128 | { 129 | rra = ra[ir-1]; 130 | ra[ir-1] = ra[1-1]; 131 | if (--ir==1) 132 | { 133 | ra[1-1] = rra; 134 | break; 135 | } 136 | } 137 | i = l; 138 | j = l+l; 139 | while (j<=ir) 140 | { 141 | if (j void MMFunctions::ISort(T* ra, int nVec, int* ira,int ascending) 159 | { 160 | if(ascending) 161 | ISort_Ascending(ra,nVec,ira); 162 | else 163 | ISort_Descending(ra,nVec,ira); 164 | } 165 | 166 | template void MMFunctions::ISort_Descending(T* ra, int nVec, int* ira) 167 | { 168 | unsigned long n, l, ir, i, j; 169 | n = nVec; 170 | T rra; 171 | int irra; 172 | 173 | if (n<2) 174 | return; 175 | l = (n>>1)+1; 176 | ir = n; 177 | for (;;) 178 | { 179 | if (l>1) 180 | { 181 | irra = ira[(--l)-1]; 182 | rra = ra[l-1]; 183 | } 184 | else 185 | { 186 | irra = ira[ir-1]; 187 | rra = ra[ir-1]; 188 | 189 | ira[ir-1] = ira[1-1]; 190 | ra[ir-1] = ra[1-1]; 191 | 192 | if (--ir==1) 193 | { 194 | ira[1-1] = irra; 195 | ra[1-1] = rra; 196 | break; 197 | } 198 | } 199 | i = l; 200 | j = l+l; 201 | while (j<=ir) 202 | { 203 | if (jra[j+1-1]) 204 | j++; 205 | if (rra>ra[j-1]) 206 | { 207 | ira[i-1] = ira[j-1]; 208 | ra[i-1] = ra[j-1]; 209 | 210 | i = j; 211 | j <<= 1; 212 | } 213 | else 214 | j = ir+1; 215 | } 216 | ira[i-1] = irra; 217 | ra[i-1] = rra; 218 | } 219 | } 220 | 221 | template void MMFunctions::ISort_Ascending(T* ra, int nVec, int* ira) 222 | { 223 | unsigned long n, l, ir, i, j; 224 | n = nVec; 225 | T rra; 226 | int irra; 227 | 228 | if (n<2) 229 | return; 230 | l = (n>>1)+1; 231 | ir = n; 232 | for (;;) 233 | { 234 | if (l>1) 235 | { 236 | irra = ira[(--l)-1]; 237 | rra = ra[l-1]; 238 | } 239 | else 240 | { 241 | irra = ira[ir-1]; 242 | rra = ra[ir-1]; 243 | 244 | ira[ir-1] = ira[1-1]; 245 | ra[ir-1] = ra[1-1]; 246 | 247 | if (--ir==1) 248 | { 249 | ira[1-1] = irra; 250 | ra[1-1] = rra; 251 | break; 252 | } 253 | } 254 | i = l; 255 | j = l+l; 256 | while (j<=ir) 257 | { 258 | if (j 33 | class MSubmodularHeap: public MHeap 34 | { 35 | public: 36 | 37 | MSubmodularHeap(int length); 38 | MSubmodularHeap(T *inarr,int length); 39 | 40 | // An easy update version for tree structure 41 | void EasyPartialUpdateTree(MERCDisjointSet *u,double balancingTerm,double *loop); 42 | 43 | 44 | private: 45 | 46 | MERCDisjointSet *u_; 47 | double *loop_; 48 | double balancingTerm_; 49 | 50 | // An easy update version for tree structure 51 | int EasyUpdateValueTree(int i); 52 | void EasySubmodularMaxHeapifyTree(); 53 | 54 | }; 55 | 56 | 57 | template 58 | MSubmodularHeap::MSubmodularHeap(int length): MHeap(length) {} 59 | 60 | template 61 | MSubmodularHeap::MSubmodularHeap(T *inarr,int length): MHeap(inarr,length) {} 62 | 63 | //============================================================================== 64 | // Fast update for tree structure 65 | //============================================================================== 66 | template 67 | void MSubmodularHeap::EasyPartialUpdateTree(MERCDisjointSet *u,double balancingTerm,double *loop) 68 | { 69 | // access to the disjoint set structure 70 | u_ = u; 71 | // keep track the loop value 72 | loop_ = loop; 73 | // copy the balancing parameter value. 74 | balancingTerm_ = balancingTerm; 75 | 76 | // A special heap update structure that utilize the submodular property. 77 | EasySubmodularMaxHeapifyTree(); 78 | } 79 | 80 | template 81 | void MSubmodularHeap::EasySubmodularMaxHeapifyTree() 82 | { 83 | //If the root node value is not updated, then update it 84 | //If the root node value is updated, then it is the maximum value in the current heap. 85 | //We don't need to update the other nodes because the dimnishing return property guarantees that the value can only be smaller. 86 | while(EasyUpdateValueTree(1)==0) 87 | { 88 | // If the edge form a loop, remove it from the loop and update the heap. 89 | if(this->array_[1].gain_ == 0) 90 | this->HeapExtractMax(); 91 | // Let insert the value into some correct place in the heap. 92 | else 93 | this->MaxHeapify(1); // find the maximum one through maxheapify 94 | } 95 | } 96 | 97 | 98 | template 99 | int MSubmodularHeap::EasyUpdateValueTree(int i) 100 | { 101 | double erGain,bGain; 102 | // store the old gain 103 | double oldGain = this->array_[i].gain_; 104 | 105 | int a,b; 106 | a = u_->Find( this->array_[i].a_ ); 107 | b = u_->Find( this->array_[i].b_ ); 108 | 109 | 110 | 111 | // If the edge forms a cycle, makes the gain zero. 112 | // Later, we will remove the zero edges from the heap. 113 | if( a==b ) 114 | { 115 | this->array_[i].gain_ = 0; 116 | } 117 | else 118 | { 119 | // recompute the entropy rate gain 120 | erGain = MERCFunctions::ComputeERGain( this->array_[i].w_, loop_[this->array_[i].a_]-this->array_[i].w_, loop_[this->array_[i].b_]-this->array_[i].w_); 121 | 122 | // recomptue the balancing gain 123 | bGain = MERCFunctions::ComputeBGain(u_->rNumVertices(), u_->rSize(a), u_->rSize(b) ); 124 | 125 | 126 | // compute the overall gain 127 | this->array_[i].gain_ = erGain+balancingTerm_*bGain; 128 | //array_[i].erGain_ = erGain; 129 | //array_[i].bGain_ = bGain; 130 | } 131 | 132 | // If the value is uptodate, we return one. (It will exit the while loop.) 133 | if(oldGain==this->array_[i].gain_) 134 | return 1; 135 | 136 | // If it is not, then we return zero. (It will trigger another MaxHeapify.) 137 | return 0; 138 | } 139 | 140 | 141 | 142 | #endif -------------------------------------------------------------------------------- /GRSC/ERS/Entropy Rate Superpixel Segmentation/ERS/mex_ers.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2011, Ming-Yu Liu 3 | 4 | All Rights Reserved 5 | 6 | Permission to use, copy, modify, and distribute this software and 7 | its documentation for any non-commercial purpose is hereby granted 8 | without fee, provided that the above copyright notice appear in 9 | all copies and that both that copyright notice and this permission 10 | notice appear in supporting documentation, and that the name of 11 | the author not be used in advertising or publicity pertaining to 12 | distribution of the software without specific, written prior 13 | permission. 14 | 15 | THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, 16 | INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 17 | ANY PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 18 | ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 19 | WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN 20 | AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING 21 | OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 22 | */ 23 | 24 | // Entropy Rate Superpixel Segmentation 25 | #include "mex.h" 26 | #include "MERCLazyGreedy.h" 27 | #include "MERCInputImage.h" 28 | #include "MERCOutputImage.h" 29 | 30 | #include "Image.h" 31 | #include "ImageIO.h" 32 | #include 33 | #include 34 | 35 | using namespace std; 36 | 37 | void mexFunction(int nlhs, mxArray *plhs[ ],int nrhs, const mxArray *prhs[ ]) 38 | { 39 | double lambda,sigma; 40 | int nC,kernel = 0; 41 | int row,col; 42 | double *pLambda,*pSigma,*pNC; 43 | double *data; 44 | double *out; 45 | size_t width,height; 46 | Image inputImage; 47 | MERCInputImage input; 48 | MERCLazyGreedy merc; 49 | 50 | if(!(nrhs==2||nrhs==4)) 51 | { 52 | mexErrMsgTxt("Error!!!\n"); 53 | mexErrMsgTxt("[labels] = mex_ers(image,nC)\n"); 54 | mexErrMsgTxt("[labels] = mex_ers(image,nC,lambda,sigma)\n"); 55 | } 56 | 57 | width = mxGetN(prhs[0]); 58 | height = mxGetM(prhs[0]); 59 | data = mxGetPr(prhs[0]); 60 | 61 | if(nrhs==2) 62 | { 63 | pNC = mxGetPr(prhs[1]); 64 | lambda = 0.5; 65 | sigma = 5.0; 66 | } 67 | 68 | if(nrhs==4) 69 | { 70 | pNC = mxGetPr(prhs[1]); 71 | pLambda = mxGetPr(prhs[2]); 72 | pSigma = mxGetPr(prhs[3]); 73 | lambda = *pLambda; 74 | sigma = *pSigma; 75 | } 76 | 77 | nC = (int)(*pNC); 78 | 79 | // Create Iamge 80 | inputImage.Resize(width,height,false); 81 | // Read the image from MATLAB 82 | for (col=0; col < mxGetN(prhs[0]); col++) 83 | for (row=0; row < mxGetM(prhs[0]); row++) 84 | inputImage.Access(col,row) = mxGetPr(prhs[0])[row+col*mxGetM(prhs[0])]; 85 | // Read the image for segmentation 86 | input.ReadImage(&inputImage); 87 | 88 | // Entropy rate superpixel segmentation 89 | merc.ClusteringTreeIF(input.nNodes_,input,kernel,sigma,lambda*1.0*nC,nC); 90 | vector label = MERCOutputImage::DisjointSetToLabel(merc.disjointSet_); 91 | 92 | // Allocate memory for the labeled image. 93 | plhs[0] = mxCreateDoubleMatrix(height, width, mxREAL); 94 | out = mxGetPr(plhs[0]); 95 | // Fill in the labeled image 96 | for (col=0; col < width; col++) 97 | for (row=0; row < height; row++) 98 | out[row+col*height] = (double)label[col+row*width]; 99 | 100 | return; 101 | } 102 | -------------------------------------------------------------------------------- /GRSC/ERS/Entropy Rate Superpixel Segmentation/README.txt: -------------------------------------------------------------------------------- 1 | /******************************************************************** 2 | * Entropy Rate Superpixel Segmentation code * 3 | * * 4 | * Ming-Yu Liu (UMD), Oncel Tuzel (MERL), * 5 | * Srikumar Ramalingam (MERL) and Rama Chellappa (UMD) * 6 | * * 7 | /******************************************************************** 8 | 9 | /* Copyright 2011, Ming-Yu Liu 10 | 11 | All Rights Reserved 12 | 13 | Permission to use, copy, modify, and distribute this software and 14 | its documentation for any non-commercial purpose is hereby granted 15 | without fee, provided that the above copyright notice appear in 16 | all copies and that both that copyright notice and this permission 17 | notice appear in supporting documentation, and that the name of 18 | the author not be used in advertising or publicity pertaining to 19 | distribution of the software without specific, written prior 20 | permission. 21 | 22 | THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, 23 | INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 24 | ANY PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 25 | ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 26 | WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN 27 | AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING 28 | OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 29 | */ 30 | 31 | /******************************************************************** 32 | * General information * 33 | /******************************************************************** 34 | Thanks for your interest in our work. This is a MATLAB wrapper for the 35 | Entropy Rate Superpixel Segmentation algorithm. For more detail about 36 | the algorithm please refer to the project webpage 37 | http://www.umiacs.umd.edu/~mingyliu 38 | or the following paper 39 | 40 | Ming-Yu Liu, Oncel Tuzel, Srikumar Ramalingam, and Rama Chellappa 41 | "Entropy Rate Superpixel Segmentation" Proceedings of the IEEE 42 | Conference on Computer Vision and Pattern Recognition(CVPR), 43 | Colorado Spring, June 2011. 44 | 45 | If you use this software, you should cite 46 | the aforementioned paper in any resulting publication. 47 | 48 | If you have any questions regarding the code please contact 49 | Ming-Yu Liu via . 50 | 51 | /******************************************************************** 52 | * Installation and usage * 53 | /******************************************************************** 54 | 55 | 1) Unzipped the files to $HOME_DIR 56 | 57 | 2) We have provided pre-compiled mex functions. You may not need to 58 | recompile the mex files again. If you need to recompile the codes. 59 | In the matlab command prompt, type >>make. This should do the job. 60 | 61 | 3) Type demo to see a demonstration of the usage of the code. 62 | 63 | mex_ers.mex : compute the superpixel segmentation for an input image. 64 | usage: 65 | [labels] = mex_ers(image,nC); 66 | [labels] = mex_ers(image,nC,lambda,sigma); 67 | Input: 68 | image : the input grey scale image 69 | nC : the number of desired superpixels 70 | lambda : the balancing parameter ( default = 0.5; ) 71 | sigma : the kernel bandwidth ( default = 5.0; ) 72 | Output: 73 | labels : the output image. Each pixel is labeled with the label 74 | of the superpixel it belongs to. Note that the labeling 75 | begins from 0 to nC-1 76 | 77 | /******************************************************************** 78 | * Revision History: * 79 | /******************************************************************** 80 | July 1, 2011; - First version for the general public 81 | 82 | -------------------------------------------------------------------------------- /GRSC/ERS/Entropy Rate Superpixel Segmentation/demo.fig: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WangJun2023/GRSC/714a19f3e37e69ad0409a9ad62c04bd70cda425f/GRSC/ERS/Entropy Rate Superpixel Segmentation/demo.fig -------------------------------------------------------------------------------- /GRSC/ERS/Entropy Rate Superpixel Segmentation/demo.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WangJun2023/GRSC/714a19f3e37e69ad0409a9ad62c04bd70cda425f/GRSC/ERS/Entropy Rate Superpixel Segmentation/demo.m -------------------------------------------------------------------------------- /GRSC/ERS/Entropy Rate Superpixel Segmentation/make.m: -------------------------------------------------------------------------------- 1 | % make erc matlab wrapper 2 | % Ming-Yu Liu 04/12/2010 3 | clear all; 4 | clc; 5 | % restoredefaultpath; 6 | 7 | mex -v -c ERS/MERCCInput.cpp 8 | mex -v -c ERS/MERCOutput.cpp 9 | mex -v -c ERS/MERCDisjointSet.cpp 10 | mex -v -c ERS/MERCFunctions.cpp 11 | mex -v -c ERS/MERCLazyGreedy.cpp 12 | mex ERS/mex_ers.cpp MERCCInput.o* MERCOutput.o* MERCDisjointSet.o* MERCFunctions.o* MERCLazyGreedy.o* 13 | 14 | delete *.o* 15 | 16 | -------------------------------------------------------------------------------- /GRSC/ERS/Entropy Rate Superpixel Segmentation/mex_ers.mexw64: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WangJun2023/GRSC/714a19f3e37e69ad0409a9ad62c04bd70cda425f/GRSC/ERS/Entropy Rate Superpixel Segmentation/mex_ers.mexw64 -------------------------------------------------------------------------------- /GRSC/ERS/Entropy Rate Superpixel Segmentation/random_color.m: -------------------------------------------------------------------------------- 1 | function [out] = random_color(img,labels,nC) 2 | % function [out] = random_color(img,labels,nC) 3 | % 4 | % From a superpixel segmentation, color each pixel randomly. 5 | % 6 | % INPUTS 7 | % img : the input image. 8 | % labels : the labeled image. 9 | % nC : the number of labels in the image; 10 | % OUTPUTS 11 | % out : the colored image. 12 | % 13 | % Copyright 2011, Ming-Yu Liu 14 | % 15 | [height width dim] = size(img); 16 | rimg = zeros(height,width); 17 | gimg = zeros(height,width); 18 | bimg = zeros(height,width); 19 | for i=0:(nC-1) 20 | idx = find(labels==i); 21 | rimg(idx) = rand(1); 22 | gimg(idx) = rand(1); 23 | bimg(idx) = rand(1); 24 | end 25 | out = img; 26 | out(:,:,1) = rimg; 27 | out(:,:,2) = gimg; 28 | out(:,:,3) = bimg; -------------------------------------------------------------------------------- /GRSC/ERS/Entropy Rate Superpixel Segmentation/seg2bmap.m: -------------------------------------------------------------------------------- 1 | function [bmap] = seg2bmap(seg,width,height) 2 | % [bmap] = seg2bmap(seg) 3 | % 4 | % From a segmentation, compute a binary boundary map with 1 pixel wide 5 | % boundaries. The boundary pixels are offset by 1/2 pixel towards the 6 | % origin from the actual segment boundary. 7 | % 8 | % INPUTS 9 | % seg Segments labeled from 1..k. 10 | % [width] Width of desired bmap, <= size(seg,2) 11 | % [height] Height of desired bmap, <= size(seg,1) 12 | % 13 | % OUTPUTS 14 | % bmap Binary boundary map. 15 | % 16 | % David Martin 17 | % January 2003 18 | 19 | if nargin<3, 20 | [height,width] = size(seg); 21 | end 22 | [h,w] = size(seg); 23 | 24 | % check width and height 25 | ar1 = width / height; 26 | ar2 = w / h; 27 | if width>w | height>h | abs(ar1-ar2)>0.01, 28 | error(sprintf('Can''t convert %dx%d seg to %dx%d bmap.',w,h,width,height)); 29 | end 30 | 31 | e = zeros(size(seg)); 32 | s = zeros(size(seg)); 33 | se = zeros(size(seg)); 34 | 35 | e(:,1:end-1) = seg(:,2:end); 36 | s(1:end-1,:) = seg(2:end,:); 37 | se(1:end-1,1:end-1) = seg(2:end,2:end); 38 | 39 | b = (seg~=e | seg~=s | seg~=se); 40 | b(end,:) = (seg(end,:)~=e(end,:)); 41 | b(:,end) = (seg(:,end)~=s(:,end)); 42 | b(end,end) = 0; 43 | 44 | if w==width & h==height, 45 | 46 | bmap = b; 47 | 48 | else 49 | 50 | bmap = zeros(height,width); 51 | for x = 1:w, 52 | for y = 1:h, 53 | if b(y,x), 54 | j = 1+floor((y-1)*height/h); 55 | i = 1+floor((x-1)*width/w); 56 | bmap(j,i) = 1; 57 | end 58 | end 59 | end 60 | 61 | end 62 | 63 | -------------------------------------------------------------------------------- /GRSC/ERS/common/Edge_ratio3.m: -------------------------------------------------------------------------------- 1 | function [Ratio]=Edge_ratio3(img) 2 | [m,n] = size(img); 3 | img = rgb2gray(img); 4 | BW = edge(img,'log'); 5 | ind = find(BW~=0); 6 | Len = length(ind); 7 | Ratio = Len/(m*n); 8 | end -------------------------------------------------------------------------------- /GRSC/ERS/common/class2label.m: -------------------------------------------------------------------------------- 1 | function indian_pines_map = class2label(predict_label,trainlabel_nl,randpp,indian_pines_gt,CTest,CTrain); 2 | indian_pines_map = indian_pines_gt; 3 | a = 1; 4 | at = 1; 5 | for i = 1:max(indian_pines_gt(:)) 6 | [v]=find(indian_pines_gt==i); 7 | cTest = CTest(i); 8 | index = randpp{i}; 9 | b = sum(CTest(1:i)); 10 | indian_pines_map(v(index(1:cTest))) = predict_label(a:b); 11 | 12 | 13 | bt = sum(CTrain(1:i)); 14 | indian_pines_map(v(index(cTest+1:end))) = trainlabel_nl(at:bt); 15 | at = bt+1; 16 | 17 | 18 | a = b+1; 19 | end 20 | 21 | -------------------------------------------------------------------------------- /GRSC/ERS/common/confusion_matrix_wei.m: -------------------------------------------------------------------------------- 1 | function [confusion, accuracy, TPR, FPR] = confusion_matrix_wei(class, c) 2 | % 3 | % class is the result of test data after classification 4 | % (1 x n) 5 | % 6 | % c is the label for testing data 7 | % (1 x len_c) 8 | % 9 | % 10 | 11 | class = class.'; 12 | c = c.'; 13 | 14 | n = length(class); 15 | c_len = length(c); 16 | 17 | if n ~= sum(c) 18 | disp('WRANING: wrong inputting!'); 19 | return; 20 | end 21 | 22 | 23 | % confusion matrix 24 | confusion = zeros(c_len, c_len); 25 | a = 0; 26 | for i = 1: c_len 27 | for j = (a + 1): (a + c(i)) 28 | confusion(i, class(j)) = confusion(i, class(j)) + 1; 29 | end 30 | a = a + c(i); 31 | end 32 | 33 | 34 | % True_positive_rate + False_positive_rate + accuracy 35 | TPR = zeros(1, c_len); 36 | FPR = zeros(1, c_len); 37 | for i = 1: c_len 38 | FPR(i) = confusion(i, i)/sum(confusion(:, i)); 39 | TPR(i) = confusion(i, i)/sum(confusion(i, :)); 40 | end 41 | accuracy = sum(diag(confusion))/sum(c); 42 | -------------------------------------------------------------------------------- /GRSC/ERS/common/cubseg.m: -------------------------------------------------------------------------------- 1 | function [labels,bmapOnImg] = cubseg(data,nC) 2 | 3 | 4 | [M,N,B]=size(data); 5 | Y_scale=scaleForSVM(reshape(data,M*N,B)); 6 | % Y_scale = reshape(indian_pines,M*N,B); 7 | Y=reshape(Y_scale,M,N,B); 8 | p = 1; 9 | [Y_pca] = pca(Y_scale, p); 10 | % Y_pca = mean(Y_scale,2); 11 | img = im2uint8(mat2gray(reshape(Y_pca', M, N, p))); 12 | 13 | % Ratio=Edge_ratio3(img); 14 | 15 | % sigma=0.05; 16 | % K = round(Ratio * 2000); 17 | grey_img = im2uint8(mat2gray(Y(:,:,30))); 18 | labels = mex_ers(double(img),nC); 19 | [height,width] = size(grey_img); 20 | [bmap] = seg2bmap(labels,width,height); 21 | bmapOnImg = img; 22 | idx = find(bmap>0); 23 | timg = grey_img; 24 | timg(idx) = 255; 25 | bmapOnImg(:,:,2) = timg; 26 | bmapOnImg(:,:,1) = grey_img; 27 | bmapOnImg(:,:,3) = grey_img; 28 | 29 | % figure; 30 | % imshow(bmapOnImg,[],'InitialMagnification','fit'); 31 | % imwrite(grey_img,'bmapOnImg.bmp') 32 | % PicPath = ['./' ,'Indian.jpg']; 33 | % print('-djpeg','-r1200', PicPath); 34 | % title('superpixel boundary map'); 35 | 36 | end 37 | 38 | % function [Ratio]=Edge_ratio3(img) 39 | % [m,n] = size(img); 40 | % % img = rgb2gray(img); 41 | % BW = edge(img,'log'); 42 | % % figure,imshow(BW) 43 | % ind = find(BW~=0); 44 | % Len = length(ind); 45 | % Ratio = Len/(m*n); 46 | % end -------------------------------------------------------------------------------- /GRSC/ERS/common/elm_kernel.m: -------------------------------------------------------------------------------- 1 | function [TrainingTime, TestingTime, TrainingAccuracy, TestingAccuracy,TY,pred_label] = elm_kernel(train_data, test_data, Elm_Type, Regularization_coefficient, Kernel_type, Kernel_para) 2 | 3 | % Usage: elm(TrainingData_File, TestingData_File, Elm_Type, NumberofHiddenNeurons, ActivationFunction) 4 | % OR: [TrainingTime, TestingTime, TrainingAccuracy, TestingAccuracy] = elm(TrainingData_File, TestingData_File, Elm_Type, NumberofHiddenNeurons, ActivationFunction) 5 | % 6 | % Input: 7 | % TrainingData_File - Filename of training data set 8 | % TestingData_File - Filename of testing data set 9 | % Elm_Type - 0 for regression; 1 for (both binary and multi-classes) classification 10 | % Regularization_coefficient - Regularization coefficient C 11 | % Kernel_type - Type of Kernels: 12 | % 'RBF_kernel' for RBF Kernel 13 | % 'lin_kernel' for Linear Kernel 14 | % 'poly_kernel' for Polynomial Kernel 15 | % 'wav_kernel' for Wavelet Kernel 16 | %Kernel_para - A number or vector of Kernel Parameters. eg. 1, [0.1,10]... 17 | % Output: 18 | % TrainingTime - Time (seconds) spent on training ELM 19 | % TestingTime - Time (seconds) spent on predicting ALL testing data 20 | % TrainingAccuracy - Training accuracy: 21 | % RMSE for regression or correct classification rate for classification 22 | % TestingAccuracy - Testing accuracy: 23 | % RMSE for regression or correct classification rate for classification 24 | % 25 | % MULTI-CLASSE CLASSIFICATION: NUMBER OF OUTPUT NEURONS WILL BE AUTOMATICALLY SET EQUAL TO NUMBER OF CLASSES 26 | % FOR EXAMPLE, if there are 7 classes in all, there will have 7 output 27 | % neurons; neuron 5 has the highest output means input belongs to 5-th class 28 | % 29 | % Sample1 regression: [TrainingTime, TestingTime, TrainingAccuracy, TestingAccuracy] = elm_kernel('sinc_train', 'sinc_test', 0, 1, ''RBF_kernel',100) 30 | % Sample2 classification: elm_kernel('diabetes_train', 'diabetes_test', 1, 1, 'RBF_kernel',100) 31 | % 32 | %%%% Authors: MR HONG-MING ZHOU AND DR GUANG-BIN HUANG 33 | %%%% NANYANG TECHNOLOGICAL UNIVERSITY, SINGAPORE 34 | %%%% EMAIL: EGBHUANG@NTU.EDU.SG; GBHUANG@IEEE.ORG 35 | %%%% WEBSITE: http://www.ntu.edu.sg/eee/icis/cv/egbhuang.htm 36 | %%%% DATE: MARCH 2012 37 | 38 | %%%%%%%%%%% Macro definition 39 | REGRESSION=0; 40 | CLASSIFIER=1; 41 | 42 | %%%%%%%%%%% Load training dataset 43 | %train_data=load(TrainingData_File); 44 | T=train_data(:,1)'; 45 | P=train_data(:,2:size(train_data,2))'; 46 | clear train_data; % Release raw training data array 47 | 48 | %%%%%%%%%%% Load testing dataset 49 | %test_data=load(TestingData_File); 50 | TV.T=test_data(:,1)'; 51 | TV.P=test_data(:,2:size(test_data,2))'; 52 | clear test_data; % Release raw testing data array 53 | 54 | C = Regularization_coefficient; 55 | NumberofTrainingData=size(P,2); 56 | NumberofTestingData=size(TV.P,2); 57 | 58 | if Elm_Type~=REGRESSION 59 | %%%%%%%%%%%% Preprocessing the data of classification 60 | sorted_target=sort(cat(2,T,TV.T),2); 61 | label=zeros(1,1); % Find and save in 'label' class label from training and testing data sets 62 | label(1,1)=sorted_target(1,1); 63 | j=1; 64 | for i = 2:(NumberofTrainingData+NumberofTestingData) 65 | if sorted_target(1,i) ~= label(1,j) 66 | j=j+1; 67 | label(1,j) = sorted_target(1,i); 68 | end 69 | end 70 | number_class=j; 71 | NumberofOutputNeurons=number_class; 72 | 73 | %%%%%%%%%% Processing the targets of training 74 | temp_T=zeros(NumberofOutputNeurons, NumberofTrainingData); 75 | for i = 1:NumberofTrainingData 76 | for j = 1:number_class 77 | if label(1,j) == T(1,i) 78 | break; 79 | end 80 | end 81 | temp_T(j,i)=1; 82 | end 83 | T=temp_T*2-1; 84 | 85 | %%%%%%%%%% Processing the targets of testing 86 | temp_TV_T=zeros(NumberofOutputNeurons, NumberofTestingData); 87 | for i = 1:NumberofTestingData 88 | for j = 1:number_class 89 | if label(1,j) == TV.T(1,i) 90 | break; 91 | end 92 | end 93 | temp_TV_T(j,i)=1; 94 | end 95 | TV.T=temp_TV_T*2-1; 96 | % end if of Elm_Type 97 | end 98 | 99 | %%%%%%%%%%% Training Phase %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 100 | tic; 101 | n = size(T,2); 102 | Omega_train = kernel_matrix(P',Kernel_type, Kernel_para); 103 | OutputWeight=((Omega_train+speye(n)/C)\(T')); 104 | TrainingTime=toc; 105 | 106 | %%%%%%%%%%% Calculate the training output 107 | Y=(Omega_train * OutputWeight)'; % Y: the actual output of the training data 108 | 109 | %%%%%%%%%%% Calculate the output of testing input 110 | tic; 111 | Omega_test = kernel_matrix(P',Kernel_type, Kernel_para,TV.P'); 112 | TY=(Omega_test' * OutputWeight)'; % TY: the actual output of the testing data 113 | TestingTime=toc; 114 | 115 | %%%%%%%%%% Calculate training & testing classification accuracy 116 | 117 | if Elm_Type == REGRESSION 118 | %%%%%%%%%% Calculate training & testing accuracy (RMSE) for regression case 119 | TrainingAccuracy=sqrt(mse(T - Y)); 120 | TestingAccuracy=sqrt(mse(TV.T - TY)); 121 | end 122 | 123 | if Elm_Type == CLASSIFIER 124 | %%%%%%%%%% Calculate training & testing classification accuracy 125 | MissClassificationRate_Training=0; 126 | MissClassificationRate_Testing=0; 127 | pred_label = []; 128 | 129 | [valt, indt] = max(T); 130 | [valy, indy] = max(Y); 131 | errorlabels = find(indt-indy~=0); 132 | MissClassificationRate_Training = length(errorlabels); 133 | 134 | % Ys = sort(Y); 135 | % Y12 = Ys(end-1,:)-Ys(end-2,:); 136 | 137 | % for i = 1 : size(T, 2) 138 | % [x, label_index_expected]=max(T(:,i)); 139 | % [x, label_index_actual]=max(Y(:,i)); 140 | % if label_index_actual~=label_index_expected 141 | % MissClassificationRate_Training=MissClassificationRate_Training+1; 142 | % end 143 | % end 144 | 145 | [valt, indt] = max(TV.T); 146 | [valy, indy] = max(TY); 147 | MissClassificationRate_Testing = length(errorlabels); 148 | pred_label = indy; 149 | 150 | TrainingAccuracy=1-MissClassificationRate_Training/size(T,2); 151 | % for i = 1 : size(TV.T, 2) 152 | % [x, label_index_expected]=max(TV.T(:,i)); 153 | % [x, label_index_actual]=max(TY(:,i)); 154 | % pred_label = [pred_label, label_index_actual]; 155 | % if label_index_actual~=label_index_expected 156 | % MissClassificationRate_Testing=MissClassificationRate_Testing+1; 157 | % end 158 | % end 159 | TestingAccuracy=1-MissClassificationRate_Testing/size(TV.T,2); 160 | end 161 | 162 | 163 | %%%%%%%%%%%%%%%%%% Kernel Matrix %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 164 | 165 | function omega = kernel_matrix(Xtrain,kernel_type, kernel_pars,Xt) 166 | 167 | nb_data = size(Xtrain,1); 168 | 169 | 170 | if strcmp(kernel_type,'RBF_kernel'), 171 | if nargin<4, 172 | XXh = sum(Xtrain.^2,2)*ones(1,nb_data); 173 | omega = XXh+XXh'-2*(Xtrain*Xtrain'); 174 | omega = exp(-omega./kernel_pars(1)); 175 | else 176 | XXh1 = sum(Xtrain.^2,2)*ones(1,size(Xt,1)); 177 | XXh2 = sum(Xt.^2,2)*ones(1,nb_data); 178 | omega = XXh1+XXh2' - 2*Xtrain*Xt'; 179 | omega = exp(-omega./kernel_pars(1)); 180 | end 181 | 182 | elseif strcmp(kernel_type,'lin_kernel') 183 | if nargin<4, 184 | omega = Xtrain*Xtrain'; 185 | else 186 | omega = Xtrain*Xt'; 187 | end 188 | 189 | elseif strcmp(kernel_type,'poly_kernel') 190 | if nargin<4, 191 | omega = (Xtrain*Xtrain'+kernel_pars(1)).^kernel_pars(2); 192 | else 193 | omega = (Xtrain*Xt'+kernel_pars(1)).^kernel_pars(2); 194 | end 195 | 196 | elseif strcmp(kernel_type,'wav_kernel') 197 | if nargin<4, 198 | XXh = sum(Xtrain.^2,2)*ones(1,nb_data); 199 | omega = XXh+XXh'-2*(Xtrain*Xtrain'); 200 | 201 | XXh1 = sum(Xtrain,2)*ones(1,nb_data); 202 | omega1 = XXh1-XXh1'; 203 | omega = cos(kernel_pars(3)*omega1./kernel_pars(2)).*exp(-omega./kernel_pars(1)); 204 | 205 | else 206 | XXh1 = sum(Xtrain.^2,2)*ones(1,size(Xt,1)); 207 | XXh2 = sum(Xt.^2,2)*ones(1,nb_data); 208 | omega = XXh1+XXh2' - 2*(Xtrain*Xt'); 209 | 210 | XXh11 = sum(Xtrain,2)*ones(1,size(Xt,1)); 211 | XXh22 = sum(Xt,2)*ones(1,nb_data); 212 | omega1 = XXh11-XXh22'; 213 | 214 | omega = cos(kernel_pars(3)*omega1./kernel_pars(2)).*exp(-omega./kernel_pars(1)); 215 | end 216 | end 217 | -------------------------------------------------------------------------------- /GRSC/ERS/common/getlabel.m: -------------------------------------------------------------------------------- 1 | function label=getlabel(classSize) 2 | 3 | label = []; 4 | for i=1:length(classSize) 5 | label = [label i*ones(1,classSize(i))]; 6 | end -------------------------------------------------------------------------------- /GRSC/ERS/common/label2class.m: -------------------------------------------------------------------------------- 1 | function label_fusion = label2class(labels_map,randpp,indian_pines_gt,CTest,trainnumber); 2 | 3 | a = 1; 4 | for i = 1:max(indian_pines_gt(:)) 5 | [v]=find(indian_pines_gt==i); 6 | cTest = CTest(i); 7 | index = randpp{i}; 8 | b = sum(CTest(1:i)); 9 | label_fusion(a:b) = labels_map(v(index(1:cTest))); 10 | a = b+1; 11 | end 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /GRSC/ERS/common/label2color2.m: -------------------------------------------------------------------------------- 1 | function RGB = label2color2(varargin) 2 | %LABEL2COLOR Convert Label Matrix to RGB Image with specified properties. 3 | % RGB = LABEL2COLOR(X) converts a label matrix X into a color RGB image 4 | % with default properties for the purpose of visualizing the labeled regions. 5 | % 6 | % RGB = LABEL2COLOR(X,PARAM1,VAL1,PARAM2,VAL2,___) converts a label matrix X, 7 | % specifying parameters and corresponding values that control various aspects of the RGB image. 8 | % Parameter case does not matter. 9 | % 10 | % PROPERTIES can be a comma-separated list of strings 11 | % 'ColorMap' - colormap (default 'jet') 12 | % 'ZeroColor' - zero color (background, uint8/double, default [0 0 0]) 13 | % 'EdgeColor' - edge color (uint8/double, default [255 255 255]) 14 | % 'EdgeWidth' - edge width (default 1) 15 | % 16 | % Class Support 17 | % ------------- 18 | % The input label matrix X can have any numeric class. It must contain 19 | % finite nonnegative integers. RGB is uint8. 20 | % 21 | % Example 1 22 | % --------- 23 | % RGB = label2color(X); 24 | % 25 | % Example 2 26 | % --------- 27 | % RGB = label2color(X,'colormap','summer'); 28 | % 29 | % Example 3 30 | % --------- 31 | % RGB = label2color(X,'ColorMap','hot','ZeroColor',[0 0 1],'EdgeColor',[1 1 1],'EdgeWidth',3); 32 | % 33 | % 34 | % 20/12/2015, ver 1.10, modify the code for 'EdgeWidth' 35 | % 21/12/2015, ver 1.20, support any numeric class 36 | % 22/12/2015, ver 1.21, remove 'assignin' 37 | % 22/12/2015, ver 1.22, 'numregion' should plus 1; set default 'ColorMap' to 'jet' 38 | % 22/12/2015, ver 1.23, add demo 39 | % 23/12/2015, ver 1.30, support custom colormap 40 | % 41 | % Jing Lou (?), http://www.loujing.com 42 | % 43 | 44 | narginchk(1, inf); 45 | 46 | paramPairs = varargin(2:end); 47 | assert(rem(length(paramPairs),2)==0, 'need param-value pairs'); 48 | for k = 1:2:length(paramPairs) 49 | validateattributes(paramPairs{k},{'char'},{'nonempty'}); 50 | % convert to lowercase 51 | paramPairs(k) = lower(paramPairs(k)); 52 | end 53 | 54 | %---------------------------------------------------------------------- 55 | % colormap 56 | numregion = 3*double(max(varargin{1}(:)))+1; 57 | ind_colormap = find(cellfun(@(s) strcmp('colormap',s), paramPairs), 1); 58 | if isempty(ind_colormap) 59 | cmap = feval('jet',numregion); 60 | else 61 | if ischar(paramPairs{ind_colormap+1}) 62 | cmap = feval(paramPairs{ind_colormap+1},numregion); 63 | else 64 | cmap = paramPairs{ind_colormap+1}; 65 | end 66 | end 67 | 68 | ind = find(cmap(:,3)==1);cmapnew = cmap;cmapnew(ind,3)=0;temp1 = cmapnew(ind,:); 69 | ind = find(cmap(:,2)==1);cmapnew = cmap;cmapnew(ind,2)=0;temp2 = cmapnew(ind,:); 70 | ind = find(cmap(:,3)==1);cmapnew = cmap;cmapnew(ind,1)=cmapnew(ind,2);cmapnew(ind,2)=0;temp3 = cmapnew(ind,:); 71 | ind = find(cmap(:,1)==1);cmapnew = cmap;cmapnew(ind,3)=cmapnew(ind,2);cmapnew(ind,2)=0;temp4 = cmapnew(ind,:); 72 | cmap = [cmap;temp1;temp2;temp3;temp4]; 73 | cmap(find(sum(cmap,2)==0),:)=[]; 74 | step = 3*size(cmap,1)/numregion; 75 | cmap = cmap(round(1:step:size(cmap,1)),:); 76 | 77 | %---------------------------------------------------------------------- 78 | % zero color 79 | ind_zerocolor = find(cellfun(@(s) strcmp('zerocolor',s), paramPairs), 1); 80 | if isempty(ind_zerocolor) 81 | zerocolor = [0 0 0]; 82 | else 83 | zerocolor = mat2gray(paramPairs{ind_zerocolor+1}); 84 | end 85 | RGB = label2rgb(varargin{1},cmap,zerocolor); 86 | 87 | %---------------------------------------------------------------------- 88 | % edge 89 | ind_edgecolor = find(cellfun(@(s) strcmp('edgecolor',s), paramPairs), 1); 90 | if isempty(ind_edgecolor) 91 | edgecolor = uint8([255 255 255]); 92 | else 93 | edgecolor = im2uint8(mat2gray(paramPairs{ind_edgecolor+1})); 94 | end 95 | 96 | ind_edgewidth = find(cellfun(@(s) strcmp('edgewidth',s), paramPairs), 1); 97 | if isempty(ind_edgewidth) 98 | edgewidth = 1; 99 | else 100 | edgewidth = paramPairs{ind_edgewidth+1}; 101 | end 102 | 103 | if ~isempty(ind_edgecolor) || ~isempty(ind_edgewidth) 104 | bwedge = edge(varargin{1},'roberts',0); 105 | if edgewidth > 1 106 | bwedge = imdilate(bwedge,ones(edgewidth)) > imerode(bwedge,ones(edgewidth)); 107 | end 108 | tmp = reshape(RGB,[],size(RGB,3)); 109 | tmp(logical(bwedge(:)),:) = repmat(edgecolor,sum(bwedge(:)),1); 110 | RGB = reshape(tmp,size(RGB)); 111 | end -------------------------------------------------------------------------------- /GRSC/ERS/common/label2noisylabel.m: -------------------------------------------------------------------------------- 1 | function paviaU_gt_nl = label2noisylabel(paviaU_gt,ratio); 2 | 3 | rand('seed',0); 4 | 5 | [m n] = size(paviaU_gt); 6 | classNum = max(paviaU_gt(:)); 7 | 8 | R = rand(m,n); 9 | R9 = ceil(classNum*rand(m,n)); 10 | paviaU_gt_nl = paviaU_gt; 11 | for i=1:m 12 | for j=1:n 13 | if paviaU_gt(i,j)~=0 14 | if R(i,j)<=ratio 15 | % paviaU_gt_nl(i,j) = R9(i,j); %noisy label includes itself 16 | 17 | temp = randperm(classNum); 18 | ind = find(temp==paviaU_gt(i,j)); 19 | temp(ind)=[]; 20 | paviaU_gt_nl(i,j) = temp(end); 21 | 22 | 23 | end 24 | end 25 | end 26 | end -------------------------------------------------------------------------------- /GRSC/ERS/common/label_fusion.m: -------------------------------------------------------------------------------- 1 | function [predict_label] = label_fusion(predict_labelS); 2 | 3 | for i=1:size(predict_labelS,1) 4 | temp = tabulate(predict_labelS(i,:)); 5 | [val ind] = max(temp(:,2)); 6 | predict_label(i,1) = temp(ind,1); 7 | end -------------------------------------------------------------------------------- /GRSC/ERS/common/pca.m: -------------------------------------------------------------------------------- 1 | function [mappedX, Y, mapping] = pca(X, no_dims) 2 | %PCA Perform the PCA algorithm 3 | % 4 | % [mappedX, mapping] = pca(X, no_dims) 5 | % 6 | % The function runs PCA on a set of datapoints X. The variable 7 | % no_dims sets the number of dimensions of the feature points in the 8 | % embedded feature space (no_dims >= 1, default = 2). 9 | % For no_dims, you can also specify a number between 0 and 1, determining 10 | % the amount of variance you want to retain in the PCA step. 11 | % The function returns the locations of the embedded trainingdata in 12 | % mappedX. Furthermore, it returns information on the mapping in mapping. 13 | % 14 | % 15 | 16 | % This file is part of the Matlab Toolbox for Dimensionality Reduction. 17 | % The toolbox can be obtained from http://homepage.tudelft.nl/19j49 18 | % You are free to use, change, or redistribute this code in any way you 19 | % want for non-commercial purposes. However, it is appreciated if you 20 | % maintain the name of the original author. 21 | % 22 | % (C) Laurens van der Maaten, Delft University of Technology 23 | 24 | temp=X; 25 | if ~exist('no_dims', 'var') 26 | no_dims = 2; 27 | end 28 | 29 | % Make sure data is zero mean 30 | mapping.mean = mean(X, 1); 31 | X = bsxfun(@minus, X, mapping.mean); 32 | 33 | % Compute covariance matrix 34 | if size(X, 2) < size(X, 1) 35 | C = cov(X); 36 | else 37 | C = (1 / size(X, 1)) * (X * X'); % if N>D, we better use this matrix for the eigendecomposition 38 | end 39 | 40 | % Perform eigendecomposition of C 41 | C(isnan(C)) = 0; 42 | C(isinf(C)) = 0; 43 | [M, lambda] = eig(C); 44 | 45 | % Sort eigenvectors in descending order 46 | [lambda, ind] = sort(diag(lambda), 'descend'); 47 | if no_dims < 1 48 | no_dims = find(cumsum(lambda ./ sum(lambda)) >= no_dims, 1, 'first'); 49 | disp(['Embedding into ' num2str(no_dims) ' dimensions.']); 50 | end 51 | if no_dims > size(M, 2) 52 | no_dims = size(M, 2); 53 | warning(['Target dimensionality reduced to ' num2str(no_dims) '.']); 54 | end 55 | M = M(:,ind(1:no_dims)); 56 | lambda = lambda(1:no_dims); 57 | 58 | % Apply mapping on the data 59 | if ~(size(X, 2) < size(X, 1)) 60 | M = bsxfun(@times, X' * M, (1 ./ sqrt(size(X, 1) .* lambda))'); % normalize in order to get eigenvectors of covariance matrix 61 | end 62 | mappedX = X * M; 63 | mappedX=mappedX'; 64 | Y=mappedX*temp; 65 | % Store information for out-of-sample extension 66 | mapping.M = M; 67 | mapping.lambda = lambda; 68 | -------------------------------------------------------------------------------- /GRSC/ERS/common/randlabelpropagation.m: -------------------------------------------------------------------------------- 1 | function [label_pre] = randlabelpropagation(trainlabel_nl, A, gamma) 2 | 3 | T = zeros(size(trainlabel_nl,2),max(trainlabel_nl)); 4 | for iCTrain=1:max(trainlabel_nl) 5 | ind = find(trainlabel_nl==iCTrain); 6 | T(ind,iCTrain)=1; 7 | end 8 | 9 | S = round(0.3*size(trainlabel_nl,2)); 10 | AA = inv(eye(size(A,1)) - 0.90 * A); 11 | 12 | for iter = 1:100 13 | Tr = T; 14 | temprand = randperm(size(Tr,1)); 15 | Tr(temprand(1:S),:)=0; 16 | Tr = [Tr;zeros(size(AA,1)-size(trainlabel_nl,2),size(Tr,2))]; 17 | F = AA * Tr; % classification function F = (I - \alpha S)^{-1}Y 18 | [~, label_temp] = max(F, [], 2); %simply checking which of elements is largest in each row 19 | label(iter,:) = label_temp(1:size(trainlabel_nl,2)); 20 | end 21 | [label_pre] = label_fusion(label'); 22 | label_pre = label_pre'; 23 | 24 | 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /GRSC/ERS/common/samplesdivide.m: -------------------------------------------------------------------------------- 1 | function [DataTest, DataTrain, CTest2, CTrain, Loc_test] = samplesdivide(indian_pines_corrected,indian_pines_gt,train,randpp); 2 | CTest2 = []; 3 | percent = 0.20; 4 | [m n p] = size(indian_pines_corrected); 5 | CTrain = [];CTest = []; 6 | DataTest = []; 7 | DataTrain = []; 8 | indian_pines_map = uint8(zeros(m,n)); 9 | data_col = reshape(indian_pines_corrected,m*n,p); 10 | [mm nn] = ind2sub([m n],1:m*n); 11 | 12 | Loc_test = []; 13 | for i = 1:max(indian_pines_gt(:)) 14 | ci = length(find(indian_pines_gt==i)); 15 | 16 | [v]=find(indian_pines_gt==i); 17 | 18 | datai = data_col(find(indian_pines_gt==i),:); 19 | if train>1 20 | cTrain = round(train); 21 | else 22 | cTrain = round(train*ci); 23 | end 24 | cTest = ci-cTrain; 25 | % cTest = round(0.2*ci); 26 | CTrain = [CTrain cTrain]; 27 | CTest = [CTest cTest]; 28 | % index = randperm(ci); 29 | index = randpp{i}; 30 | step = 1; 31 | DataTest = [DataTest; datai(index(1:step:cTest),:)]; 32 | CTest2 = [CTest2 size(datai(index(1:step:cTest),:),1)]; 33 | DataTrain = [DataTrain; datai(index(cTest+1:cTest+cTrain),:)]; 34 | Loc_test = [Loc_test; v(index(1:step:cTest))]; 35 | end 36 | % indian_pines_map = reshape(indian_pines_map,m,n); 37 | 38 | Normalize = max(max(DataTrain)); 39 | DataTrain = DataTrain./Normalize; 40 | DataTest = DataTest./Normalize; -------------------------------------------------------------------------------- /GRSC/ERS/common/scaleForSVM.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WangJun2023/GRSC/714a19f3e37e69ad0409a9ad62c04bd70cda425f/GRSC/ERS/common/scaleForSVM.m -------------------------------------------------------------------------------- /GRSC/ERS/common/supSimALL.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WangJun2023/GRSC/714a19f3e37e69ad0409a9ad62c04bd70cda425f/GRSC/ERS/common/supSimALL.m -------------------------------------------------------------------------------- /GRSC/Entrop.m: -------------------------------------------------------------------------------- 1 | function H = Entrop(X) 2 | G = 256; 3 | [L, N] = size(X); 4 | H = zeros(L, 1); 5 | minX = min(X(:)); 6 | maxX = max(X(:)); 7 | edge = linspace(minX, maxX, G); 8 | for i = 1 : L 9 | histX = hist(X(i, :), edge) / N; 10 | H (i) = - histX * log(histX + eps)'; 11 | end 12 | end 13 | -------------------------------------------------------------------------------- /GRSC/EuDist2.m: -------------------------------------------------------------------------------- 1 | function D = EuDist2(fea_a,fea_b,bSqrt) 2 | %EUDIST2 Efficiently Compute the Euclidean Distance Matrix by Exploring the 3 | %Matlab matrix operations. 4 | % 5 | % D = EuDist(fea_a,fea_b) 6 | % fea_a: nSample_a * nFeature 7 | % fea_b: nSample_b * nFeature 8 | % D: nSample_a * nSample_a 9 | % or nSample_a * nSample_b 10 | % 11 | % Examples: 12 | % 13 | % a = rand(500,10); 14 | % b = rand(1000,10); 15 | % 16 | % A = EuDist2(a); % A: 500*500 17 | % D = EuDist2(a,b); % D: 500*1000 18 | % 19 | % version 2.1 --November/2011 20 | % version 2.0 --May/2009 21 | % version 1.0 --November/2005 22 | % 23 | % Written by Deng Cai (dengcai AT gmail.com) 24 | 25 | 26 | if ~exist('bSqrt','var') 27 | bSqrt = 1; 28 | end 29 | 30 | if (~exist('fea_b','var')) || isempty(fea_b) 31 | aa = sum(fea_a.*fea_a,2); 32 | ab = fea_a*fea_a'; 33 | 34 | if issparse(aa) 35 | aa = full(aa); 36 | end 37 | 38 | D = bsxfun(@plus,aa,aa') - 2*ab; 39 | D(D<0) = 0; 40 | if bSqrt 41 | D = sqrt(D); 42 | end 43 | D = max(D,D'); 44 | else 45 | aa = sum(fea_a.*fea_a,2); 46 | bb = sum(fea_b.*fea_b,2); 47 | ab = fea_a*fea_b'; 48 | 49 | if issparse(aa) 50 | aa = full(aa); 51 | bb = full(bb); 52 | end 53 | 54 | D = bsxfun(@plus,aa,bb') - 2*ab; 55 | D(D<0) = 0; 56 | if bSqrt 57 | D = sqrt(D); 58 | end 59 | end 60 | 61 | -------------------------------------------------------------------------------- /GRSC/GRSC.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WangJun2023/GRSC/714a19f3e37e69ad0409a9ad62c04bd70cda425f/GRSC/GRSC.m -------------------------------------------------------------------------------- /GRSC/GRSC_main.m: -------------------------------------------------------------------------------- 1 | function [Z,S,obj] = GRSC_main(X, alpha, beta) 2 | alpha = 10^alpha; 3 | beta = 10^beta; 4 | 5 | [Z, ~] = InitializeSIGs(X'); 6 | 7 | distX = L2_distance_1(X,X); 8 | [distX1, idx] = sort(distX,2); 9 | 10 | [dim,num] = size(X); 11 | knn0 = 15; 12 | rr = zeros(num,1); 13 | for i = 1:num 14 | di = distX1(i,2:knn0+2); 15 | rr(i) = 0.5*(knn0*di(knn0+1)-sum(di(1:knn0))); 16 | end 17 | gamma = mean(rr); 18 | 19 | flag = 1; 20 | Q = zeros(dim); 21 | iter = 0; 22 | maxIter = 100; 23 | 24 | [S, ~] = InitializeSIGs(X); 25 | D = diag(sum(S)); 26 | L = D-S; 27 | 28 | while flag 29 | iter = iter + 1; 30 | 31 | %% update Z 32 | for i = 1 : dim 33 | Z_i = Z(i,:); 34 | Q(i,i) = 0.5/sqrt((Z_i*Z_i'+ eps)); 35 | end 36 | Z = inv(X*X'+ beta * X * L * X'+ alpha * Q)* X * X'; 37 | Z = Z - diag(diag(Z)); 38 | Z = max(Z,eps); 39 | 40 | %% update S 41 | U = Z' * X; 42 | distU = L2_distance_1(U,U); 43 | S = zeros(num); 44 | for i = 1 : num 45 | idxa0 = idx(i,2:knn0+1); 46 | dui = distU(i,idxa0); 47 | dxi = distX(i,idxa0); 48 | ad = -(dxi+0.5*beta*dui)/(2*gamma); 49 | S(i,idxa0) = EProjSimplex_new(ad); 50 | end 51 | S = (S+S')/2; 52 | 53 | D = diag(sum(S)); 54 | L = D-S; 55 | 56 | %% cal obj 57 | temp1 = norm(X'-X'*Z,'fro')^2; 58 | temp2 = sum(sum(L2_distance_1(X,X).* S))+ gamma * norm(S,'fro')^2; 59 | temp3 = alpha*L2_1(Z); 60 | temp4 = beta * trace(Z'*X*L*X'*Z); 61 | obj(iter) = temp1 + temp2 + temp3 + temp4; 62 | if (iter>2) && (abs((obj(iter-1)-obj(iter))/(obj(iter-1)))<1e-6 || iter>maxIter) 63 | flag = 0; 64 | end 65 | 66 | end 67 | 68 | end 69 | -------------------------------------------------------------------------------- /GRSC/InitializeSIGs.m: -------------------------------------------------------------------------------- 1 | function [S, D] = InitializeSIGs(X, k, issymmetric) 2 | % X: each column is a data point 3 | % k: number of neighbors 4 | % issymmetric: set S = (S+S')/2 if issymmetric=1 5 | % S: similarity matrix, each row is a data point 6 | % Ref: F. Nie, X. Wang, M. I. Jordan, and H. Huang, The constrained 7 | % Laplacian rank algorithm for graph-based clustering, in AAAI, 2016. 8 | 9 | if nargin < 3 10 | issymmetric = 1; 11 | end 12 | if nargin < 2 13 | k = 15; 14 | end 15 | 16 | [~, n] = size(X); 17 | D = L2_distance_1(X, X); 18 | [~, idx] = sort(D, 2); % sort each row 19 | 20 | S = zeros(n); 21 | for i = 1:n 22 | id = idx(i,2:k+2); 23 | di = D(i, id); 24 | S(i,id) = (di(k+1)-di)/(k*di(k+1)-sum(di(1:k))+eps); 25 | end 26 | 27 | if issymmetric == 1 28 | S = (S+S')/2; 29 | end -------------------------------------------------------------------------------- /GRSC/L2_1.m: -------------------------------------------------------------------------------- 1 | function [A]=L2_1(U) 2 | A=0; 3 | [n,~]=size(U); 4 | for i=1:n 5 | A=A+sqrt(U(i,:)*U(i,:)'); 6 | end 7 | end -------------------------------------------------------------------------------- /GRSC/L2_distance_1.m: -------------------------------------------------------------------------------- 1 | % compute squared Euclidean distance 2 | % ||A-B||^2 = ||A||^2 + ||B||^2 - 2*A'*B 3 | function d = L2_distance_1(a,b) 4 | % a,b: two matrices. each column is a data 5 | % d: distance matrix of a and b 6 | 7 | 8 | 9 | if (size(a,1) == 1) 10 | a = [a; zeros(1,size(a,2))]; 11 | b = [b; zeros(1,size(b,2))]; 12 | end 13 | 14 | aa=sum(a.*a); bb=sum(b.*b); ab=a'*b; 15 | d = repmat(aa',[1 size(bb,2)]) + repmat(bb,[size(aa,2) 1]) - 2*ab; 16 | 17 | d = real(d); 18 | d = max(d,0); 19 | 20 | % % force 0 on the diagonal? 21 | % if (df==1) 22 | % d = d.*(1-eye(size(d))); 23 | % end 24 | -------------------------------------------------------------------------------- /GRSC/LP.m: -------------------------------------------------------------------------------- 1 | 2 | function KH = LP(X) 3 | 4 | v = length(X); % view number 5 | n = size(X{1},2); 6 | 7 | for i = 1 :v 8 | X{i} = X{i}'; 9 | for j = 1:n 10 | X{i}(j,:) = ( X{i}(j,:) - mean( X{i}(j,:) ) ) / std( X{i}(j,:) ) ; 11 | end 12 | end 13 | 14 | KH = zeros(n,n,v); 15 | for idx = 1 : v 16 | A0 = constructW_PKN(X{idx}',10); 17 | A0 = A0-diag(diag(A0)); 18 | A10 = (A0+A0')/2; 19 | D10 = diag(1./sqrt(sum(A10, 2))); 20 | KH(:,:,idx) = D10*A10*D10; 21 | 22 | % dist = EuDist2(X{idx},X{idx},0); 23 | % sigma = mean(min(dist,[],2).^0.5)*2; 24 | % feaVec = exp(-dist/(2*sigma*sigma)); 25 | % KH(:,:,idx) = feaVec; 26 | end 27 | 28 | end -------------------------------------------------------------------------------- /GRSC/PridictLabel.m: -------------------------------------------------------------------------------- 1 | function idx = PridictLabel(T,K) 2 | 3 | nCluster = K ; 4 | Z = ( abs(T) + abs(T') ) / 2 ; 5 | idx = clu_ncut(Z,nCluster) ; 6 | % for j = 1 : rep 7 | % idx = clu_ncut(Z,nCluster) ; 8 | % acc = compacc(idx,gnd); 9 | % accAvg = accAvg+acc; 10 | % end 11 | % accAvg = accAvg/rep; 12 | 13 | end -------------------------------------------------------------------------------- /GRSC/SelectBandFromClusRes.m: -------------------------------------------------------------------------------- 1 | function [Y] = SelectBandFromClusRes(lable, K, img) 2 | % img: d*N 3 | Y = []; 4 | for i=1:K 5 | index = find(lable==i); 6 | tempdata = img(:,index); 7 | meandata = mean(tempdata,2); 8 | D = EuDist2(meandata',tempdata'); % 1*Nk 9 | [dumb idx] = sort(D,'ascend'); 10 | Y = [Y,index(idx(1))]; 11 | end -------------------------------------------------------------------------------- /GRSC/SpectralClustering.m: -------------------------------------------------------------------------------- 1 | function [C] = SpectralClustering(W, k, Type) 2 | %SPECTRALCLUSTERING Executes spectral clustering algorithm 3 | % Executes the spectral clustering algorithm defined by 4 | % Type on the adjacency matrix W and returns the k cluster 5 | % indicator vectors as columns in C. 6 | % If L and U are also called, the (normalized) Laplacian and 7 | % eigenvectors will also be returned. 8 | % 9 | % 'W' - Adjacency matrix, needs to be square 10 | % 'k' - Number of clusters to look for 11 | % 'Type' - Defines the type of spectral clustering algorithm 12 | % that should be used. Choices are: 13 | % 1 - Unnormalized 14 | % 2 - Normalized according to Shi and Malik (2000) 15 | % 3 - Normalized according to Ng, Jordan and Weiss (2002) 16 | % 17 | % References: 18 | % - Ulrike von Luxburg, "A Tutorial on Spectral Clustering", 19 | % Statistics and Computing 17 (4), 2007 20 | % 21 | % Author: Ingo Buerk 22 | % Year : 2011/2012 23 | % Bachelor Thesis 24 | 25 | % calculate degree matrix 26 | % d = (sum(W, 2)); 27 | % d = d ./ norm(d); 28 | % d = d.^2; 29 | % d = d ./ norm(d); 30 | % D = sparse(1:size(W, 1), 1:size(W, 2), d); 31 | % W = D*W*D; 32 | 33 | n = size(W, 1); 34 | degs = sum(W, 2); 35 | D = sparse(1:size(W, 1), 1:size(W, 2), degs); 36 | 37 | % compute unnormalized Laplacian 38 | L = D - W; 39 | 40 | % compute normalized Laplacian if needed 41 | switch Type 42 | case 2 43 | % avoid dividing by zero 44 | degs(degs == 0) = eps; 45 | % calculate inverse of D 46 | D_ = spdiags(1./degs, 0, size(D, 1), size(D, 2)); 47 | 48 | % calculate normalized Laplacian 49 | L = D_ * L; 50 | case 3 51 | % avoid dividing by zero 52 | degs(degs == 0) = eps; 53 | % calculate D^(-1/2) 54 | D_ = spdiags(1./(degs.^0.5), 0, size(D, 1), size(D, 2)); 55 | 56 | % calculate normalized Laplacian 57 | L = D_ * L * D_; 58 | end 59 | 60 | % L may be almost symmetric due to error in numerical calculation, so we make it symmetric. 61 | L = (L + L')/2; 62 | 63 | % compute the eigenvectors corresponding to the k smallest 64 | % eigenvalues 65 | try 66 | [U, ~] = eigs(L, k, 'SA');% eigs(L, speye(n), k, 'smallestreal'); 67 | catch ME 68 | warning('Error occur in eigs, the clustering result is wrong: \n%s', ME.message) 69 | U = rand(size(L,1), k); 70 | end 71 | % eigcut(U, data) 72 | 73 | % in case of the Jordan-Weiss algorithm, we need to normalize 74 | % the eigenvectors row-wise 75 | if Type == 3 76 | U_n = U ./ sqrt(sum(U.^2, 2)); 77 | end 78 | 79 | % now use the k-means algorithm to cluster U row-wise 80 | % C will be a n-by-1 matrix containing the cluster number for 81 | % each data point 82 | if any(isnan(U_n)) 83 | U_n(isnan(U_n)) = 0; 84 | end 85 | 86 | 87 | for rep = 1:20 88 | 89 | if n < 5000 90 | C = kmeans(U_n, k,'Replicates',30,'MaxIter',1000); 91 | elseif n < 10000 92 | C = kmeans(U_n, k,'Replicates',20,'MaxIter',1000); 93 | elseif n < 30000 94 | C = kmeans(U_n, k,'Replicates',5,'MaxIter',1000); 95 | else 96 | C = kmeans(U_n, k,'Replicates',3,'MaxIter',1000); 97 | end 98 | end 99 | 100 | end -------------------------------------------------------------------------------- /GRSC/cal_OA/KNN_Classifier/KNN_Classifier.m: -------------------------------------------------------------------------------- 1 | function [OA,MA,Kappa,test_SL,predict_label] = KNN_Classifier(Dataset, band_set) 2 | 3 | [train_X,train_labels,test_X,test_labels,test_SL] = randdivide(Dataset); 4 | test_size = size(test_labels, 1); 5 | C = max(test_labels); 6 | bs_train_X = train_X(:, band_set); 7 | bs_test_X = test_X(:, band_set); 8 | 9 | mdl = fitcknn(bs_train_X, train_labels, 'NumNeighbors',5, 'Standardize',1); 10 | predict_label = predict(mdl,bs_test_X); 11 | OA = 0; 12 | cmat = confusionmat(test_labels, predict_label); 13 | for i = 1 : size(predict_label, 1) 14 | if predict_label(i) == test_labels(i) 15 | OA = OA + 1; 16 | end 17 | end 18 | OA = OA / size(predict_label, 1); 19 | sum_accu = 0; 20 | for i = 1 : C 21 | sum_accu = sum_accu + cmat(i, i) / sum(cmat(i, :), 2); 22 | end 23 | MA = sum_accu / C; 24 | Pe = 0; 25 | for i = 1 : C 26 | Pe = Pe + cmat(i, :) * cmat(:, i); 27 | end 28 | Pe = Pe / (test_size*test_size); 29 | Kappa = (OA - Pe) / (1 - Pe); 30 | 31 | end 32 | 33 | -------------------------------------------------------------------------------- /GRSC/cal_OA/KSRC_Classifier/KSRC_Classifier.m: -------------------------------------------------------------------------------- 1 | function [OA,MA,Kappa,test_SL,pred] = KSRC_Classifier(Dataset,band_set, Train, Test) 2 | 3 | NewData.ground_truth = Dataset.ground_truth; 4 | NewData.A = Dataset.A(:,:,band_set); 5 | 6 | sz = size(NewData.A); 7 | rows = sz(1); 8 | cols = sz(2); 9 | img = reshape(NewData.A, [prod(sz(1:2)) sz(3)]); 10 | img = img'; 11 | % img_gt = NewData.ground_truth(:); 12 | 13 | train_ratio = Dataset.train_ratio; 14 | [GroundT(:,1), ~, GroundT(:,2)] = find(Dataset.ground_truth(:)); 15 | GroundT = sortrows(GroundT,2); 16 | no_train = round(size(GroundT,1) * train_ratio); 17 | GroundT=GroundT'; 18 | no_classes = max(max(Dataset.ground_truth)); 19 | indexes=train_test_random_new(GroundT(2,:),fix(no_train/no_classes),no_train); 20 | train_SL = GroundT(:,indexes); 21 | test_SL = GroundT; 22 | test_SL(:,indexes) = []; 23 | Train.idx = train_SL(1,:); 24 | Train.lab = train_SL(2,:); 25 | Test.idx = test_SL(1,:); 26 | Test.lab = test_SL(2,:); 27 | 28 | 29 | % parameters 30 | mu = 1e-3; lam = 1e-4; wind = 5; 31 | sig = sqrt(0.5 ./ 40); sig0 = sqrt(0.5 ./ 0.7); 32 | 33 | p.mu = mu; p.lam = lam; 34 | 35 | alg = 1; 36 | 37 | if alg == 1 38 | % MF kernel 39 | [Ktrain, Ktest] = ker_mm(img, rows, cols, Train.idx, Test.idx, wind, sig, [80 80], 1); 40 | else 41 | % NF kernel 42 | [Ktrain, Ktest] = ker_lwm(img, rows, cols, Train.idx, Test.idx, wind, sig, sig0, [80 80], 1); 43 | end 44 | 45 | AtX = Ktest; AtA = Ktrain; 46 | S = SpRegKL1(AtX, AtA, p); 47 | pred = class_ker_pred(AtX, AtA, S, Test.lab, Train.lab); 48 | test = Test.lab; 49 | 50 | test = test'; 51 | pred = pred'; 52 | test_size = size(test, 1); 53 | cmat = confusionmat(test, pred); 54 | OA = length(find(pred == test)) / length(test); 55 | sum_accu = 0; 56 | for i = 1 : no_classes 57 | sum_accu = sum_accu + cmat(i, i) / sum(cmat(i, :), 2); 58 | end 59 | MA = sum_accu / no_classes; 60 | Pe = 0; 61 | for i = 1 : no_classes 62 | Pe = Pe + cmat(i, :) * cmat(:, i); 63 | end 64 | Pe = Pe / (test_size*test_size); 65 | Kappa = (OA - Pe) / (1 - Pe); 66 | 67 | end 68 | 69 | -------------------------------------------------------------------------------- /GRSC/cal_OA/KSRC_Classifier/RBF.m: -------------------------------------------------------------------------------- 1 | function K = RBF(X, X2, sigma, block) 2 | % RBF kernel 3 | % 2012_09_20 4 | n1 = size(X,2); n2 = size(X2,2); 5 | if (n1 < block) && (n2 < block), 6 | K = ker_rbf(X, X2, sigma); 7 | else 8 | K = zeros(n1, n2); 9 | n1_block = ceil(n1/block); n2_block = ceil(n2/block); 10 | for i = 1 : n1_block 11 | n1_idx = (i-1)*block+1 : min(i*block, n1); 12 | for j = 1 : n2_block 13 | n2_idx = (j-1)*block+1 : min(j*block, n2); 14 | K(n1_idx, n2_idx) = ker_rbf(X(:,n1_idx), X2(:,n2_idx), sigma); 15 | end 16 | end 17 | end 18 | end 19 | 20 | function K = ker_rbf(X, X2, sigma) 21 | % RBF kernel 22 | n1sq = sum(X.^2); n1 = size(X,2); 23 | n2sq = sum(X2.^2); n2 = size(X2,2); 24 | D = (ones(n2,1)*n1sq)' + ones(n1,1)*n2sq - 2 * X' * X2; 25 | K = exp(-D/(2*sigma^2)); 26 | end -------------------------------------------------------------------------------- /GRSC/cal_OA/KSRC_Classifier/README.md: -------------------------------------------------------------------------------- 1 | # KSRC 2 | Spatial-spectral kernel sparse representation for hyperspectral image classification, JSTARS, 2013 3 | -------------------------------------------------------------------------------- /GRSC/cal_OA/KSRC_Classifier/SpRegKL1.m: -------------------------------------------------------------------------------- 1 | function S = SpRegKL1(AtX, AtA, param) 2 | % kernel sparse regression 3 | % 2012_10_03 4 | 5 | J = size(AtA,2); 6 | 7 | % param set 8 | if ~isfield(param,'lam'), lam = 1E-3; else lam = param.lam; end 9 | if ~isfield(param,'mu'), mu = 1; else mu = param.mu; end 10 | if ~isfield(param,'tol'), tol = 1E-3; else tol = param.tol; end 11 | if ~isfield(param,'maxit'), maxit = 1000; else maxit = param.maxit; end 12 | if ~isfield(param, 'verb'), verb = 1; else verb = param.verb; end 13 | if ~isfield(param, 'exact'), exact = 1; else exact = param.exact; end 14 | 15 | if exact == 1, 16 | % inital 17 | s = zeros(size(AtX)); d = s; 18 | F = inv(AtA+mu*eye(J)); 19 | S0 = F * AtX; 20 | % algorithm 21 | for iter = 1 : maxit, 22 | S = F * (AtX + mu*(s+d)); 23 | s = soft(S-d, lam/mu); 24 | d = d - (S - s); 25 | if check_stop(iter, S, S0, tol), 26 | break; 27 | end 28 | print_state(iter, verb); 29 | S0 = S; 30 | end 31 | else 32 | % 33 | end 34 | 35 | if verb == 1, 36 | disp(strcat(['SpRegKL1 Iterations:', num2str(iter)])); 37 | end 38 | end 39 | 40 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 41 | function z = soft(u, a) 42 | z = sign(u) .* max(abs(u)-a, 0); 43 | end 44 | 45 | function stop = check_stop(iter, S, S0, tol) 46 | stop = 0; 47 | if iter > 1, 48 | dtol = sqrt(sum(sum((S-S0).^2)) / sum(sum(S0.^2))); 49 | if dtol < tol, stop = 1; end 50 | end 51 | end 52 | 53 | function print_state(iter, verb) 54 | if rem(iter,10)==0, 55 | if verb == 1, fprintf('.'); end 56 | end 57 | end 58 | 59 | function val = fun_val(AtA, AtX, S, lam) 60 | SSt = S * S'; 61 | val = 0.5 * sum(sum(AtA.*SSt)) - sum(sum(AtX.*S)) + lam * sum(sum(abs(S))); 62 | end -------------------------------------------------------------------------------- /GRSC/cal_OA/KSRC_Classifier/class_eval.m: -------------------------------------------------------------------------------- 1 | function opt = class_eval(dat_lab, lab) 2 | % modified 20120825 3 | cls = unique(lab); 4 | nClass = length(cls); 5 | opt.ratio = zeros(1,nClass); opt.OA = 0; opt.num = zeros(nClass); 6 | l = 1; 7 | for k = cls 8 | idx = (lab == k); 9 | k_cls = sum(idx); 10 | k_crt = sum(dat_lab(idx) == k); 11 | opt.ratio(l) = k_crt / k_cls * 100; 12 | opt.OA = opt.OA + k_crt; 13 | j = 1; 14 | for i = cls 15 | opt.num(j,l) = sum(dat_lab(idx)==i); 16 | j = j + 1; 17 | end 18 | l = l + 1; 19 | end 20 | opt.OA = opt.OA / length(lab) * 100; 21 | 22 | n = sum(opt.num(:)); % Total number of samples 23 | PA = sum(diag(opt.num)); 24 | 25 | % Estimated Overall Cohen's Kappa (suboptimal implementation) 26 | npj = sum(opt.num,1); 27 | nip = sum(opt.num,2); 28 | PE = npj*nip; 29 | if (n*PA-PE) == 0 && (n^2-PE) == 0 30 | % Solve indetermination 31 | opt.Kappa = 1; 32 | else 33 | opt.Kappa = (n*PA-PE)/(n^2-PE); 34 | end 35 | end -------------------------------------------------------------------------------- /GRSC/cal_OA/KSRC_Classifier/class_ker_pred.m: -------------------------------------------------------------------------------- 1 | function [pred, dist, sci] = class_ker_pred(AtX, AtA, coef, test_lab, dict_lab) 2 | % ||Px - PA_i * s^i|| 3 | % modified 20120825 4 | cls = unique(dict_lab); 5 | nClass = length(cls); nTest = length(test_lab); 6 | pred = zeros(1,nTest); dist = zeros(nClass,nTest); 7 | sci = zeros(1,nTest); 8 | for i = 1 : nTest 9 | err = zeros(1,nClass); isci = zeros(1,nClass); 10 | j = 1; 11 | for k = cls 12 | kDict = (dict_lab == k); 13 | % xt * AtA * x - 2 * xt * AtX 14 | err(j) = coef(kDict,i)' * AtA(kDict, kDict) * coef(kDict,i) - 2*coef(kDict,i)'*AtX(kDict,i); 15 | isci(j) = sum(abs(coef(kDict,i))); 16 | j = j + 1; 17 | end 18 | sci(i) = (nClass*max(isci)/sum(abs(coef(:,i))) - 1) / (nClass - 1); 19 | [ ~, b] = min(err); pred(i) = cls(b); 20 | dist(:,i) = err; 21 | end 22 | end -------------------------------------------------------------------------------- /GRSC/cal_OA/KSRC_Classifier/ker_lwm.m: -------------------------------------------------------------------------------- 1 | function [Ktrain, Ktest] = ker_lwm(img, rows, cols, trainidx, testidx, wind, sig, filt, blo, mx) 2 | % local weighted mean kernel 3 | % 2012-12-14 4 | 5 | train_size = length(trainidx); 6 | train_idx = zeros(train_size, 1); train_idx(1:end) = trainidx; 7 | idx = union(trainidx, testidx); 8 | test_size = length(idx); 9 | test_idx = zeros(test_size, 1); test_idx(1:end) = idx; 10 | img_idx = zeros(rows*cols,1); img_idx(idx) = 1 : test_size; 11 | trainidx = img_idx(trainidx); testidx = img_idx(testidx); 12 | 13 | % return value 14 | K = zeros(train_size, test_size); 15 | 16 | train_pos(:,1) = mod(train_idx-1,rows) + 1; train_pos(:,2) = (train_idx-train_pos(:,1)) / rows + 1; 17 | test_pos(:,1) = mod(test_idx-1,rows) + 1; test_pos(:,2) = (test_idx-test_pos(:,1)) / rows + 1; 18 | nWind = (2*wind + 1)^2; 19 | w_train_size = zeros(train_size, 1); w_test_size = zeros(test_size, 1); 20 | row_blo = ceil(rows./blo); col_blo = ceil(cols./blo); 21 | block = row_blo .* col_blo; 22 | r1_block = mod((1:block(1))-1,row_blo(1)) + 1; c1_block = ((1:block(1))-r1_block) / row_blo(1) + 1; 23 | r2_block = mod((1:block(2))-1,row_blo(2)) + 1; c2_block = ((1:block(2))-r2_block) / row_blo(2) + 1; 24 | 25 | % location of the pixels in the window 26 | [ijw_train, ijw_test] = compute_location; 27 | 28 | % local weight 29 | [train_weight, test_weight] = compute_weight; 30 | 31 | %========================================================================== 32 | fprintf('%3d',0); 33 | for bi = 1 : block(1), % out block 34 | fprintf('\b\b\b%3d', bi); 35 | [train_rc, con] = block_by_block(bi, blo(1), r1_block, c1_block, rows, cols, train_pos); 36 | if con == 1, continue; end 37 | if sum(train_rc) == 0, continue; end 38 | [~, b_train_size, b_w_train, b_train_widx, b_w_train_size] = set_block_train; 39 | b_trainw = img(:,b_train_widx); b_train_weight = train_weight(:,train_rc); 40 | for bj = 1 : block(2), % inner block 41 | %disp([num2str(bi) ', ' num2str(bj) ', ' num2str(block(1)) ',' num2str(block(2))]); 42 | [test_rc, con] = block_by_block(bj, blo(2), r2_block, c2_block, rows, cols, test_pos); 43 | if con == 1, continue; end 44 | if sum(test_rc) == 0, continue; end 45 | [~, b_test_size, b_w_test, b_test_widx, b_w_test_size] = set_block_test; 46 | b_testw = img(:,b_test_widx); b_test_weight = test_weight(:,test_rc); 47 | %disp([b_train_wsize b_test_wsize b_train_size b_test_size]); 48 | % local weighted mean kernel 49 | b_Kbuf = kernelmatrix(b_trainw, b_testw, sig); 50 | b_K = compute_kernel; 51 | % normalize 52 | b_s_train_weight = sum(b_train_weight); b_s_test_weight = sum(b_test_weight); 53 | b_K = bsxfun(@times, b_K, (1./b_s_train_weight)'); b_K = bsxfun(@times, b_K, 1./b_s_test_weight); 54 | K(train_rc, test_rc) = b_K; 55 | end 56 | end 57 | fprintf('\n'); 58 | %-------------------------------------------------------------------------- 59 | Ktrain = K(:,trainidx); Ktest = K(:,testidx); 60 | %========================================================================== 61 | function [ijw_train, ijw_test] = compute_location 62 | ijw_train = zeros(nWind, train_size); 63 | i = train_pos(:,1); j = train_pos(:,2); 64 | iw_begin = max(i-wind, 1); iw_end = min(i+wind, rows); 65 | jw_begin = max(j-wind, 1); jw_end = min(j+wind, cols); 66 | for n = 1 : train_size, 67 | iw = iw_begin(n) : iw_end(n); jw = jw_begin(n) : jw_end(n); 68 | iw_size = length(iw); jw_size = length(jw); 69 | iw = repmat(iw', 1, jw_size); jw = repmat(jw, iw_size, 1); 70 | ijw = iw + (jw - 1) * rows; 71 | ijw_train(1:iw_size*jw_size, n) = ijw(:); 72 | w_train_size(n) = iw_size*jw_size; 73 | end 74 | ijw_test = zeros(nWind, test_size); 75 | i = test_pos(:,1); j = test_pos(:,2); 76 | iw_begin = max(i-wind, 1); iw_end = min(i+wind, rows); 77 | jw_begin = max(j-wind, 1); jw_end = min(j+wind, cols); 78 | for n = 1 : test_size, 79 | iw = iw_begin(n) : iw_end(n); jw = jw_begin(n) : jw_end(n); 80 | iw_size = length(iw); jw_size = length(jw); 81 | iw = repmat(iw', 1, jw_size); jw = repmat(jw, iw_size, 1); 82 | ijw = iw + (jw - 1) * rows; 83 | ijw_test(1:iw_size*jw_size, n) = ijw(:); 84 | w_test_size(n) = iw_size*jw_size; 85 | end 86 | end 87 | function [b_train_idx, b_train_size, b_w_train, b_train_widx, b_w_train_size] = set_block_train 88 | % set definition of block 89 | b_train_idx = train_idx(train_rc); b_train_size = length(b_train_idx); 90 | b_ijw_train = ijw_train(:,train_rc); b_w_train_size = w_train_size(train_rc); 91 | b_train_widx = unique(b_ijw_train); b_train_widx = b_train_widx(b_train_widx>0); 92 | b_train_wsize = length(b_train_widx); 93 | % new location of the pixels in the window 94 | img_idx = zeros(rows*cols,1); img_idx(b_train_widx) = 1 : b_train_wsize; 95 | b_w_train = b_ijw_train; b_w_train(b_w_train>0) = img_idx(b_w_train(b_w_train>0)); 96 | end 97 | function [b_test_idx, b_test_size, b_w_test, b_test_widx, b_w_test_size] = set_block_test 98 | % set definition of block 99 | b_test_idx = test_idx(test_rc); b_test_size = length(b_test_idx); 100 | b_ijw_test = ijw_test(:,test_rc); b_w_test_size = w_test_size(test_rc); 101 | b_test_widx = unique(b_ijw_test); b_test_widx = b_test_widx(b_test_widx>0); 102 | b_test_wsize = length(b_test_widx); 103 | % new location of the pixels in the window 104 | img_idx = zeros(rows*cols,1); img_idx(b_test_widx) = 1 : b_test_wsize; 105 | b_w_test = b_ijw_test; b_w_test(b_w_test>0) = img_idx(b_w_test(b_w_test>0)); 106 | end 107 | function [train_weight, test_weight] = compute_weight 108 | train_weight = zeros(nWind,train_size); test_weight = zeros(nWind,test_size); 109 | for b = 1 : block(1), 110 | [train_rc, con] = block_by_block(b, blo(1), r1_block, c1_block, rows, cols, train_pos); 111 | if con == 1, continue; end 112 | [b_train_idx, b_train_size, b_w_train, b_train_widx, b_w_train_size] = set_block_train; 113 | b_train_weight = zeros(nWind, b_train_size); 114 | b_train = img(:,b_train_idx); b_trainw = img(:,b_train_widx); 115 | b_trainbuf = kernelmatrix(b_train, b_trainw, filt); 116 | for n = 1 : b_train_size, 117 | x = b_w_train(1:b_w_train_size(n), n); 118 | KK = b_trainbuf(n, x); 119 | b_train_weight(1:b_w_train_size(n), n) = KK; 120 | end 121 | train_weight(:,train_rc) = b_train_weight; 122 | end 123 | clear b_train b_trainw b_trainbuf; 124 | for b = 1 : block(2), 125 | [test_rc, con] = block_by_block(b, blo(2), r2_block, c2_block, rows, cols, test_pos); 126 | if con == 1, continue; end 127 | [b_test_idx, b_test_size, b_w_test, b_test_widx, b_w_test_size] = set_block_test; 128 | b_test_weight = zeros(nWind, b_test_size); 129 | b_test = img(:,b_test_idx); b_testw = img(:,b_test_widx); 130 | b_testbuf = kernelmatrix(b_test, b_testw, filt); 131 | for m = 1 : b_test_size, 132 | x = b_w_test(1:b_w_test_size(m), m); 133 | KK = b_testbuf(m, x); 134 | b_test_weight(1:b_w_test_size(m), m) = KK; 135 | end 136 | test_weight(:,test_rc) = b_test_weight; 137 | end 138 | clear b_test b_testw b_testbuf; 139 | end 140 | function b_K = compute_kernel 141 | if mx == 1, 142 | b_K = mex_pk_lwm(b_Kbuf, ... 143 | b_w_train, b_w_train_size, b_train_weight, ... 144 | b_w_test, b_w_test_size, b_test_weight, ... 145 | 1); 146 | else 147 | b_K = zeros(b_train_size, b_test_size); 148 | for n = 1 : b_train_size, 149 | x1 = b_w_train(1:b_w_train_size(n), n); 150 | K1 = b_Kbuf(x1,:); 151 | K1 = bsxfun(@times, K1, b_train_weight(1:b_w_train_size(n), n)); 152 | for m = 1 : b_test_size, 153 | x2 = b_w_test(1:b_w_test_size(m), m); 154 | K2 = K1(:, x2); 155 | K2 = bsxfun(@times, K2, b_test_weight(1:b_w_test_size(m), m)'); 156 | b_K(n,m) = sum(sum(K2)); 157 | end 158 | end 159 | end 160 | end 161 | end 162 | 163 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 164 | function K = kernelmatrix(X, X2, sig) 165 | % RBF 166 | n1sq = sum(X.^2); n1 = size(X,2); 167 | n2sq = sum(X2.^2); n2 = size(X2,2); 168 | D = n1sq'*ones(1,n2) + ones(n1,1)*n2sq - 2 * X' * X2; 169 | K = exp(-1 / (2*sig^2) * D); 170 | end 171 | 172 | function [train_rc, con] = block_by_block(b, blo, r_block, c_block, rows, cols, train_pos) 173 | con = 0; 174 | br = r_block(b); bc = c_block(b); 175 | br_begin = 1 + (br-1) * blo; br_end = min(rows, br*blo); if br_begin > br_end, con = 1; end 176 | bc_begin = 1 + (bc-1) * blo; bc_end = min(cols, bc*blo); if bc_begin > bc_end, con = 1; end 177 | train_rc = (train_pos(:,1) >= br_begin) & (train_pos(:,1) <= br_end) & (train_pos(:,2) >= bc_begin) & (train_pos(:,2) <= bc_end); 178 | end -------------------------------------------------------------------------------- /GRSC/cal_OA/KSRC_Classifier/ker_mm.m: -------------------------------------------------------------------------------- 1 | function [Ktrain, Ktest] = ker_mm(img, rows, cols, trainidx, testidx, wind, sig, blo, mx) 2 | % mean kernel 3 | % 2012-12-14 4 | 5 | train_size = length(trainidx); 6 | train_idx = zeros(train_size, 1); train_idx(1:end) = trainidx; 7 | idx = union(trainidx, testidx); 8 | test_size = length(idx); 9 | test_idx = zeros(test_size, 1); test_idx(1:end) = idx; 10 | img_idx = zeros(rows*cols,1); img_idx(idx) = 1 : test_size; 11 | trainidx = img_idx(trainidx); testidx = img_idx(testidx); 12 | 13 | % return value 14 | K = zeros(train_size, test_size); 15 | 16 | train_pos(:,1) = mod(train_idx-1,rows) + 1; train_pos(:,2) = (train_idx-train_pos(:,1)) / rows + 1; 17 | test_pos(:,1) = mod(test_idx-1,rows) + 1; test_pos(:,2) = (test_idx-test_pos(:,1)) / rows + 1; 18 | nWind = (2*wind + 1)^2; 19 | w_train_size = zeros(train_size, 1); w_test_size = zeros(test_size, 1); 20 | row_blo = ceil(rows./blo); col_blo = ceil(cols./blo); 21 | block = row_blo .* col_blo; 22 | r1_block = mod((1:block(1))-1,row_blo(1)) + 1; c1_block = ((1:block(1))-r1_block) / row_blo(1) + 1; 23 | r2_block = mod((1:block(2))-1,row_blo(2)) + 1; c2_block = ((1:block(2))-r2_block) / row_blo(2) + 1; 24 | 25 | % location of the pixels in the window 26 | [ijw_train, ijw_test] = compute_location; 27 | 28 | %========================================================================== 29 | fprintf('%3d',0); 30 | for bi = 1 : block(1), % out block 31 | fprintf('\b\b\b%3d', bi); 32 | [train_rc, con] = block_by_block(bi, blo(1), r1_block, c1_block, rows, cols, train_pos); 33 | if con == 1, continue; end 34 | if sum(train_rc) == 0, continue; end 35 | [~, b_train_size, b_w_train, b_train_widx, b_w_train_size] = set_block_train; 36 | b_trainw = img(:,b_train_widx); 37 | for bj = 1 : block(2), % inner block 38 | %disp([num2str(bi) ', ' num2str(bj) ', ' num2str(block(1)) ',' num2str(block(2))]); 39 | [test_rc, con] = block_by_block(bj, blo(2), r2_block, c2_block, rows, cols, test_pos); 40 | if con == 1, continue; end 41 | if sum(test_rc) == 0, continue; end 42 | [~, b_test_size, b_w_test, b_test_widx, b_w_test_size] = set_block_test; 43 | b_testw = img(:,b_test_widx); 44 | %disp([b_train_wsize b_test_wsize b_train_size b_test_size]); 45 | % mean kernel 46 | b_Kbuf = kernelmatrix(b_trainw, b_testw, sig); 47 | b_K = compute_kernel; 48 | % normalize 49 | b_K = b_K .* (1/nWind^2); 50 | K(train_rc, test_rc) = b_K; 51 | end 52 | end 53 | fprintf('\n'); 54 | %-------------------------------------------------------------------------- 55 | Ktrain = K(:,trainidx); Ktest = K(:,testidx); 56 | %========================================================================== 57 | function [ijw_train, ijw_test] = compute_location 58 | ijw_train = zeros(nWind, train_size); 59 | i = train_pos(:,1); j = train_pos(:,2); 60 | iw_begin = max(i-wind, 1); iw_end = min(i+wind, rows); 61 | jw_begin = max(j-wind, 1); jw_end = min(j+wind, cols); 62 | for n = 1 : train_size, 63 | iw = iw_begin(n) : iw_end(n); jw = jw_begin(n) : jw_end(n); 64 | iw_size = length(iw); jw_size = length(jw); 65 | iw = repmat(iw', 1, jw_size); jw = repmat(jw, iw_size, 1); 66 | ijw = iw + (jw - 1) * rows; 67 | ijw_train(1:iw_size*jw_size, n) = ijw(:); 68 | w_train_size(n) = iw_size*jw_size; 69 | end 70 | ijw_test = zeros(nWind, test_size); 71 | i = test_pos(:,1); j = test_pos(:,2); 72 | iw_begin = max(i-wind, 1); iw_end = min(i+wind, rows); 73 | jw_begin = max(j-wind, 1); jw_end = min(j+wind, cols); 74 | for n = 1 : test_size, 75 | iw = iw_begin(n) : iw_end(n); jw = jw_begin(n) : jw_end(n); 76 | iw_size = length(iw); jw_size = length(jw); 77 | iw = repmat(iw', 1, jw_size); jw = repmat(jw, iw_size, 1); 78 | ijw = iw + (jw - 1) * rows; 79 | ijw_test(1:iw_size*jw_size, n) = ijw(:); 80 | w_test_size(n) = iw_size*jw_size; 81 | end 82 | end 83 | function [b_train_idx, b_train_size, b_w_train, b_train_widx, b_w_train_size] = set_block_train 84 | % set definition of block 85 | b_train_idx = train_idx(train_rc); b_train_size = length(b_train_idx); 86 | b_ijw_train = ijw_train(:,train_rc); b_w_train_size = w_train_size(train_rc); 87 | b_train_widx = unique(b_ijw_train); b_train_widx = b_train_widx(b_train_widx>0); 88 | b_train_wsize = length(b_train_widx); 89 | % new location of the pixels in the window 90 | img_idx = zeros(rows*cols,1); img_idx(b_train_widx) = 1 : b_train_wsize; 91 | b_w_train = b_ijw_train; b_w_train(b_w_train>0) = img_idx(b_w_train(b_w_train>0)); 92 | end 93 | function [b_test_idx, b_test_size, b_w_test, b_test_widx, b_w_test_size] = set_block_test 94 | % set definition of block 95 | b_test_idx = test_idx(test_rc); b_test_size = length(b_test_idx); 96 | b_ijw_test = ijw_test(:,test_rc); b_w_test_size = w_test_size(test_rc); 97 | b_test_widx = unique(b_ijw_test); b_test_widx = b_test_widx(b_test_widx>0); 98 | b_test_wsize = length(b_test_widx); 99 | % new location of the pixels in the window 100 | img_idx = zeros(rows*cols,1); img_idx(b_test_widx) = 1 : b_test_wsize; 101 | b_w_test = b_ijw_test; b_w_test(b_w_test>0) = img_idx(b_w_test(b_w_test>0)); 102 | end 103 | function b_K = compute_kernel 104 | if mx == 1, 105 | b_K = mex_pk_mm(b_Kbuf, ... 106 | b_w_train, b_w_train_size, ... 107 | b_w_test, b_w_test_size, ... 108 | 1); 109 | else 110 | b_K = zeros(b_train_size, b_test_size); 111 | for n = 1 : b_train_size, 112 | x1 = b_w_train(1:b_w_train_size(n), n); 113 | K1 = b_Kbuf(x1,:); 114 | for m = 1 : b_test_size, 115 | x2 = b_w_test(1:b_w_test_size(m), m); 116 | K2 = K1(:, x2); 117 | b_K(n,m) = sum(sum(K2)); 118 | end 119 | end 120 | end 121 | end 122 | end 123 | 124 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 125 | function K = kernelmatrix(X, X2, sig) 126 | % RBF 127 | n1sq = sum(X.^2); n1 = size(X,2); 128 | n2sq = sum(X2.^2); n2 = size(X2,2); 129 | D = n1sq'*ones(1,n2) + ones(n1,1)*n2sq - 2 * X' * X2; 130 | K = exp(-1 / (2*sig^2) * D); 131 | end 132 | 133 | function [train_rc, con] = block_by_block(b, blo, r_block, c_block, rows, cols, train_pos) 134 | con = 0; 135 | br = r_block(b); bc = c_block(b); 136 | br_begin = 1 + (br-1) * blo; br_end = min(rows, br*blo); if br_begin > br_end, con = 1; end 137 | bc_begin = 1 + (bc-1) * blo; bc_end = min(cols, bc*blo); if bc_begin > bc_end, con = 1; end 138 | train_rc = (train_pos(:,1) >= br_begin) & (train_pos(:,1) <= br_end) & (train_pos(:,2) >= bc_begin) & (train_pos(:,2) <= bc_end); 139 | end -------------------------------------------------------------------------------- /GRSC/cal_OA/KSRC_Classifier/line_dat.m: -------------------------------------------------------------------------------- 1 | function img = line_dat(dat, rdown, rup) 2 | img = dat; 3 | [lmax lmin] = linear(dat, rdown, rup); 4 | img(datlmax) = lmax; 5 | img = (img-lmin) / lmax; 6 | end 7 | 8 | function [lmax lmin] = linear(X, a, b) 9 | X = X(:); 10 | x = sort(X); 11 | L = length(x); 12 | lmin = x(max(ceil(L*a),1)); 13 | lmax = x(min(floor(L*b),end)); 14 | end -------------------------------------------------------------------------------- /GRSC/cal_OA/KSRC_Classifier/load_data.m: -------------------------------------------------------------------------------- 1 | function [img, img_gt, rows, cols, bands] = load_data(n) 2 | % 20121127 3 | switch n 4 | case 1, 5 | load data\indian\Indian_gt.mat; 6 | img_gt = indian_pines_gt; 7 | load data\indian\Indian_pines_corrected.mat; 8 | img = indian_pines_corrected; 9 | end 10 | 11 | [img, rows, cols, bands] = reshape3d_2d(img); 12 | img_gt = img_gt(:); 13 | rdown = 0.001; rup = 0.999; 14 | img = line_dat(img, rdown, rup); 15 | end -------------------------------------------------------------------------------- /GRSC/cal_OA/KSRC_Classifier/load_train_test.m: -------------------------------------------------------------------------------- 1 | function [trainidx, testidx] = load_train_test(dat, type, i, j) 2 | switch dat, 3 | case 1, 4 | if type == 1, 5 | load(['data\indian\train_test\Indian_n' num2str(i) '_' num2str(j) '.mat']); 6 | end 7 | if type == 2, 8 | end 9 | end 10 | trainidx = train_idx; testidx = test_idx; 11 | end -------------------------------------------------------------------------------- /GRSC/cal_OA/KSRC_Classifier/mex_pk_lwm.cpp: -------------------------------------------------------------------------------- 1 | // local weight mean kernel 2 | #include "mex.h" 3 | #include 4 | #include 5 | #include 6 | #include 7 | using namespace Concurrency; 8 | 9 | typedef double DAT; 10 | typedef double INT; 11 | template 12 | void delete_matrix(T **pVal, int n) 13 | { 14 | for (int i=0; i 4 | #include 5 | #include 6 | #include 7 | using namespace Concurrency; 8 | 9 | typedef double DAT; 10 | typedef double INT; 11 | template 12 | void delete_matrix(T **pVal, int n) 13 | { 14 | for (int i=0; in 21 | indexes = [indexes ;index1(per_index1(1:n))']; 22 | else 23 | indexes = [indexes ;index1(per_index1(1:floor(length(index1)/2)))']; 24 | end 25 | end 26 | indexes = indexes(:); 27 | indexes_all = [1:length(y)]; 28 | indexes_all(indexes) = []; 29 | n_new = nall - length(indexes); 30 | per_indexall = randperm(length(indexes_all)); 31 | if n_new>0 32 | indexes_new = indexes_all(per_indexall(1:n_new)); 33 | indexes = [indexes;indexes_new']; 34 | end 35 | indexes = indexes(:); 36 | 37 | 38 | 39 | 40 | % indexes = indexes'; 41 | % train = y(indexes); 42 | % y(indexes) = []; 43 | % test = y; 44 | 45 | % for k_iter = 1:K 46 | % index_k = y == k_iter; 47 | % index_k = find(index_k); 48 | % if length(index_k) > n 49 | % index_k_random = ceil(length(index_k).*rand(n,1)); 50 | % index_k_random = sort(index_k_random); 51 | % index_k_random1 = [index_k_random(2:n);index_k_random(1)]; 52 | % resid = index_k_random1 - index_k_random; 53 | % resid0 = resid == 0; 54 | % index_k_random(resid0) = []; 55 | % train_k = alltrain(:,index_k(index_k_random)); 56 | % yindex = [yindex,index_k(index_k_random)]; 57 | % else 58 | % n1 = ceil(length(index_k)/2); 59 | % index_k_random = ceil(length(index_k).*rand(n1,1)); 60 | % index_k_random = sort(index_k_random); 61 | % index_k_random1 = [index_k_random(2:n1);index_k_random(1)]; 62 | % resid = index_k_random1 - index_k_random; 63 | % resid0 = resid == 0; 64 | % index_k_random(resid0) = []; 65 | % train_k = alltrain(:,index_k(index_k_random)); 66 | % yindex = [yindex,index_k(index_k_random)]; 67 | % end 68 | % train = [train,train_k]; 69 | % end 70 | % 71 | % trainold = alltrain; 72 | % alltrain(:,yindex) = []; 73 | % test = alltrain; 74 | % for i = 1:K 75 | % ly = length(find(y==i)); 76 | % nf = ceil(pK*ly); 77 | % f = lys + ceil(ly.*rand(nf,1)); 78 | % f = sort(f); 79 | % findex = []; 80 | % for j = 1:(length(f)-1) 81 | % if f(j) == f(j+1) 82 | % findex = [findex,j]; 83 | % end 84 | % end 85 | % f(findex) = []; 86 | % train10 = alltrain(:,f); 87 | % yindex = [yindex,f']; 88 | % train = [train,train10]; 89 | % lys = lys + ly; 90 | % end 91 | % 92 | % alltrain(:,yindex) = []; 93 | % test = alltrain; 94 | -------------------------------------------------------------------------------- /GRSC/cal_OA/LDA_Classifier/LDA_Classifier.m: -------------------------------------------------------------------------------- 1 | function [OA,MA,Kappa,test_SL,predict_label] = LDA_Classifier(Dataset, band_set) 2 | 3 | [train_X,train_labels,test_X,test_labels,test_SL] = randdivide(Dataset); 4 | test_size = size(test_labels, 1); 5 | C = max(test_labels); 6 | bs_train_X = train_X(:, band_set); 7 | bs_test_X = test_X(:, band_set); 8 | 9 | 10 | factor = fitcdiscr(bs_train_X, train_labels); 11 | predict_label = double(factor.predict(bs_test_X)); 12 | cmat = confusionmat(test_labels, predict_label); 13 | OA = length(find(predict_label == test_labels)) / length(test_labels); 14 | sum_accu = 0; 15 | for i = 1 : C 16 | sum_accu = sum_accu + cmat(i, i) / sum(cmat(i, :), 2); 17 | end 18 | MA = sum_accu / C; 19 | Pe = 0; 20 | for i = 1 : C 21 | Pe = Pe + cmat(i, :) * cmat(:, i); 22 | end 23 | Pe = Pe / (test_size*test_size); 24 | Kappa = (OA - Pe) / (1 - Pe); 25 | end 26 | 27 | -------------------------------------------------------------------------------- /GRSC/cal_OA/SVM_Classifier/SVM_Classifier.m: -------------------------------------------------------------------------------- 1 | function [OA,MA,Kappa,test_SL,predict_labels] = SVM_Classifier(Dataset, band_set) 2 | 3 | [train_X,train_labels,test_X,test_labels,test_SL] = randdivide(Dataset); 4 | test_size = size(test_labels, 1); 5 | C = max(test_labels); 6 | bs_train_X = train_X(:, band_set); 7 | bs_test_X = test_X(:, band_set); 8 | 9 | 10 | model = svmtrain(train_labels, bs_train_X, Dataset.svm_para); 11 | [predict_labels, corrected_num, ~] = svmpredict(test_labels, bs_test_X, model, '-q'); 12 | OA = corrected_num(1) / 100; 13 | cmat = confusionmat(test_labels, predict_labels); 14 | sum_accu = 0; 15 | for i = 1 : C 16 | sum_accu = sum_accu + cmat(i, i) / sum(cmat(i, :), 2); 17 | end 18 | MA = sum_accu / C; 19 | Pe = 0; 20 | for i = 1 : C 21 | Pe = Pe + cmat(i, :) * cmat(:, i); 22 | end 23 | Pe = Pe / (test_size * test_size); 24 | Kappa = (OA - Pe) / (1 - Pe); 25 | end 26 | 27 | -------------------------------------------------------------------------------- /GRSC/cal_OA/randdivide.m: -------------------------------------------------------------------------------- 1 | function [train_X,train_labels,test_X,test_labels,test_SL] = randdivide(Dataset) 2 | ground_truth = Dataset.ground_truth; 3 | A = Dataset.A; 4 | train_ratio = Dataset.train_ratio; 5 | num_classes = max(max(ground_truth)); 6 | pixel_pos = cell(1, num_classes); 7 | [M, N, ~] = size(A); 8 | for i = 1:M 9 | for j = 1:N 10 | if ground_truth(i, j) ~= 0 11 | pixel_pos{ground_truth(i, j)} = [pixel_pos{ground_truth(i, j)}; [i j]]; 12 | end 13 | end 14 | end 15 | 16 | train_X = []; 17 | test_X = []; 18 | train_labels = []; 19 | test_labels = []; 20 | test_pos = []; 21 | row_rank = cell(num_classes, 1); 22 | for i = 1:num_classes 23 | pos_mat = pixel_pos{i}; 24 | row_rank{i} = randperm(size(pos_mat, 1)); 25 | pos_mat = pos_mat(row_rank{i}, :); 26 | 27 | [m1, ~] = size(pos_mat); 28 | for j = 1 : floor(m1 * train_ratio) 29 | temp = A(pos_mat(j, 1), pos_mat(j, 2), :); 30 | train_X = [train_X temp(:)]; 31 | train_labels = [train_labels;i]; 32 | end 33 | end 34 | 35 | for i = 1: num_classes 36 | pos_mat = pixel_pos{i}; 37 | pos_mat = pos_mat(row_rank{i}, :); 38 | [m1, ~] = size(pos_mat); 39 | for j = floor(m1 * train_ratio) + 1 : m1 40 | temp = A(pos_mat(j, 1), pos_mat(j, 2), :); 41 | test_X = [test_X temp(:)]; 42 | test_labels = [test_labels;i]; 43 | test_pos = [test_pos; (pos_mat(j, 2)-1) * M + pos_mat(j, 1)]; 44 | end 45 | end 46 | 47 | train_X = train_X'; 48 | test_X = test_X'; 49 | test_SL(1,:) = test_pos; 50 | test_SL(2,:) = test_labels; 51 | train_labels = double(train_labels); 52 | test_labels = double(test_labels); 53 | end 54 | 55 | -------------------------------------------------------------------------------- /GRSC/cal_OA/test_bs_accu.m: -------------------------------------------------------------------------------- 1 | function [accu,Classify_map] = test_bs_accu(band_set, Dataset, classifier_type) 2 | warning('off'); 3 | for iter = 1 : 3 4 | switch(classifier_type) 5 | case 'EPF' 6 | [OA(iter),MA(iter),Kappa(iter),test_SL,predict_label] = EPF_Classifier(Dataset, band_set); 7 | case 'KSRC' 8 | [OA(iter),MA(iter),Kappa(iter),test_SL,predict_label] = KSRC_Classifier(Dataset, band_set); 9 | case 'LBP' 10 | [OA(iter),MA(iter),Kappa(iter),test_SL,predict_label] = LBP_Classifier(Dataset, band_set); 11 | case 'SVM' 12 | [OA(iter),MA(iter),Kappa(iter),test_SL,predict_label] = SVM_Classifier(Dataset, band_set); 13 | case 'CART' 14 | [OA(iter),MA(iter),Kappa(iter),test_SL,predict_label] = CART_Classifier(Dataset, band_set); 15 | case 'KNN' 16 | [OA(iter),MA(iter),Kappa(iter),test_SL,predict_label] = KNN_Classifier(Dataset, band_set); 17 | case 'LDA' 18 | [OA(iter),MA(iter),Kappa(iter),test_SL,predict_label] = LDA_Classifier(Dataset, band_set); 19 | case 'NB' 20 | [OA(iter),MA(iter),Kappa(iter),test_SL,predict_label] = NB_Classifier(Dataset, band_set); 21 | case 'RF' 22 | [OA(iter),MA(iter),Kappa(iter),test_SL,predict_label] = RF_Classifier(Dataset, band_set); 23 | end 24 | end 25 | accu.OA = mean(OA); 26 | accu.MA = mean(MA); 27 | accu.Kappa = mean(Kappa); 28 | 29 | accu.STDOA = std(OA); 30 | accu.STDMA = std(MA); 31 | accu.STDKappa = std(Kappa); 32 | 33 | [M,N,B] = size(Dataset.A); 34 | 35 | Classify_map = Dataset.ground_truth(:); 36 | Classify_map(test_SL(1,:)) = predict_label; 37 | Classify_map = reshape(Classify_map,[M N]); 38 | 39 | end -------------------------------------------------------------------------------- /GRSC/cal_OA/train_test_random_new.m: -------------------------------------------------------------------------------- 1 | function [indexes]=train_test_random_new(y,n,nall) 2 | % function to ramdonly select training samples and testing samples from the 3 | % whole set of ground truth. 4 | % alltrain is the ground truth 5 | % % clc 6 | % alltrain = alltrain'; 7 | % y = alltrain(2,:); % Indiana 8 | % y = alltrain(1,:); % Salinas 9 | % yindex = []; 10 | % train = []; 11 | % lys = 0; 12 | K = max(y); 13 | % pK = 0.0001, 14 | 15 | % generate the training set 16 | indexes = []; 17 | for i = 1:K 18 | index1 = find(y == i); 19 | per_index1 = randperm(length(index1)); 20 | if length(index1)/2>n 21 | indexes = [indexes ;index1(per_index1(1:n))']; 22 | else 23 | indexes = [indexes ;index1(per_index1(1:floor(length(index1)/2)))']; 24 | end 25 | end 26 | indexes = indexes(:); 27 | indexes_all = [1:length(y)]; 28 | indexes_all(indexes) = []; 29 | n_new = nall - length(indexes); 30 | per_indexall = randperm(length(indexes_all)); 31 | if n_new>0 32 | indexes_new = indexes_all(per_indexall(1:n_new)); 33 | indexes = [indexes;indexes_new']; 34 | end 35 | indexes = indexes(:); 36 | 37 | 38 | 39 | 40 | % indexes = indexes'; 41 | % train = y(indexes); 42 | % y(indexes) = []; 43 | % test = y; 44 | 45 | % for k_iter = 1:K 46 | % index_k = y == k_iter; 47 | % index_k = find(index_k); 48 | % if length(index_k) > n 49 | % index_k_random = ceil(length(index_k).*rand(n,1)); 50 | % index_k_random = sort(index_k_random); 51 | % index_k_random1 = [index_k_random(2:n);index_k_random(1)]; 52 | % resid = index_k_random1 - index_k_random; 53 | % resid0 = resid == 0; 54 | % index_k_random(resid0) = []; 55 | % train_k = alltrain(:,index_k(index_k_random)); 56 | % yindex = [yindex,index_k(index_k_random)]; 57 | % else 58 | % n1 = ceil(length(index_k)/2); 59 | % index_k_random = ceil(length(index_k).*rand(n1,1)); 60 | % index_k_random = sort(index_k_random); 61 | % index_k_random1 = [index_k_random(2:n1);index_k_random(1)]; 62 | % resid = index_k_random1 - index_k_random; 63 | % resid0 = resid == 0; 64 | % index_k_random(resid0) = []; 65 | % train_k = alltrain(:,index_k(index_k_random)); 66 | % yindex = [yindex,index_k(index_k_random)]; 67 | % end 68 | % train = [train,train_k]; 69 | % end 70 | % 71 | % trainold = alltrain; 72 | % alltrain(:,yindex) = []; 73 | % test = alltrain; 74 | % for i = 1:K 75 | % ly = length(find(y==i)); 76 | % nf = ceil(pK*ly); 77 | % f = lys + ceil(ly.*rand(nf,1)); 78 | % f = sort(f); 79 | % findex = []; 80 | % for j = 1:(length(f)-1) 81 | % if f(j) == f(j+1) 82 | % findex = [findex,j]; 83 | % end 84 | % end 85 | % f(findex) = []; 86 | % train10 = alltrain(:,f); 87 | % yindex = [yindex,f']; 88 | % train = [train,train10]; 89 | % lys = lys + ly; 90 | % end 91 | % 92 | % alltrain(:,yindex) = []; 93 | % test = alltrain; 94 | -------------------------------------------------------------------------------- /GRSC/clu_ncut.m: -------------------------------------------------------------------------------- 1 | function [idx] = clu_ncut(L,K) 2 | % this routine groups the data X into K subspaces by NCut 3 | % inputs: 4 | % L -- an N*N affinity matrix, N is the number of data points 5 | % K -- the number of subpaces (i.e., clusters) 6 | L = (L + L')/2; 7 | D = diag(1./sqrt(sum(L,2))); 8 | L = D*L*D; 9 | [U,S,V] = svd(L); 10 | 11 | V = U(:,1:K); 12 | V = D*V; 13 | 14 | stream = RandStream.getGlobalStream; 15 | reset(stream); 16 | % idx = kmeans(V,K,'emptyaction','singleton','replicates',20,'display','off'); 17 | [idx, ~, ~, ~] = kmeans(V, K,'maxiter',100,'replicates',50,'emptyaction','singleton'); 18 | idx = idx'; -------------------------------------------------------------------------------- /GRSC/constructW_PKN.m: -------------------------------------------------------------------------------- 1 | % construct similarity matrix with probabilistic k-nearest neighbors. It is a parameter free, distance consistent similarity. 2 | function W = constructW_PKN(X, k, issymmetric) 3 | % X: each column is a data point 4 | % k: number of neighbors 5 | % issymmetric: set W = (W+W')/2 if issymmetric=1 6 | % W: similarity matrix 7 | 8 | if nargin < 3 9 | issymmetric = 1; 10 | end; 11 | if nargin < 2 12 | k = 5; 13 | end; 14 | 15 | [dim, n] = size(X); 16 | D = L2_distance_1(X, X); 17 | [dumb, idx] = sort(D, 2); % sort each row 18 | 19 | W = zeros(n); 20 | for i = 1:n 21 | id = idx(i,2:k+2); 22 | di = D(i, id); 23 | W(i,id) = (di(k+1)-di)/(k*di(k+1)-sum(di(1:k))+eps); 24 | end; 25 | 26 | if issymmetric == 1 27 | W = (W+W')/2; 28 | end; 29 | 30 | 31 | 32 | 33 | % compute squared Euclidean distance 34 | % ||A-B||^2 = ||A||^2 + ||B||^2 - 2*A'*B 35 | function d = L2_distance_1(a,b) 36 | % a,b: two matrices. each column is a data 37 | % d: distance matrix of a and b 38 | 39 | 40 | 41 | if (size(a,1) == 1) 42 | a = [a; zeros(1,size(a,2))]; 43 | b = [b; zeros(1,size(b,2))]; 44 | end 45 | 46 | aa=sum(a.*a); bb=sum(b.*b); ab=a'*b; 47 | d = repmat(aa',[1 size(bb,2)]) + repmat(bb,[size(aa,2) 1]) - 2*ab; 48 | 49 | d = real(d); 50 | d = max(d,0); 51 | 52 | % % force 0 on the diagonal? 53 | % if (df==1) 54 | % d = d.*(1-eye(size(d))); 55 | % end 56 | 57 | 58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /GRSC/datasets/Indian_pines.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WangJun2023/GRSC/714a19f3e37e69ad0409a9ad62c04bd70cda425f/GRSC/datasets/Indian_pines.mat -------------------------------------------------------------------------------- /GRSC/datasets/Indian_pines_gt.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WangJun2023/GRSC/714a19f3e37e69ad0409a9ad62c04bd70cda425f/GRSC/datasets/Indian_pines_gt.mat -------------------------------------------------------------------------------- /GRSC/eig1.m: -------------------------------------------------------------------------------- 1 | function [eigvec, eigval, eigval_full] = eig1(A, c, isMax, isSym) 2 | 3 | if nargin < 2 4 | c = size(A,1); 5 | isMax = 1; 6 | isSym = 1; 7 | elseif c > size(A,1) 8 | c = size(A,1); 9 | end; 10 | 11 | if nargin < 3 12 | isMax = 1; 13 | isSym = 1; 14 | end; 15 | 16 | if nargin < 4 17 | isSym = 1; 18 | end; 19 | 20 | if isSym == 1 21 | A = max(A,A'); 22 | end; 23 | [v d] = eig(A); 24 | d = diag(d); 25 | %d = real(d); 26 | if isMax == 0 27 | [d1, idx] = sort(d); 28 | else 29 | [d1, idx] = sort(d,'descend'); 30 | end; 31 | 32 | idx1 = idx(1:c); 33 | eigval = d(idx1); 34 | eigvec = v(:,idx1); 35 | 36 | eigval_full = d(idx); -------------------------------------------------------------------------------- /GRSC/get_data.m: -------------------------------------------------------------------------------- 1 | function [Dataset] = get_data(dataset_name) 2 | %% import the dataset 3 | switch dataset_name 4 | case 'Indian_Pines' 5 | A = importdata('Indian_pines.mat'); 6 | ground_truth = importdata('Indian_pines_gt.mat'); 7 | case 'Salinas' 8 | A = importdata('Salinas.mat'); 9 | ground_truth = importdata('Salinas_gt.mat'); 10 | case 'Pavia_University' 11 | A = importdata('PaviaU.mat'); 12 | ground_truth = importdata('PaviaU_gt.mat'); 13 | case 'KSC' 14 | A = importdata('KSC.mat'); 15 | ground_truth = importdata('KSC_gt.mat'); 16 | case 'Botswana' 17 | A = importdata('Botswana.mat'); 18 | ground_truth = importdata('Botswana_gt.mat'); 19 | end 20 | %% definition and initialization 21 | A = double(A); 22 | minv = min(A(:)); 23 | maxv = max(A(:)); 24 | A = double(A - minv) / double(maxv - minv); 25 | 26 | %% Generalize the output 27 | X = permute(A, [3, 1, 2]); 28 | X = X(:, :); 29 | Dataset.X = X; 30 | Dataset.A = A; 31 | Dataset.ground_truth = ground_truth; 32 | end -------------------------------------------------------------------------------- /GRSC/mySVD.m: -------------------------------------------------------------------------------- 1 | function [U, S, V] = mySVD(X,ReducedDim) 2 | %mySVD Accelerated singular value decomposition. 3 | % [U,S,V] = mySVD(X) produces a diagonal matrix S, of the 4 | % dimension as the rank of X and with nonnegative diagonal elements in 5 | % decreasing order, and unitary matrices U and V so that 6 | % X = U*S*V'. 7 | % 8 | % [U,S,V] = mySVD(X,ReducedDim) produces a diagonal matrix S, of the 9 | % dimension as ReducedDim and with nonnegative diagonal elements in 10 | % decreasing order, and unitary matrices U and V so that 11 | % Xhat = U*S*V' is the best approximation (with respect to F norm) of X 12 | % among all the matrices with rank no larger than ReducedDim. 13 | % 14 | % Based on the size of X, mySVD computes the eigvectors of X*X^T or X^T*X 15 | % first, and then convert them to the eigenvectors of the other. 16 | % 17 | % See also SVD. 18 | % 19 | % version 2.0 --Feb/2009 20 | % version 1.0 --April/2004 21 | % 22 | % Written by Deng Cai (dengcai AT gmail.com) 23 | % 24 | 25 | MAX_MATRIX_SIZE = 1600; % You can change this number according your machine computational power 26 | EIGVECTOR_RATIO = 0.1; % You can change this number according your machine computational power 27 | 28 | 29 | if ~exist('ReducedDim','var') 30 | ReducedDim = 0; 31 | end 32 | 33 | [nSmp, mFea] = size(X); 34 | if mFea/nSmp > 1.0713 35 | ddata = X*X'; 36 | ddata = max(ddata,ddata'); 37 | 38 | dimMatrix = size(ddata,1); 39 | if (ReducedDim > 0) && (dimMatrix > MAX_MATRIX_SIZE) && (ReducedDim < dimMatrix*EIGVECTOR_RATIO) 40 | option = struct('disp',0); 41 | [U, eigvalue] = eigs(ddata,ReducedDim,'la',option); 42 | eigvalue = diag(eigvalue); 43 | else 44 | if issparse(ddata) 45 | ddata = full(ddata); 46 | end 47 | 48 | [U, eigvalue] = eig(ddata); 49 | eigvalue = diag(eigvalue); 50 | [dump, index] = sort(-eigvalue); 51 | eigvalue = eigvalue(index); 52 | U = U(:, index); 53 | end 54 | clear ddata; 55 | 56 | maxEigValue = max(abs(eigvalue)); 57 | eigIdx = find(abs(eigvalue)/maxEigValue < 1e-10); 58 | eigvalue(eigIdx) = []; 59 | U(:,eigIdx) = []; 60 | 61 | if (ReducedDim > 0) && (ReducedDim < length(eigvalue)) 62 | eigvalue = eigvalue(1:ReducedDim); 63 | U = U(:,1:ReducedDim); 64 | end 65 | 66 | eigvalue_Half = eigvalue.^.5; 67 | S = spdiags(eigvalue_Half,0,length(eigvalue_Half),length(eigvalue_Half)); 68 | 69 | if nargout >= 3 70 | eigvalue_MinusHalf = eigvalue_Half.^-1; 71 | V = X'*(U.*repmat(eigvalue_MinusHalf',size(U,1),1)); 72 | end 73 | else 74 | ddata = X'*X; 75 | ddata = max(ddata,ddata'); 76 | 77 | dimMatrix = size(ddata,1); 78 | if (ReducedDim > 0) && (dimMatrix > MAX_MATRIX_SIZE) && (ReducedDim < dimMatrix*EIGVECTOR_RATIO) 79 | option = struct('disp',0); 80 | [V, eigvalue] = eigs(ddata,ReducedDim,'la',option); 81 | eigvalue = diag(eigvalue); 82 | else 83 | if issparse(ddata) 84 | ddata = full(ddata); 85 | end 86 | 87 | [V, eigvalue] = eig(ddata); 88 | eigvalue = diag(eigvalue); 89 | 90 | [dump, index] = sort(-eigvalue); 91 | eigvalue = eigvalue(index); 92 | V = V(:, index); 93 | end 94 | clear ddata; 95 | 96 | maxEigValue = max(abs(eigvalue)); 97 | eigIdx = find(abs(eigvalue)/maxEigValue < 1e-10); 98 | eigvalue(eigIdx) = []; 99 | V(:,eigIdx) = []; 100 | 101 | if (ReducedDim > 0) && (ReducedDim < length(eigvalue)) 102 | eigvalue = eigvalue(1:ReducedDim); 103 | V = V(:,1:ReducedDim); 104 | end 105 | 106 | eigvalue_Half = eigvalue.^.5; 107 | S = spdiags(eigvalue_Half,0,length(eigvalue_Half),length(eigvalue_Half)); 108 | 109 | eigvalue_MinusHalf = eigvalue_Half.^-1; 110 | U = X*(V.*repmat(eigvalue_MinusHalf',size(V,1),1)); 111 | end 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | -------------------------------------------------------------------------------- /GRSC/predict.m: -------------------------------------------------------------------------------- 1 | function [Y] = predict(Z,k) 2 | Y =[]; 3 | [dim,num] = size(Z); 4 | for i = 1 : dim 5 | temp = Z(i,:); 6 | vc(i) = sqrt((temp*temp'+eps)); 7 | end 8 | [~,idx] = sort(vc, 'descend'); 9 | Y = idx(1:k); 10 | end 11 | 12 | -------------------------------------------------------------------------------- /GRSC/run.m: -------------------------------------------------------------------------------- 1 | clear all 2 | clc 3 | dataset_names = {'Indian_Pines', 'KSC', 'Botswana','Salinas', 'Pavia_University'}; 4 | classifier_names = {'KNN', 'LDA','SVM','KSRC'}; 5 | svm_para = {'-c 5000.000000 -g 0.500000 -m 500 -t 2 -q',... 6 | '-c 10000.000000 -g 16.000000 -m 500 -t 2 -q',... 7 | '-c 10000 -g 0.5 -m 500 -t 2 -q',... 8 | '-c 100 -g 16 -m 500 -t 2 -q',... 9 | '-c 100 -g 4 -m 500 -t 2 -q',... 10 | }; 11 | train_ratio = [0.1, 0.1, 0.1, 0.1, 0.1]; 12 | SuperpixelNum = [165, 186, 180, 103, 155]; 13 | ResSavePath = 'result/'; 14 | warning off; 15 | 16 | for dataset_id = 1 17 | Dataset = get_data(dataset_names{dataset_id}); 18 | Dataset.svm_para = svm_para{1, dataset_id}; 19 | Dataset.train_ratio = train_ratio(dataset_id); 20 | nC = SuperpixelNum(dataset_id); 21 | for classifier_id = 1 22 | [OA, MA, Kappa] = GRSC(Dataset,classifier_names{classifier_id},nC); 23 | resFile = [ResSavePath dataset_names{dataset_id},'-',num2str(nC),'-',... 24 | num2str(train_ratio(dataset_id)),'-',classifier_names{classifier_id},'.mat']; 25 | save(resFile, 'OA', 'MA', 'Kappa'); 26 | end 27 | end -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # GRSC 2 | This is the source code for Graph Regularized Spatial-spectral Subspace Clustering for Hyperspectral Band Selection, Neural Networks 2022. 3 | 4 | More datasets can be downloaded from 百度网盘 5 | 提取码:5sy0 6 | 7 | If you have any question about the code, please send email to wang_jun@nudt.edu.cn 8 | --------------------------------------------------------------------------------