Clean-up of sandbox, rearranging everything.

Added a couple of files that was never commited.
This commit is contained in:
Harald Kuhr
2010-06-07 09:55:35 +02:00
parent 1f60b62626
commit b6ee5ce450
37 changed files with 5735 additions and 0 deletions

View File

@@ -0,0 +1,128 @@
/*
* Copyright (c) 2008, Harald Kuhr
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name "TwelveMonkeys" nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.twelvemonkeys.image;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.Kernel;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
/**
* ConvolveTester
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @author last modified by $Author: haku $
* @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-core/src/main/java/com/twelvemonkeys/image/ConvolveTester.java#1 $
*/
public class ConvolveTester {
// Initial sample timings (avg, 1000 iterations)
// PNG, type 0: JPEG, type 3:
// ZERO_FILL: 5.4 ms 4.6 ms
// NO_OP: 5.4 ms 4.6 ms
// REFLECT: 42.4 ms 24.9 ms
// WRAP: 86.9 ms 29.5 ms
final static int ITERATIONS = 1000;
public static void main(String[] pArgs) throws IOException {
File input = new File(pArgs[0]);
BufferedImage image = ImageIO.read(input);
BufferedImage result = null;
System.out.println("image: " + image);
if (pArgs.length > 1) {
float ammount = Float.parseFloat(pArgs[1]);
int edgeOp = pArgs.length > 2 ? Integer.parseInt(pArgs[2]) : ImageUtil.EDGE_REFLECT;
long start = System.currentTimeMillis();
for (int i = 0; i < ITERATIONS; i++) {
result = sharpen(image, ammount, edgeOp);
}
long end = System.currentTimeMillis();
System.out.println("Time: " + ((end - start) / (double) ITERATIONS) + "ms");
showIt(result, "Sharpened " + ammount + " " + input.getName());
}
else {
showIt(image, "Original " + input.getName());
}
}
public static void showIt(final BufferedImage pImage, final String pTitle) {
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
JFrame frame = new JFrame(pTitle);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
JPanel pane = new JPanel(new BorderLayout());
GraphicsConfiguration gc = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
BufferedImageIcon icon = new BufferedImageIcon(ImageUtil.accelerate(pImage, gc));
JScrollPane scroll = new JScrollPane(new JLabel(icon));
scroll.setBorder(null);
pane.add(scroll);
frame.setContentPane(pane);
frame.pack();
frame.setVisible(true);
}
});
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
static BufferedImage sharpen(BufferedImage pOriginal, final float pAmmount, int pEdgeOp) {
if (pAmmount == 0f) {
return pOriginal;
}
// Create the convolution matrix
float[] data = new float[]{
0.0f, -pAmmount, 0.0f,
-pAmmount, 4f * pAmmount + 1f, -pAmmount,
0.0f, -pAmmount, 0.0f
};
// Do the filtering
return ImageUtil.convolve(pOriginal, new Kernel(3, 3, data), pEdgeOp);
}
}

View File

@@ -0,0 +1,78 @@
/*
* Copyright (c) 2008, Harald Kuhr
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name "TwelveMonkeys" nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.twelvemonkeys.image;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.*;
import java.awt.image.renderable.RenderableImage;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* EasyImage
* <p/>
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-core/src/main/java/com/twelvemonkeys/image/EasyImage.java#1 $
*/
public class EasyImage extends BufferedImage {
public EasyImage(InputStream pInput) throws IOException {
this(ImageIO.read(pInput));
}
public EasyImage(BufferedImage pImage) {
this(pImage.getColorModel(), pImage.getRaster());
}
public EasyImage(RenderableImage pImage) {
this(pImage.createDefaultRendering());
}
public EasyImage(RenderedImage pImage) {
this(pImage.getColorModel(), pImage.copyData(pImage.getColorModel().createCompatibleWritableRaster(pImage.getWidth(), pImage.getHeight())));
}
public EasyImage(ImageProducer pImage) {
this(new BufferedImageFactory(pImage).getBufferedImage());
}
public EasyImage(Image pImage) {
this(new BufferedImageFactory(pImage).getBufferedImage());
}
private EasyImage(ColorModel cm, WritableRaster raster) {
super(cm, raster, cm.isAlphaPremultiplied(), null);
}
public boolean write(String pFormat, OutputStream pOutput) throws IOException {
return ImageIO.write(this, pFormat, pOutput);
}
}

View File

@@ -0,0 +1,61 @@
/*
* Copyright (c) 2008, Harald Kuhr
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name "TwelveMonkeys" nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.twelvemonkeys.image;
import java.awt.image.ImageConsumer;
import java.awt.image.ColorModel;
/**
* ExtendedImageConsumer
* <p/>
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-core/src/main/java/com/twelvemonkeys/image/ExtendedImageConsumer.java#1 $
*/
public interface ExtendedImageConsumer extends ImageConsumer {
/**
*
* @param pX
* @param pY
* @param pWidth
* @param pHeight
* @param pModel
* @param pPixels
* @param pOffset
* @param pScanSize
*/
public void setPixels(int pX, int pY, int pWidth, int pHeight,
ColorModel pModel,
short[] pPixels, int pOffset, int pScanSize);
// Allow for packed and interleaved models
public void setPixels(int pX, int pY, int pWidth, int pHeight,
ColorModel pModel,
byte[] pPixels, int pOffset, int pScanSize);
}

View File

@@ -0,0 +1,255 @@
package com.twelvemonkeys.image;
import javax.swing.*;
import java.awt.*;
import java.awt.color.ColorSpace;
import java.awt.image.*;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Random;
/**
* MappedBufferImage
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @author last modified by $Author: haraldk$
* @version $Id: MappedBufferImage.java,v 1.0 May 26, 2010 5:07:01 PM haraldk Exp$
*/
public class MappedBufferImage extends BufferedImage {
private static final boolean ALPHA = true;
public MappedBufferImage(ColorModel cm, MappedFileRaster raster, boolean isRasterPremultiplied) {
super(cm, raster, isRasterPremultiplied, null);
}
public static void main(String[] args) throws IOException {
int w = args.length > 0 ? Integer.parseInt(args[0]) : 6000;
int h = args.length > 1 ? Integer.parseInt(args[1]) : (args.length > 0 ? w * 2 / 3 : 4000);
DataBuffer buffer = new MappedFileBuffer(w, h, ALPHA ? 4 : 3, 1);
// Mix in some nice colors
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
int r = (int) ((x * y * 255.0) / (h * w));
int g = (int) (((w - x) * y * 255.0) / (h * w));
int b = (int) ((x * (h - y) * 255.0) / (h * w));
int off = (y * w + x) * (ALPHA ? 4 : 3);
if (ALPHA) {
int a = (int) (((w - x) * (h - y) * 255.0) / (h * w));
buffer.setElem(off++, 255 - a);
}
buffer.setElem(off++, b);
buffer.setElem(off++, g);
buffer.setElem(off, r);
}
}
ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
ComponentColorModel model = new ComponentColorModel(cs, ALPHA, false, ALPHA ? TRANSLUCENT : OPAQUE, DataBuffer.TYPE_BYTE);
BufferedImage image = new MappedBufferImage(model, new MappedFileRaster(w, h, buffer), false);
// Add some random dots (get out the coffee)
// int s = 300;
// int ws = w / s;
// int hs = h / s;
//
// Color[] colors = new Color[] {
// Color.WHITE, Color.ORANGE, Color.BLUE, Color.MAGENTA, Color.BLACK, Color.RED, Color.CYAN,
// Color.GRAY, Color.GREEN, Color.YELLOW, Color.PINK, Color.LIGHT_GRAY, Color.DARK_GRAY
// };
//
// Random r = new Random();
//
// for (int y = 0; y < hs - 1; y++) {
// for (int x = 0; x < ws - 1; x++) {
// Graphics2D g = image.getSubimage(x * s, y * s, 2 * s, 2 * s).createGraphics();
// try {
// g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// g.setComposite(AlphaComposite.SrcOver.derive(r.nextFloat()));
// g.setColor(colors[r.nextInt(colors.length)]);
// int o = r.nextInt(s) + s / 10;
// int c = (2 * s - o) / 2;
// g.fillOval(c, c, o, o);
// }
// finally {
// g.dispose();
// }
// }
// }
System.out.println("image = " + image);
JFrame frame = new JFrame(String.format("Test [%s x %s] (%s)", w, h, toHumanReadableSize(w * h * (ALPHA ? 4 : 3))));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JScrollPane scroll = new JScrollPane(new ImageComponent(image));
scroll.setBorder(BorderFactory.createEmptyBorder());
scroll.getViewport().setScrollMode(JViewport.SIMPLE_SCROLL_MODE);
scroll.getViewport().setDoubleBuffered(false);
frame.add(scroll);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static String toHumanReadableSize(long size) {
return String.format("%,d MB", (int) (size / (double) (1024L << 10)));
}
private static class ImageComponent extends JComponent implements Scrollable {
private final BufferedImage image;
private final Paint texture;
public ImageComponent(BufferedImage image) {
setDoubleBuffered(false);
this.image = image;
texture = createTexture();
}
private static Paint createTexture() {
GraphicsConfiguration graphicsConfiguration = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
BufferedImage pattern = graphicsConfiguration.createCompatibleImage(20, 20);
Graphics2D g = pattern.createGraphics();
try {
g.setColor(Color.LIGHT_GRAY);
g.fillRect(0, 0, pattern.getWidth(), pattern.getHeight());
g.setColor(Color.GRAY);
g.fillRect(0, 0, pattern.getWidth() / 2, pattern.getHeight() / 2);
g.fillRect(pattern.getWidth() / 2, pattern.getHeight() / 2, pattern.getWidth() / 2, pattern.getHeight() / 2);
}
finally {
g.dispose();
}
return new TexturePaint(pattern, new Rectangle(pattern.getWidth(), pattern.getHeight()));
}
@Override
protected void paintComponent(Graphics g) {
Insets insets = getInsets();
// We ant to paint only the visible part of the image
Rectangle rect = getVisibleRect();
Graphics2D g2 = (Graphics2D) g;
g2.setPaint(texture);
g2.fillRect(rect.x, rect.y, rect.width, rect.height);
try {
// Paint slices of the image, to preserve memory
// Make slices wide to conform to memory alignment of buffer
int sliceHeight = 200;
int slices = rect.height / sliceHeight;
for (int i = 0; i <= slices; i++) {
int h = i == slices ? Math.min(sliceHeight, image.getHeight() - (rect.y + i * sliceHeight)) : sliceHeight;
if (h == 0) {
break;
}
BufferedImage img = image.getSubimage(rect.x, rect.y + i * sliceHeight, rect.width, h);
g2.drawImage(img, insets.left + rect.x, insets.top + rect.y + i * sliceHeight, null);
}
// BufferedImage img = image.getSubimage(rect.x, rect.y, rect.width, rect.height);
// g2.drawImage(img, insets.left + rect.x, insets.top + rect.y, null);
}
catch (NullPointerException e) {
e.printStackTrace();
// Happens whenever apple.awt.OSXCachingSufraceManager runs out of memory
repaint(); // NOTE: Will cause a brief flash while the component is redrawn
}
}
@Override
public Dimension getPreferredSize() {
Insets insets = getInsets();
return new Dimension(image.getWidth() + insets.left + insets.right, image.getHeight() + insets.top + insets.bottom);
}
public Dimension getPreferredScrollableViewportSize() {
return getPreferredSize();
}
public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) {
return 10;
}
public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) {
switch (orientation) {
case SwingConstants.HORIZONTAL:
return visibleRect.width * 3 / 4;
case SwingConstants.VERTICAL:
default:
return visibleRect.height * 3 / 4;
}
}
public boolean getScrollableTracksViewportWidth() {
return false;
}
public boolean getScrollableTracksViewportHeight() {
return false;
}
}
private static class MappedFileBuffer extends DataBuffer {
final ByteBuffer buffer;
public MappedFileBuffer(final int width, final int height, final int numComponents, final int numBanks) throws IOException {
super(DataBuffer.TYPE_BYTE, width * height * numComponents, numBanks);
if (size < 0) {
throw new IllegalArgumentException("Integer overflow");
}
File tempFile = File.createTempFile(String.format("%s-", getClass().getSimpleName()), ".tmp");
tempFile.deleteOnExit();
RandomAccessFile raf = new RandomAccessFile(tempFile, "rw");
raf.setLength(size * banks);
FileChannel channel = raf.getChannel();
// Map entire file into memory, let OS virtual memory/paging do the heavy lifting
buffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, size * banks);
// According to the docs, we can safely close the channel and delete the file now
channel.close();
if (!tempFile.delete()) {
System.err.println("Could not delete temp file: " + tempFile.getAbsolutePath());
}
}
@Override
public int getElem(int bank, int i) {
return buffer.get(bank * size + i);
}
@Override
public void setElem(int bank, int i, int val) {
buffer.put(bank * size + i, (byte) val);
}
}
private static class MappedFileRaster extends WritableRaster {
public MappedFileRaster(int w, int h, DataBuffer buffer) {
super(
new PixelInterleavedSampleModel(DataBuffer.TYPE_BYTE, w, h, ALPHA ? 4 : 3, w * (ALPHA ? 4 : 3), ALPHA ? new int[]{3, 2, 1, 0} : new int[]{2, 1, 0}),
buffer, new Point()
);
}
@Override
public String toString() {
return String.format("%s@%s: w = %s h = %s", getClass().getSimpleName(), System.identityHashCode(this), getWidth(), getHeight());
}
}
}

View File

@@ -0,0 +1,163 @@
/*
* Copyright (c) 2008, Harald Kuhr
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name "TwelveMonkeys" nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.twelvemonkeys.image;
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
/**
* SubsampleTester
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @author last modified by $Author: haku $
* @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-core/src/main/java/com/twelvemonkeys/image/SubsampleTester.java#1 $
*/
public class SubsampleTester {
// Initial testing shows we need at least 9 pixels (sampleFactor == 3) to make a good looking image..
// Also, using Lanczos is much better than (and allmost as fast as) halving using AffineTransform
// - But I guess those numbers depend on the data type of the input image...
public static void main(String[] pArgs) throws IOException {
// To/from larger than or equal to 4x4
//ImageUtil.createResampled(new BufferedImage(5, 5, BufferedImage.TYPE_INT_ARGB), 4, 4, BufferedImage.SCALE_SMOOTH);
//ImageUtil.createResampled(new BufferedImage(4, 4, BufferedImage.TYPE_INT_ARGB), 5, 5, BufferedImage.SCALE_SMOOTH);
// To/from smaller than or equal to 4x4 with fast scale
//ImageUtil.createResampled(new BufferedImage(3, 3, BufferedImage.TYPE_INT_ARGB), 10, 10, BufferedImage.SCALE_FAST);
//ImageUtil.createResampled(new BufferedImage(10, 10, BufferedImage.TYPE_INT_ARGB), 3, 3, BufferedImage.SCALE_FAST);
// To/from smaller than or equal to 4x4 with default scale
//ImageUtil.createResampled(new BufferedImage(3, 3, BufferedImage.TYPE_INT_ARGB), 10, 10, BufferedImage.SCALE_DEFAULT);
//ImageUtil.createResampled(new BufferedImage(10, 10, BufferedImage.TYPE_INT_ARGB), 3, 3, BufferedImage.SCALE_DEFAULT);
// To/from smaller than or equal to 4x4 with smooth scale
try {
ImageUtil.createResampled(new BufferedImage(3, 3, BufferedImage.TYPE_INT_ARGB), 10, 10, BufferedImage.SCALE_SMOOTH);
}
catch (IndexOutOfBoundsException e) {
e.printStackTrace();
}
//try {
// ImageUtil.createResampled(new BufferedImage(10, 10, BufferedImage.TYPE_INT_ARGB), 3, 3, BufferedImage.SCALE_SMOOTH);
//}
//catch (IndexOutOfBoundsException e) {
// e.printStackTrace();
// return;
//}
File input = new File(pArgs[0]);
ImageInputStream stream = ImageIO.createImageInputStream(input);
Iterator<ImageReader> readers = ImageIO.getImageReaders(stream);
if (readers.hasNext()) {
if (stream == null) {
return;
}
ImageReader reader = readers.next();
reader.setInput(stream);
ImageReadParam param = reader.getDefaultReadParam();
for (int i = 0; i < 25; i++) {
//readImage(pArgs, reader, param);
}
long start = System.currentTimeMillis();
BufferedImage image = readImage(pArgs, reader, param);
long end = System.currentTimeMillis();
System.out.println("elapsed time: " + (end - start) + " ms");
int subX = param.getSourceXSubsampling();
int subY = param.getSourceYSubsampling();
System.out.println("image: " + image);
//ImageIO.write(image, "png", new File(input.getParentFile(), input.getName().replace('.', '_') + "_new.png"));
ConvolveTester.showIt(image, input.getName() + (subX > 1 || subY > 1 ? " (subsampled " + subX + " by " + subY + ")" : ""));
}
else {
System.err.println("No reader found for input: " + input.getAbsolutePath());
}
}
private static BufferedImage readImage(final String[] pArgs, final ImageReader pReader, final ImageReadParam pParam) throws IOException {
double sampleFactor; // Minimum number of samples (in each dimension) pr pixel in output
int width = pArgs.length > 1 ? Integer.parseInt(pArgs[1]) : 300;
int height = pArgs.length > 2 ? Integer.parseInt(pArgs[2]) : 200;
if (pArgs.length > 3 && (sampleFactor = Double.parseDouble(pArgs[3])) > 0) {
int originalWidth = pReader.getWidth(0);
int originalHeight = pReader.getHeight(0);
System.out.println("originalWidth: " + originalWidth);
System.out.println("originalHeight: " + originalHeight);
int subX = (int) Math.max(originalWidth / (double) (width * sampleFactor), 1.0);
int subY = (int) Math.max(originalHeight / (double) (height * sampleFactor), 1.0);
if (subX > 1 || subY > 1) {
System.out.println("subX: " + subX);
System.out.println("subY: " + subY);
pParam.setSourceSubsampling(subX, subY, subX > 1 ? subX / 2 : 0, subY > 1 ? subY / 2 : 0);
}
}
BufferedImage image = pReader.read(0, pParam);
System.out.println("image: " + image);
int algorithm = BufferedImage.SCALE_DEFAULT;
if (pArgs.length > 4) {
if ("smooth".equals(pArgs[4].toLowerCase())) {
algorithm = BufferedImage.SCALE_SMOOTH;
}
else if ("fast".equals(pArgs[4].toLowerCase())) {
algorithm = BufferedImage.SCALE_FAST;
}
}
if (image.getWidth() != width || image.getHeight() != height) {
image = ImageUtil.createScaled(image, width, height, algorithm);
}
return image;
}
}

View File

@@ -0,0 +1,524 @@
/*
* This software is copyrighted as noted below. It may be freely copied,
* modified, and redistributed, provided that the copyright notice 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 giving the
* name of the person performing the modification, the date of modification,
* and the reason for such modification.
*/
/*
* inv_cmap.c - Compute an inverse colormap.
*
* Author: Spencer W. Thomas
* EECS Dept.
* University of Michigan
* Date: Thu Sep 20 1990
* Copyright (c) 1990, University of Michigan
*
* $Id: inv_cmap.c,v 3.0.1.3 1992/04/30 14:07:28 spencer Exp $
*/
#include <math.h>
#include <stdio.h>
static int bcenter, gcenter, rcenter;
static long gdist, rdist, cdist;
static long cbinc, cginc, crinc;
static unsigned long *gdp, *rdp, *cdp;
static unsigned char *grgbp, *rrgbp, *crgbp;
static gstride, rstride;
static long x, xsqr, colormax;
static int cindex;
#ifdef USE_PROTOTYPES
static void maxfill( unsigned long *, long );
static int redloop( void );
static int greenloop( int );
static int blueloop( int );
#else
static void maxfill();
static int redloop();
static int greenloop();
static int blueloop();
#endif
/*****************************************************************
* TAG( inv_cmap )
*
* Compute an inverse colormap efficiently.
* Inputs:
* colors: Number of colors in the forward colormap.
* colormap: The forward colormap.
* bits: Number of quantization bits. The inverse
* colormap will have (2^bits)^3 entries.
* dist_buf: An array of (2^bits)^3 long integers to be
* used as scratch space.
* Outputs:
* rgbmap: The output inverse colormap. The entry
* rgbmap[(r<<(2*bits)) + (g<<bits) + b]
* is the colormap entry that is closest to the
* (quantized) color (r,g,b).
* Assumptions:
* Quantization is performed by right shift (low order bits are
* truncated). Thus, the distance to a quantized color is
* actually measured to the color at the center of the cell
* (i.e., to r+.5, g+.5, b+.5, if (r,g,b) is a quantized color).
* Algorithm:
* Uses a "distance buffer" algorithm:
* The distance from each representative in the forward color map
* to each point in the rgb space is computed. If it is less
* than the distance currently stored in dist_buf, then the
* corresponding entry in rgbmap is replaced with the current
* representative (and the dist_buf entry is replaced with the
* new distance).
*
* The distance computation uses an efficient incremental formulation.
*
* Distances are computed "outward" from each color. If the
* colors are evenly distributed in color space, the expected
* number of cells visited for color I is N^3/I.
* Thus, the complexity of the algorithm is O(log(K) N^3),
* where K = colors, and N = 2^bits.
*/
/*
* Here's the idea: scan from the "center" of each cell "out"
* until we hit the "edge" of the cell -- that is, the point
* at which some other color is closer -- and stop. In 1-D,
* this is simple:
* for i := here to max do
* if closer then buffer[i] = this color
* else break
* repeat above loop with i := here-1 to min by -1
*
* In 2-D, it's trickier, because along a "scan-line", the
* region might start "after" the "center" point. A picture
* might clarify:
* | ...
* | ... .
* ... .
* ... | .
* . + .
* . .
* . .
* .........
*
* The + marks the "center" of the above region. On the top 2
* lines, the region "begins" to the right of the "center".
*
* Thus, we need a loop like this:
* detect := false
* for i := here to max do
* if closer then
* buffer[..., i] := this color
* if !detect then
* here = i
* detect = true
* else
* if detect then
* break
*
* Repeat the above loop with i := here-1 to min by -1. Note that
* the "detect" value should not be reinitialized. If it was
* "true", and center is not inside the cell, then none of the
* cell lies to the left and this loop should exit
* immediately.
*
* The outer loops are similar, except that the "closer" test
* is replaced by a call to the "next in" loop; its "detect"
* value serves as the test. (No assignment to the buffer is
* done, either.)
*
* Each time an outer loop starts, the "here", "min", and
* "max" values of the next inner loop should be
* re-initialized to the center of the cell, 0, and cube size,
* respectively. Otherwise, these values will carry over from
* one "call" to the inner loop to the next. This tracks the
* edges of the cell and minimizes the number of
* "unproductive" comparisons that must be made.
*
* Finally, the inner-most loop can have the "if !detect"
* optimized out of it by splitting it into two loops: one
* that finds the first color value on the scan line that is
* in this cell, and a second that fills the cell until
* another one is closer:
* if !detect then {needed for "down" loop}
* for i := here to max do
* if closer then
* buffer[..., i] := this color
* detect := true
* break
* for i := i+1 to max do
* if closer then
* buffer[..., i] := this color
* else
* break
*
* In this implementation, each level will require the
* following variables. Variables labelled (l) are local to each
* procedure. The ? should be replaced with r, g, or b:
* cdist: The distance at the starting point.
* ?center: The value of this component of the color
* c?inc: The initial increment at the ?center position.
* ?stride: The amount to add to the buffer
* pointers (dp and rgbp) to get to the
* "next row".
* min(l): The "low edge" of the cell, init to 0
* max(l): The "high edge" of the cell, init to
* colormax-1
* detect(l): True if this row has changed some
* buffer entries.
* i(l): The index for this row.
* ?xx: The accumulated increment value.
*
* here(l): The starting index for this color. The
* following variables are associated with here,
* in the sense that they must be updated if here
* is changed.
* ?dist: The current distance for this level. The
* value of dist from the previous level (g or r,
* for level b or g) initializes dist on this
* level. Thus gdist is associated with here(b)).
* ?inc: The initial increment for the row.
* ?dp: Pointer into the distance buffer. The value
* from the previous level initializes this level.
* ?rgbp: Pointer into the rgb buffer. The value
* from the previous level initializes this level.
*
* The blue and green levels modify 'here-associated' variables (dp,
* rgbp, dist) on the green and red levels, respectively, when here is
* changed.
*/
void
inv_cmap( colors, colormap, bits, dist_buf, rgbmap )
int colors, bits;
unsigned char *colormap[3], *rgbmap;
unsigned long *dist_buf;
{
int nbits = 8 - bits;
colormax = 1 << bits;
x = 1 << nbits;
xsqr = 1 << (2 * nbits);
/* Compute "strides" for accessing the arrays. */
gstride = colormax;
rstride = colormax * colormax;
maxfill( dist_buf, colormax );
for ( cindex = 0; cindex < colors; cindex++ )
{
/*
* Distance formula is
* (red - map[0])^2 + (green - map[1])^2 + (blue - map[2])^2
*
* Because of quantization, we will measure from the center of
* each quantized "cube", so blue distance is
* (blue + x/2 - map[2])^2,
* where x = 2^(8 - bits).
* The step size is x, so the blue increment is
* 2*x*blue - 2*x*map[2] + 2*x^2
*
* Now, b in the code below is actually blue/x, so our
* increment will be 2*(b*x^2 + x^2 - x*map[2]). For
* efficiency, we will maintain this quantity in a separate variable
* that will be updated incrementally by adding 2*x^2 each time.
*/
/* The initial position is the cell containing the colormap
* entry. We get this by quantizing the colormap values.
*/
rcenter = colormap[0][cindex] >> nbits;
gcenter = colormap[1][cindex] >> nbits;
bcenter = colormap[2][cindex] >> nbits;
rdist = colormap[0][cindex] - (rcenter * x + x/2);
gdist = colormap[1][cindex] - (gcenter * x + x/2);
cdist = colormap[2][cindex] - (bcenter * x + x/2);
cdist = rdist*rdist + gdist*gdist + cdist*cdist;
crinc = 2 * ((rcenter + 1) * xsqr - (colormap[0][cindex] * x));
cginc = 2 * ((gcenter + 1) * xsqr - (colormap[1][cindex] * x));
cbinc = 2 * ((bcenter + 1) * xsqr - (colormap[2][cindex] * x));
/* Array starting points. */
cdp = dist_buf + rcenter * rstride + gcenter * gstride + bcenter;
crgbp = rgbmap + rcenter * rstride + gcenter * gstride + bcenter;
(void)redloop();
}
}
/* redloop -- loop up and down from red center. */
static int
redloop()
{
int detect;
int r;
int first;
long txsqr = xsqr + xsqr;
static long rxx;
detect = 0;
/* Basic loop up. */
for ( r = rcenter, rdist = cdist, rxx = crinc,
rdp = cdp, rrgbp = crgbp, first = 1;
r < colormax;
r++, rdp += rstride, rrgbp += rstride,
rdist += rxx, rxx += txsqr, first = 0 )
{
if ( greenloop( first ) )
detect = 1;
else if ( detect )
break;
}
/* Basic loop down. */
for ( r = rcenter - 1, rxx = crinc - txsqr, rdist = cdist - rxx,
rdp = cdp - rstride, rrgbp = crgbp - rstride, first = 1;
r >= 0;
r--, rdp -= rstride, rrgbp -= rstride,
rxx -= txsqr, rdist -= rxx, first = 0 )
{
if ( greenloop( first ) )
detect = 1;
else if ( detect )
break;
}
return detect;
}
/* greenloop -- loop up and down from green center. */
static int
greenloop( restart )
int restart;
{
int detect;
int g;
int first;
long txsqr = xsqr + xsqr;
static int here, min, max;
static long ginc, gxx, gcdist; /* "gc" variables maintain correct */
static unsigned long *gcdp; /* values for bcenter position, */
static unsigned char *gcrgbp; /* despite modifications by blueloop */
/* to gdist, gdp, grgbp. */
if ( restart )
{
here = gcenter;
min = 0;
max = colormax - 1;
ginc = cginc;
}
detect = 0;
/* Basic loop up. */
for ( g = here, gcdist = gdist = rdist, gxx = ginc,
gcdp = gdp = rdp, gcrgbp = grgbp = rrgbp, first = 1;
g <= max;
g++, gdp += gstride, gcdp += gstride, grgbp += gstride, gcrgbp += gstride,
gdist += gxx, gcdist += gxx, gxx += txsqr, first = 0 )
{
if ( blueloop( first ) )
{
if ( !detect )
{
/* Remember here and associated data! */
if ( g > here )
{
here = g;
rdp = gcdp;
rrgbp = gcrgbp;
rdist = gcdist;
ginc = gxx;
}
detect = 1;
}
}
else if ( detect )
{
break;
}
}
/* Basic loop down. */
for ( g = here - 1, gxx = ginc - txsqr, gcdist = gdist = rdist - gxx,
gcdp = gdp = rdp - gstride, gcrgbp = grgbp = rrgbp - gstride,
first = 1;
g >= min;
g--, gdp -= gstride, gcdp -= gstride, grgbp -= gstride, gcrgbp -= gstride,
gxx -= txsqr, gdist -= gxx, gcdist -= gxx, first = 0 )
{
if ( blueloop( first ) )
{
if ( !detect )
{
/* Remember here! */
here = g;
rdp = gcdp;
rrgbp = gcrgbp;
rdist = gcdist;
ginc = gxx;
detect = 1;
}
}
else if ( detect )
{
break;
}
}
return detect;
}
/* blueloop -- loop up and down from blue center. */
static int
blueloop( restart )
int restart;
{
int detect;
register unsigned long *dp;
register unsigned char *rgbp;
register long bdist, bxx;
register int b, i = cindex;
register long txsqr = xsqr + xsqr;
register int lim;
static int here, min, max;
static long binc;
if ( restart )
{
here = bcenter;
min = 0;
max = colormax - 1;
binc = cbinc;
}
detect = 0;
/* Basic loop up. */
/* First loop just finds first applicable cell. */
for ( b = here, bdist = gdist, bxx = binc, dp = gdp, rgbp = grgbp, lim = max;
b <= lim;
b++, dp++, rgbp++,
bdist += bxx, bxx += txsqr )
{
if ( *dp > bdist )
{
/* Remember new 'here' and associated data! */
if ( b > here )
{
here = b;
gdp = dp;
grgbp = rgbp;
gdist = bdist;
binc = bxx;
}
detect = 1;
break;
}
}
/* Second loop fills in a run of closer cells. */
for ( ;
b <= lim;
b++, dp++, rgbp++,
bdist += bxx, bxx += txsqr )
{
if ( *dp > bdist )
{
*dp = bdist;
*rgbp = i;
}
else
{
break;
}
}
/* Basic loop down. */
/* Do initializations here, since the 'find' loop might not get
* executed.
*/
lim = min;
b = here - 1;
bxx = binc - txsqr;
bdist = gdist - bxx;
dp = gdp - 1;
rgbp = grgbp - 1;
/* The 'find' loop is executed only if we didn't already find
* something.
*/
if ( !detect )
for ( ;
b >= lim;
b--, dp--, rgbp--,
bxx -= txsqr, bdist -= bxx )
{
if ( *dp > bdist )
{
/* Remember here! */
/* No test for b against here necessary because b <
* here by definition.
*/
here = b;
gdp = dp;
grgbp = rgbp;
gdist = bdist;
binc = bxx;
detect = 1;
break;
}
}
/* The 'update' loop. */
for ( ;
b >= lim;
b--, dp--, rgbp--,
bxx -= txsqr, bdist -= bxx )
{
if ( *dp > bdist )
{
*dp = bdist;
*rgbp = i;
}
else
{
break;
}
}
/* If we saw something, update the edge trackers. */
return detect;
}
static void
maxfill( buffer, side )
unsigned long *buffer;
long side;
{
register unsigned long maxv = ~0L;
register long i;
register unsigned long *bp;
for ( i = side * side * side, bp = buffer;
i > 0;
i--, bp++ )
*bp = maxv;
}