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 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701
|
/*
* Resample
*
* Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007 Marco Schmidt.
* All rights reserved.
*/
package net.sourceforge.jiu.geometry;
import net.sourceforge.jiu.data.PixelImage;
import net.sourceforge.jiu.data.IntegerImage;
import net.sourceforge.jiu.ops.ImageToImageOperation;
import net.sourceforge.jiu.ops.MissingParameterException;
import net.sourceforge.jiu.ops.WrongParameterException;
// 2007-04-19 optimization results
//* 10393 original speed in ms
//* 6053 innerloop fix
//* 5688 if .. continue loop break
//* 5485 replaced contrib[] array access by variable
//* 5173 doing the same on first pass (except innerloop fix which was ok there)
// global gain is 2x faster
/* This is the beginning of resample.pas, the Unit on which this class is based:
// -----------------------------------------------------------------------------
// Project: bitmap resampler
// Module: resample
// Description: Interpolated Bitmap Resampling using filters.
// Version: 01.03
// Release: 4
// Date: 29-JUN-1999
// Target: Win32, Delphi 2, 3 & 4
// Author(s): anme: Anders Melander, anders@melander.dk
// Copyright (c) 1997-99 by Anders Melander
// Formatting: 2 space indent, 8 space tabs, 80 columns.
// -----------------------------------------------------------------------------
// This software is copyrighted as noted above. It may be freely copied,
// modified, and redistributed, provided that the copyright notice(s) is
// preserved on all copies.
//
// There is no warranty or other guarantee of fitness for this software,
// it is provided solely "as is". Bug reports or fixes may be sent
// to the author, who may or may not act on them as he desires.
//
// You may not include this software in a program or other software product
// without supplying the source, or without informing the end-user that the
// source is available for no extra charge.
//
// If you modify this software, you should include a notice in the "Revision
// history" section giving the name of the person performing the modification,
// the date of modification, and the reason for such modification.
// -----------------------------------------------------------------------------
// Here's some additional copyrights for you:
//
// From filter.c:
// The authors and the publisher hold no copyright restrictions
// on any of these files; this source code is public domain, and
// is freely available to the entire computer graphics community
// for study, use, and modification. We do request that the
// comment at the top of each file, identifying the original
// author and its original publication in the book Graphics
// Gems, be retained in all programs that use these files.
//
// -----------------------------------------------------------------------------
// Revision history:
//
// 0100 110997 anme - Adapted from Dale Schumacher's fzoom v0.20.
//
// 0101 110198 anme - Added Lanczos3 and Mitchell filters.
// - Fixed range bug.
// Min value was not checked on conversion from Single to
// byte.
// - Numerous optimizations.
// - Added TImage stretch on form resize.
// - Added support for Delphi 2 via TCanvas.Pixels.
// - Renamed module from stretch to resample.
// - Moved demo code to separate module.
//
// 0102 150398 anme - Fixed a problem that caused all pixels to be shifted
// 1/2 pixel down and to the right (in source
// coordinates). Thanks to David Ullrich for the
// solution.
//
// 0103 170898 anme - Fixed typo: Renamed Strecth function to Stretch.
// Thanks to Graham Stratford for spotting it.
// Sorry about that.
// 081298 anme - Added check for too small destination bitmap.
// Thanks to Jeppe Oland for bringing this problem to my
// attention.
// 260399 anme - Fixed a problem with resampling of very narrow
// bitmaps. Thanks to Holger Dors for bringing the
// problem to my attention.
// - Removed dependency of math unit.
// 290699 jobe - Subsampling improvements by Josha Beukema.
//
// -----------------------------------------------------------------------------
// Credits:
// The algorithms and methods used in this library are based on the article
// "General Filtered Image Rescaling" by Dale Schumacher which appeared in the
// book Graphics Gems III, published by Academic Press, Inc.
//
// The edge offset problem was fixed by:
// * David Ullrich <ullrich@hardy.math.okstate.edu>
//
// The subsampling problem was fixed by:
// * Josha Beukema <jbeukema@inn.nl>
// -----------------------------------------------------------------------------
// To do (in rough order of priority):
// * Implement Dale Schumacher's "Optimized Bitmap Scaling Routines".
// * Optimize to use integer math instead of floating point where possible.
// -----------------------------------------------------------------------------
*/
/**
* Resizes grayscale and truecolor images using filters.
* For other image types (including paletted or bilevel images), you might
* want to use the {@link ScaleReplication} class or convert the images to
* grayscale (or RGB truecolor) first and then use this class.
* Several algorithms for resampling are implemented, they differ in resulting image quality
* and computational complexity.
*
* <h3>Usage example</h3>
* This will scale <code>image</code> to 150 percent of its original size
* in both directions, using the Lanczos3 filter type:
* <pre>
* Resample resample = new Resample();
* resample.setInputImage(image);
* resample.setSize(image.getWidth() * 3 / 2, image.getHeight() * 3 / 2);
* resample.setFilter(Resample.FILTER_TYPE_LANCZOS3);
* resample.process();
* PixelImage scaledImage = resample.getOutputImage();
* </pre>
*
* <h3>Known problems</h3>
* <ul>
* <li>Scaling down certain images (with stripe or checkers patterns in them) will
* lead to moire effects in the resulting image.
* These effects can be somewhat reduced by scaling down in several step (e.g.
* first from 1600 x 1200 to 800 x 600, then from 800 x 600 to 400 x 300, and so on).</li>
* <li>Scaling down with filter type {@link #FILTER_TYPE_BOX} can lead to errors in the scaled image.
* No fix known yet. Workaround: Use the class {@link ScaleReplication}.</li>
* </ul>
*
* <h3>Origin</h3>
* This code is a port of Anders Melander's
* Object Pascal (Delphi) unit <tt>resample.pas</tt> to Java.
* The Delphi code is an adaptation (with some improvements) of
* Dale Schumacher's <tt>fzoom</tt> C code.
* <del>Check out the homepage for the Delphi resample code, a demo application
* to compare the different filtering algorithms is also provided:
* <a target="_top" href="http://www.melander.dk/delphi/resampler/index.html">http://www.melander.dk/delphi/resampler/index.html</a>.
* You will also find the original C code there.</del>
* <ins>The site seems to have gone for good.</ins>
*
* <h3>Theory</h3>
* The theoretical background for all implementations is Dale Schumacher's article
* <em>General Filtered Image Rescaling</em>
* in <em>Graphics Gems III</em>, editor David Kirk, Academic Press, pages 8-16, 1994.
* <p>
* The <em>Graphics Gems Repository</em> can be found at
* <a target="_top" href="http://www.acm.org/tog/GraphicsGems/">http://www.acm.org/tog/GraphicsGems/</a>.
* It also includes information on the books and how to order them.
*
* @author Marco Schmidt
*/
public class Resample extends ImageToImageOperation
{
/**
* Constant for the Box filter (also known as Nearest Neighbor filter).
*/
public static final int FILTER_TYPE_BOX = 0;
/**
* Constant for the Triangle filter (also known as Linear filter or Bilinear filter).
*/
public static final int FILTER_TYPE_TRIANGLE = 1;
/**
* Constant for the Hermite filter.
*/
public static final int FILTER_TYPE_HERMITE = 2;
/**
* Constant for the Bell filter.
*/
public static final int FILTER_TYPE_BELL = 3;
/**
* Constant for the B-Spline filter.
*/
public static final int FILTER_TYPE_B_SPLINE = 4;
/**
* Constant for the Lanczos3 filter.
*/
public static final int FILTER_TYPE_LANCZOS3 = 5;
/**
* Constant for the Mitchell filter.
*/
public static final int FILTER_TYPE_MITCHELL = 6;
class Contributor
{
int pixel; // Source pixel
float weight; // Pixel weight
}
class CList
{
int n;
Contributor[] p;
}
private Integer outWidth;
private Integer outHeight;
private ResampleFilter filter;
private static ResampleFilter createFilter(int filterType)
{
switch(filterType)
{
case(FILTER_TYPE_BOX): return new BoxFilter();
case(FILTER_TYPE_TRIANGLE): return new TriangleFilter();
case(FILTER_TYPE_HERMITE): return new HermiteFilter();
case(FILTER_TYPE_BELL): return new BellFilter();
case(FILTER_TYPE_B_SPLINE): return new BSplineFilter();
case(FILTER_TYPE_LANCZOS3): return new Lanczos3Filter();
case(FILTER_TYPE_MITCHELL): return new MitchellFilter();
default:
{
throw new IllegalArgumentException("Unknown filter type in Resample: " + filterType);
}
}
}
/**
* Returns the filter to be used in this operation.
* @return ResampleFilter object or <code>null</code> if none was defined yet
*/
public ResampleFilter getFilter()
{
return filter;
}
/**
* Returns the names of all predefined filters.
* Each FILTER_TYPE_xyz constant can be used as an index into the array that is returned.
* Names are retrieved by creating an object of each predefined filter class and calling its
* getName method.
* @return String array with filter names
*/
public static String[] getFilterNames()
{
String[] result = new String[getNumFilters()];
for (int i = 0; i < getNumFilters(); i++)
{
ResampleFilter filter = createFilter(i);
result[i] = filter.getName();
}
return result;
}
/**
* Returns the number of predefined filters.
* @return number of filters
*/
public static int getNumFilters()
{
return 7;
}
/**
* This method does the actual work of rescaling an image.
*/
private void process(IntegerImage in, IntegerImage out)
{
if (out == null)
{
out = (IntegerImage)in.createCompatibleImage(outWidth.intValue(), outHeight.intValue());
setOutputImage(out);
}
if (filter == null)
{
filter = new TriangleFilter();
}
float fwidth = filter.getSamplingRadius();
final int dstWidth = outWidth.intValue();
final int dstHeight = outHeight.intValue();
final int srcWidth = in.getWidth();
final int srcHeight = in.getHeight();
/* if (SrcWidth < 1) or (SrcHeight < 1) then
raise Exception.Create('Source bitmap too small');*/
// Create intermediate image to hold horizontal zoom
IntegerImage work = (IntegerImage)in.createCompatibleImage(dstWidth, srcHeight);
float xscale;
float yscale;
if (srcWidth == 1)
{
xscale = (float)dstWidth / (float)srcWidth;
}
else
{
xscale = (float)(dstWidth - 1) / (float)(srcWidth - 1);
}
if (srcHeight == 1)
{
yscale = (float)dstHeight / (float)srcHeight;
}
else
{
yscale = (float)(dstHeight - 1) / (float)(srcHeight - 1);
}
/* Marco: the following two variables are used for progress notification */
int processedItems = 0;
int totalItems = /*dstWidth +*/ srcHeight + /*dstHeight +*/ dstWidth;
// --------------------------------------------
// Pre-calculate filter contributions for a row
// -----------------------------------------------
CList[] contrib = new CList[dstWidth];
for (int i = 0; i < contrib.length; i++)
{
contrib[i] = new CList();
}
// Horizontal sub-sampling
// Scales from bigger to smaller width
if (xscale < 1.0f)
{
float width = fwidth / xscale;
float fscale = 1.0f / xscale;
int numPixels = (int)(width * 2.0f + 1);
for (int i = 0; i < dstWidth; i++)
{
contrib[i].n = 0;
contrib[i].p = new Contributor[numPixels];
for (int j = 0; j < contrib[i].p.length; j++)
{
contrib[i].p[j] = new Contributor();
}
float center = i / xscale;
int left = (int)Math.floor(center - width);
int right = (int)Math.ceil(center + width);
for (int j = left; j <= right; j++)
{
float weight = filter.apply((center - j) / fscale) / fscale;
if (weight == 0.0f)
{
continue;
}
int n;
if (j < 0)
{
n = -j;
}
else
if (j >= srcWidth)
{
n = srcWidth - j + srcWidth - 1;
}
else
{
n = j;
}
int k = contrib[i].n;
contrib[i].n = contrib[i].n + 1;
contrib[i].p[k].pixel = n;
contrib[i].p[k].weight = weight;
}
//setProgress(processedItems++, totalItems);
}
}
else
// Horizontal super-sampling
// Scales from smaller to bigger width
{
int numPixels = (int)(fwidth * 2.0f + 1);
for (int i = 0; i < dstWidth; i++)
{
contrib[i].n = 0;
contrib[i].p = new Contributor[numPixels];
for (int j = 0; j < contrib[i].p.length; j++)
{
contrib[i].p[j] = new Contributor();
}
float center = i / xscale;
int left = (int)Math.floor(center - fwidth);
int right = (int)Math.ceil(center + fwidth);
for (int j = left; j <= right; j++)
{
float weight = filter.apply(center - j);
if (weight == 0.0f)
{
continue;
}
int n;
if (j < 0)
{
n = -j;
}
else
if (j >= srcWidth)
{
n = srcWidth - j + srcWidth - 1;
}
else
{
n = j;
}
int k = contrib[i].n;
if (n < 0 || n >= srcWidth)
{
weight = 0.0f;
}
contrib[i].n = contrib[i].n + 1;
contrib[i].p[k].pixel = n;
contrib[i].p[k].weight = weight;
}
//setProgress(processedItems++, totalItems);
}
}
// ----------------------------------------------------
// Apply filter to sample horizontally from Src to Work
// ----------------------------------------------------
// start of Java-specific code
// Marco: adjusted code to work with multi-channel images
// where each channel can have a different maximum sample value (not only 255)
final int NUM_CHANNELS = work.getNumChannels();
final int[] MAX = new int[NUM_CHANNELS];
for (int k = 0; k < NUM_CHANNELS; k++)
{
MAX[k] = work.getMaxSample(k);
}
// end of Java-specific code
for (int k = 0; k < srcHeight; k++)
{
for (int i = 0; i < dstWidth; i++)
{
for (int channel = 0; channel < NUM_CHANNELS; channel++)
{
CList c=contrib[i];
float sample = 0.0f;
int max=c.n;
for (int j = 0; j < max; j++)
{
sample+=in.getSample(channel, c.p[j].pixel, k) * c.p[j].weight;
}
// Marco: procedure BoundRound included directly
int result = (int)sample;
if (result < 0)
{
result = 0;
}
else
if (result > MAX[channel])
{
result = MAX[channel];
}
work.putSample(channel, i, k, result);
}
}
setProgress(processedItems++, totalItems);
}
/* Marco: no need for "free memory" code as Java has garbage collection:
// Free the memory allocated for horizontal filter weights
for i := 0 to DstWidth-1 do
FreeMem(contrib^[i].p);
FreeMem(contrib);
*/
// -----------------------------------------------
// Pre-calculate filter contributions for a column
// -----------------------------------------------
/*GetMem(contrib, DstHeight* sizeof(TCList));*/
contrib = new CList[dstHeight];
for (int i = 0; i < contrib.length; i++)
{
contrib[i] = new CList();
}
// Vertical sub-sampling
// Scales from bigger to smaller height
if (yscale < 1.0f)
{
float width = fwidth / yscale;
float fscale = 1.0f / yscale;
int numContributors = (int)(width * 2.0f + 1);
for (int i = 0; i < dstHeight; i++)
{
contrib[i].n = 0;
contrib[i].p = new Contributor[numContributors];
for (int j = 0; j < contrib[i].p.length; j++)
{
contrib[i].p[j] = new Contributor();
}
float center = i / yscale;
int left = (int)Math.floor(center - width);
int right = (int)Math.ceil(center + width);
for (int j = left; j <= right; j++)
{
float weight = filter.apply((center - j) / fscale) / fscale;
// change suggested by Mike Dillon; not thoroughly tested;
// old version:
// float weight = filter.apply(center - j);
if (weight == 0.0f)
{
continue;
}
int n;
if (j < 0)
{
n = -j;
}
else
if (j >= srcHeight)
{
n = srcHeight - j + srcHeight - 1;
}
else
{
n = j;
}
int k = contrib[i].n;
contrib[i].n = contrib[i].n + 1;
if (n < 0 || n >= srcHeight)
{
weight = 0.0f;// Flag that cell should not be used
}
contrib[i].p[k].pixel = n;
contrib[i].p[k].weight = weight;
}
//setProgress(processedItems++, totalItems);
}
}
else
// Vertical super-sampling
// Scales from smaller to bigger height
{
int numContributors = (int)(fwidth * 2.0f + 1);
for (int i = 0; i < dstHeight; i++)
{
contrib[i].n = 0;
contrib[i].p = new Contributor[numContributors];
for (int j = 0; j < contrib[i].p.length; j++)
{
contrib[i].p[j] = new Contributor();
}
float center = i / yscale;
int left = (int)Math.floor(center - fwidth);
int right = (int)Math.ceil(center + fwidth);
for (int j = left; j <= right; j++)
{
float weight = filter.apply(center - j);
if (weight == 0.0f)
{
continue;
}
int n;
if (j < 0)
{
n = -j;
}
else
if (j >= srcHeight)
{
n = srcHeight - j + srcHeight - 1;
}
else
{
n = j;
}
int k = contrib[i].n;
contrib[i].n = contrib[i].n + 1;
if (n < 0 || n >= srcHeight)
{
weight = 0.0f;// Flag that cell should not be used
}
contrib[i].p[k].pixel = n;
contrib[i].p[k].weight = weight;
}
//setProgress(processedItems++, totalItems);
}
}
// --------------------------------------------------
// Apply filter to sample vertically from Work to Dst
// --------------------------------------------------
for (int k = 0; k < dstWidth; k++)
{
for (int i = 0; i < dstHeight; i++)
{
for (int channel = 0; channel < NUM_CHANNELS; channel++)
{
float sample = 0.0f;
CList c=contrib[i];
int max=c.n;
for (int j = 0; j < max; j++)
{
sample += work.getSample(channel, k, c.p[j].pixel) * c.p[j].weight;
}
int result = (int)sample;
if (result < 0)
{
result = 0;
}
else
if (result > MAX[channel])
{
result = MAX[channel];
}
out.putSample(channel, k, i, result);
}
}
setProgress(processedItems++, totalItems);
}
}
public void process() throws
MissingParameterException,
WrongParameterException
{
ensureInputImageIsAvailable();
if (outWidth == null && outHeight == null && getOutputImage() != null)
{
PixelImage out = getOutputImage();
outWidth = new Integer(out.getWidth());
outHeight = new Integer(out.getHeight());
}
if (outWidth == null)
{
throw new MissingParameterException("Output width has not been initialized");
}
if (outHeight == null)
{
throw new MissingParameterException("Output height has not been initialized");
}
PixelImage image = getInputImage();
if (image.getWidth() == outWidth.intValue() &&
image.getHeight() == outHeight.intValue())
{
throw new WrongParameterException("Input image already has the size specified by setSize.");
}
ensureOutputImageResolution(outWidth.intValue(), outHeight.intValue());
if (image instanceof IntegerImage)
{
process((IntegerImage)image, (IntegerImage)getOutputImage());
}
else
{
throw new WrongParameterException("Input image must implement IntegerImage.");
}
}
/**
* Set the pixel resolution of the output image.
* @param width the horizontal resolution of the output image
* @param height the vertical resolution of the output image
*/
public void setSize(int width, int height)
{
outWidth = new Integer(width);
outHeight = new Integer(height);
}
/**
* Set a new filter object to be used with this operation.
* @param newFilter a resample filter to be used for scaling
*/
public void setFilter(ResampleFilter newFilter)
{
filter = newFilter;
}
/**
* Sets a new filter type, using the default sampling radius of that filter.
* @param filterType the new filter type, one of the FILTER_TYPE_xyz constants of this class
*/
public void setFilter(int filterType)
{
setFilter(createFilter(filterType));
}
/**
* Sets a new filter type with a user-defined sampling radius.
* @param filterType the new filter type, one of the FILTER_TYPE_xyz constants of this class
* @param samplingRadius the sampling radius to be used with that filter, must be larger than 0.0f
*/
public void setFilter(int filterType, float samplingRadius)
{
ResampleFilter newFilter = createFilter(filterType);
newFilter.setSamplingRadius(samplingRadius);
setFilter(newFilter);
}
}
|