1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433
| package millie.plugins.free;
import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import millie.image.Kernel;
import millie.image.PredefinedKernel;
import millie.plugins.GenericPluginFilter;
import millie.plugins.parameters.ComboBoxEntry;
import millie.plugins.parameters.ComboBoxParameter;
import millie.plugins.parameters.IntSliderParameter;
import millie.se.operator.ConvolveOperator;
import millie.se.operator.extender.BorderExtenderCopy;
public class WaterShedPlugin extends GenericPluginFilter {
enum InputType {
Normal("image (fond sombre)"),
Invert("image (fond clair)"),
Variance("variance de l'image"),
LogVariance("log-variance de l'image");
private InputType(String txt) {this.label=txt;}
String label;
}
enum OutputType {
ImageShed("image + lignes de partage"),
Shed("lignes de partage seules"),
MosaicShed("mosaique + lignes de partage"),
Mosaic("mosaique seule");
private OutputType(String txt) {this.label=txt;}
String label;
}
// saved input parameters
private int savedRadius=0;
private InputType savedInputtype = null;
// saved sum images
private long[][] R,R2,G,G2,B,B2;
public WaterShedPlugin() {
setPluginName("Segmentation WaterShed (LPE)");
setRefreshable(false);
setLongProcessing(true);
setReinitializable(true);
ComboBoxEntry[] inputTypeParameter = new ComboBoxEntry[InputType.values().length];
for(InputType e : InputType.values())
inputTypeParameter[e.ordinal()] = new ComboBoxEntry(e.name(),e.label);
addParameter(new ComboBoxParameter("inputtype","Type d'entrée", inputTypeParameter));
addParameter(new IntSliderParameter("radius", "rayon (sampling)",1,10,3));
ComboBoxEntry[] outputTypeParameter = new ComboBoxEntry[OutputType.values().length];
for(OutputType e : OutputType.values())
outputTypeParameter[e.ordinal()] = new ComboBoxEntry(e.name(),e.label);
addParameter(new ComboBoxParameter("outputtype","Affichage", outputTypeParameter));
}
@Override
public BufferedImage filter() throws Exception {
BufferedImage original = getInputImage();
int radius = getParameter("radius").getIntValue();
OutputType outputtype = OutputType.valueOf(getParameter("outputtype").getStringValue());
InputType inputtype = InputType.valueOf(getParameter("inputtype").getStringValue());
boolean needCompute=false;
if (radius!=savedRadius) needCompute=true;
if (inputtype!=savedInputtype) needCompute=true;
boolean drawImage=false, drawMosaic=false, drawShed=true;
switch(outputtype) {
case ImageShed: drawImage=true;drawMosaic=false;drawShed=true; break;
case Shed: drawImage=false;drawMosaic=false;drawShed=true; break;
case MosaicShed: drawImage=false;drawMosaic=true;drawShed=true; break;
case Mosaic: drawImage=false;drawMosaic=true;drawShed=false; break;
}
if (needCompute) {
this.savedRadius = radius;
this.savedInputtype = inputtype;
this.image = null;
this.width = original.getWidth();
this.height = original.getHeight();
switch(inputtype) {
case Normal: this.image=BitmapToArrayGray(original,radius,true); break;
case Invert: this.image=BitmapToArrayGray(original,radius,false); break;
case Variance: this.image=variance(original,radius,false) ;break;
case LogVariance: this.image=variance(original,radius,true); break;
}
// compute ideal step
double stddev = stddev(this.image,this.width,this.height);
int step = (int)(0.50*stddev);
// watershed segmentation
process(step);
System.out.println("Region count : "+this.maxid);
}
return display(original,drawImage,drawMosaic,drawShed);
}
/* --------------------------------------------------------------------- */
/* INPUT PROCESSING */
/* --------------------------------------------------------------------- */
private static int[] logscale = new int[256];
static {
for(int i=0;i<256;i++)
logscale[i]=(int)(255*Math.pow(i/255.0,0.333));
}
private int getGrayLevel(BufferedImage input, int x, int y) {
// convert rgb to luminance
int rgb=input.getRGB(x,y);
int r = (rgb >>16 ) & 0xFF;
int g = (rgb >> 8 ) & 0xFF;
int b = rgb & 0xFF;
return (299*r + 587*g + 114*b)/1000;
}
private int[][] BitmapToArrayGray(BufferedImage input, int radius, boolean invert) {
// 1. bluring
double sigma = radius*0.333;
Kernel kernel = PredefinedKernel.getGaussianKernel(radius, sigma);
ConvolveOperator op = new ConvolveOperator(kernel,new BorderExtenderCopy());
BufferedImage blured = op.compute(input);
// 2. convert to graylevel array
int width = blured.getWidth();
int height = blured.getHeight();
int[][] c2 = new int[width][height];
for (int y=0; y<height; y++)
for (int x=0; x<width; x++) {
c2[x][y]=getGrayLevel(blured,x,y);
if (invert) c2[x][y]=255-c2[x][y];
}
return c2;
}
// compute the sum-image of the given image
public long[][] sumImage(long[][] image, int width, int height) {
long[][] sum = new long[width][height];
sum[0][0] = image[0][0];
// 2. first column
for (int y=1; y<height; y++)
sum[0][y] = image[0][y] + sum[0][y-1];
// 3. first line
for (int x=1; x<width; x++)
sum[x][0] = image[x][0] + sum[x-1][0];
// 4. remaining pixels
for (int y=1; y<height; y++)
for (int x=1; x<width; x++)
sum[x][y] = image[x][y] + sum[x-1][y] + sum[x][y-1] - sum[x-1][y-1];
return sum;
}
private int[][] variance(BufferedImage input, int radius, boolean log) {
int width = input.getWidth();
int height = input.getHeight();
long[][] layer = new long[width][height];
// RED sum-image
if (this.R==null || this.R2==null) {
for (int y=0; y<height; y++) for (int x=0; x<width; x++) layer[x][y]=((input.getRGB(x,y)>>16) & 0xFF);
this.R = sumImage(layer,width,height);
for (int y=0; y<height; y++) for (int x=0; x<width; x++) layer[x][y]*=layer[x][y];
this.R2 = sumImage(layer,width,height);
}
// GREEN sum-image
if (this.G==null || this.G2==null) {
for (int y=0; y<height; y++) for (int x=0; x<width; x++) layer[x][y]=((input.getRGB(x,y)>>8) & 0xFF);
this.G = sumImage(layer,width,height);
for (int y=0; y<height; y++) for (int x=0; x<width; x++) layer[x][y]*=layer[x][y];
this.G2 = sumImage(layer,width,height);
}
// BLUE sum-image
if (this.B==null || this.B2==null) {
for (int y=0; y<height; y++) for (int x=0; x<width; x++) layer[x][y]=(input.getRGB(x,y) & 0xFF);
this.B = sumImage(layer,width,height);
for (int y=0; y<height; y++) for (int x=0; x<width; x++) layer[x][y]*=layer[x][y];
this.B2 = sumImage(layer,width,height);
}
// compute the local variance
int[][] c2 = new int[width][height];
for (int y=0; y<height; y++) {
for (int x=0; x<width; x++) {
// zone coords
int xmin = Math.max(x-radius,0);
int xmax = Math.min(x+radius,width-1);
int ymin = Math.max(y-radius,0);
int ymax = Math.min(y+radius,height-1);
int area = (xmax-xmin)*(ymax-ymin);
// red variance
double XR = R[xmax][ymax] - R[xmin][ymax] - R[xmax][ymin] + R[xmin][ymin];
double XR2 = R2[xmax][ymax] - R2[xmin][ymax] - R2[xmax][ymin] + R2[xmin][ymin];
double var_R = XR2/area - (XR*XR)/(area*area);
// green variance
double XG = G[xmax][ymax] - G[xmin][ymax] - G[xmax][ymin] + G[xmin][ymin];
double XG2 = G2[xmax][ymax] - G2[xmin][ymax] - G2[xmax][ymin] + G2[xmin][ymin];
double var_G = XG2/area - (XG*XG)/(area*area);
// blue variance
double XB = B[xmax][ymax] - B[xmin][ymax] - B[xmax][ymin] + B[xmin][ymin];
double XB2 = B2[xmax][ymax] - B2[xmin][ymax] - B2[xmax][ymin] + B2[xmin][ymin];
double var_B = XB2/area - (XB*XB)/(area*area);
// weighted sum of the 3 variances
double v = 0.299*var_R + 0.587*var_G + 0.114*var_B;
// convert to range [0-255]
v = Math.sqrt(v)*2;
if (v>255) v=255;
if (log) v = logscale[(int)v];
c2[x][y]=(int)v;
}
}
return c2;
}
private static double stddev(int[][] image,int W,int H) {
double X=0,X2=0,COUNT=0;
for (int y = 0; y < H; y++) {
for (int x = 0; x < W; x++) {
X+=image[x][y];
X2+=image[x][y]*image[x][y];
COUNT++;
}
}
double variance = (X2/COUNT) - ((X*X)/(COUNT*COUNT));
double stddev = Math.sqrt(variance);
return stddev;
}
/* --------------------------------------------------------------------- */
/* OUTPUT PROCESSING */
/* --------------------------------------------------------------------- */
public BufferedImage display(BufferedImage original, boolean drawImage, boolean drawMosaic, boolean drawShed) {
Map<Integer, int[]> regions = new HashMap<Integer, int[]>();
// Compute mean region color
if (drawMosaic) {
for (int y = 0; y < this.height; y++) {
for (int x = 0; x < this.width; x++) {
int rid = this.rmap[x][y];
int[] stat = regions.get(rid);
if (stat==null) {
stat = new int[4];
regions.put(rid, stat);
}
int rgb = original.getRGB(x, y);
int r=(rgb>>16) & 0xFF, g=(rgb>>8 ) & 0xFF, b=rgb & 0xFF;
stat[0]+=r; stat[1]+=g; stat[2]+=b; stat[3]++;
}
}
for(int[] rgb:regions.values()) {
// mean
rgb[0]=(int)(0.5+rgb[0]/rgb[3]);
rgb[1]=(int)(0.5+rgb[1]/rgb[3]);
rgb[2]=(int)(0.5+rgb[2]/rgb[3]);
// rgb format
int r = rgb[0] & 0xFF;
int g = rgb[1] & 0xFF;
int b = rgb[2] & 0xFF;
rgb[3] = (r<<16)+(g<<8)+b;
}
}
// create output image
BufferedImage out = new BufferedImage(this.width,this.height,ColorSpace.TYPE_RGB);
for (int y = 0; y < this.height; y++) {
for (int x = 0; x < this.width; x++) {
int rid = this.rmap[x][y];
if (rid>0) {
if (drawImage) // copy original pixel
out.setRGB(x, y, original.getRGB(x, y));
if (drawMosaic) // copy mean value of region
out.setRGB(x, y, regions.get(rid)[3]);
}
if (rid<0) {
if (drawShed) // draw watershed
out.setRGB(x, y, 0xFF0000);
else // copy mean value of an adjacent region
out.setRGB(x, y, regions.get(-rid)[3]);
}
}
}
return out;
}
/* --------------------------------------------------------------------- */
/* WATERSHED PROCESSING */
/* --------------------------------------------------------------------- */
// original gray-level image
private int width,height;
private int[][] image = null;
private final int GRAYLEVEL = 256;
// region map
private int[][] rmap = null;
private int maxid=0;
// pixel and list of pixel structure
class Pixel {
int x,y,level;
public Pixel(int x,int y,int l) {
this.x=x; this.y=y; this.level=l;
}
}
class ListOfPixels extends LinkedList<Pixel> {}
// list of pixels (one per level) to process
private ListOfPixels[] explorelist;
// offsets of the 8 neighbors
private int[] dx8 = new int[] {-1, 0, 1, 1, 1, 0,-1,-1};
private int[] dy8 = new int[] {-1,-1,-1, 0, 1, 1, 1, 0};
// ---------------------------------------------------
// gray-level watershed algorithm : return the boolean watershep map
public void process(int step) {
// allocate memory
this.maxid=0;
this.rmap = new int[this.width][this.height];
this.explorelist = new ListOfPixels[GRAYLEVEL];
for(int i=0;i<GRAYLEVEL;i++)
this.explorelist[i]=new ListOfPixels();
// flooding level by level
int level=0,yoffset=0;
while(level<GRAYLEVEL) {
// extend region by exploring neighbors of known pixels
while(true) {
Pixel p = nextPixel(level,step);
if (p==null) break;
extend(p);
}
// find a new seed for this level
Pixel seed = findSeed(level,yoffset);
if (seed!=null) {
// create and assign a new region to this seed
this.rmap[seed.x][seed.y]=(++maxid);
yoffset=seed.y;
// add this seed to the list of pixel to explore
explorelist[level].add(seed);
} else {
// no more seed for this level -> next level
level++;
yoffset=0;
}
}
// clean up
this.explorelist = null;
}
// find a seed ( = unassigned pixel ) at the specified level
private Pixel findSeed(int level,int yoffset) {
for (int y = yoffset; y < this.height; y++)
for (int x = 0; x < this.width; x++)
if (this.image[x][y]==level && this.rmap[x][y]==0)
return new Pixel(x,y,level);
return null;
}
// return the next pixel to explore
private Pixel nextPixel(int level, int step) {
// return the first pixel found in the explorelist
for(int i=level;i<level+step && i<GRAYLEVEL;i++) {
if (!explorelist[i].isEmpty())
return explorelist[i].remove(0);
}
return null;
}
// explore the 8 neighbors of a pixel and set the region
private void extend(Pixel p) {
int region=this.rmap[p.x][p.y];
// this pixel is a watershed => cannot extend it
if (region<0) return;
// for each neighbor pixel
for(int k=0;k<8;k++) {
int xk = p.x+dx8[k];
int yk = p.y+dy8[k];
if (xk<0 || xk>=this.width) continue;
if (yk<0 || yk>=this.height) continue;
// level and region of neighbor
int vk = this.image[xk][yk];
int rk = this.rmap[xk][yk];
// neighbor is a watershed => ignore
if (rk<0) continue;
// neighbor as no region assigned => set it
if (rk==0) {
this.rmap[xk][yk]=region;
this.explorelist[vk].add(new Pixel(xk,yk,vk));
continue;
}
// neighbor is assigned to the same region => nothing to do
if (rk==region) continue;
// neighbor is assigned to another region => it's a watershed
this.rmap[xk][yk]=-rk;
}
}
} |
Partager