下面列出了java.awt.image.Raster#getPixel() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Setup
public void setUp() throws IOException {
BufferedImage image = ImageIO.read(getClass().getClassLoader().getResourceAsStream(TEST_IMAGE));
int numPixels = image.getWidth() * image.getHeight();
pixels = NdArrays.ofFloats(Shape.of(numPixels, 3));
channels = NdArrays.ofFloats(Shape.of(3, numPixels));
Raster imageData = image.getData();
float[] pixel = new float[3];
for (int y = 0, pixelIdx = 0; y < image.getHeight(); ++y) {
for (int x = 0; x < image.getWidth(); ++x, ++pixelIdx) {
imageData.getPixel(x, y, pixel);
StdArrays.copyTo(pixels.get(pixelIdx), pixel);
StdArrays.copyTo(channels.slice(all(), at(pixelIdx)), pixel);
}
}
batches = NdArrays.ofFloats(Shape.of(BATCH_SIZE, 3, numPixels));
firstBatch = batches.get(0);
}
@Test
public void testPaint() throws IOException {
BufferedImage img = ImageIO.read(getClass().getResourceAsStream(
"/org/geomajas/plugin/rasterizing/images/testIcon.png"));
RenderedImageIcon icon = new RenderedImageIcon(img, 24, 24);
BufferedImage copy = new BufferedImage(24, 24, BufferedImage.TYPE_4BYTE_ABGR);
icon.paintIcon(null, copy.getGraphics(), 0, 0);
copy.getGraphics().dispose();
//ImageIO.write(copy, "png", new FileOutputStream("my.png"));
Raster r1 = img.getData();
Raster r2 = copy.getData();
for (int i = 0; i < 24; i++) {
for (int j = 0; j < 24; j++) {
int[] p1 = r1.getPixel(i, j, (int[]) null);
int[] p2 = r2.getPixel(i, j, (int[]) null);
Assert.assertArrayEquals(p2, p1);
}
}
}
/**
* 元画像の積分画像を生成します。
*
* @param source 元画像
* @return 積分結果の配列
*/
public static double[][] calcIntegralImage(BufferedImage source) {
double[][] integralImage = new double[source.getHeight()][source.getWidth()];
Raster raster = source.getRaster();
int[] pixel = new int[raster.getNumBands()];
double leftNum;
double upNum;
double leftUpNum;
for (int y = 0; y < source.getHeight(); y++) {
for (int x = 0; x < source.getWidth(); x++) {
leftNum = (x == 0) ? 0 : integralImage[y][x - 1];
upNum = (y == 0) ? 0 : integralImage[y - 1][x];
leftUpNum = (x == 0 || y == 0) ? 0 : integralImage[y - 1][x - 1];
try {
integralImage[y][x] = leftNum + upNum + raster.getPixel(x, y, pixel)[0] - leftUpNum;
} catch (Exception e) {
e.printStackTrace();
}
}
}
return integralImage;
}
private static BufferedImage convertCMYKToRGB(Raster raster) throws IOException {
int width = raster.getWidth();
int height = raster.getHeight();
BufferedImage rgbImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
int[] cmyk = new int[4];
int r, g, b, p;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
cmyk = raster.getPixel(x, y, cmyk);
r = ((cmyk[0]) * (cmyk[3])) / 255;
g = ((cmyk[1]) * (cmyk[3])) / 255;
b = ((cmyk[2]) * (cmyk[3])) / 255;
p = (r << 16) | (g << 8) | b;
rgbImage.setRGB(x, y, p);
}
}
return rgbImage;
}
private void dumpPixels (int x0,
int y0,
int w,
int h)
{
Raster raster = image.getData();
int[] pixel = null;
System.out.print("pixels=");
for (int y = y0; y < y0+h; y++) {
System.out.println();
for (int x = x0; x <= x0+w; x++) {
pixel = raster.getPixel(x, y, pixel);
System.out.print(" [");
for (int i = 0; i < pixel.length; i++) {
System.out.print(String.format("%3x", pixel[i]));
}
System.out.print("]");
}
}
System.out.println();
}
/**
* returns all UEP with a threshold > min in a pointlist.
* The UEP process has to be applied before!
*
* @param img
* @param min
* @return
*/
private List<Point> reportPoints(PlanarImage img, int min) {
Raster r = img.getData();
int[] rgb = new int[3];
double d;
List<Point> pList = new ArrayList<Point>();
for (int x = 0; x < img.getWidth(); x++)
for (int y = 0; y < img.getHeight(); y++) {
rgb = r.getPixel(x, y, rgb);
d = (rgb[0]);
if (d > min) {
Point p = new Point(x, y);
pList.add(p);
if (logger.isTraceEnabled()) {
logger.trace(x + "," + y + ": " + d);
}
}
}
return pList;
}
/**
* Creats a binary ImagePlus based on a planar image. If a pixel is fg it is set to white, otherwise to black.
*
* @param image
* @param fg
* @return
*/
public static ImagePlus toBinaryImagePlus(PlanarImage image, Color fg) {
if (image == null || (image.getWidth() * image.getHeight() > 6000 * 6000L))
throw new IllegalArgumentException("this implementation can only handle images where width*height<=6000*6000. (And image cannot be null)");
int width = image.getWidth();
int height = image.getHeight();
Raster raster = image.getData();
int[] arr = new int[4];
// set background to black and foreground to white for imageJ watershed
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
int b = 0;
for (int y = b; y < height - b; y++) {
for (int x = b; x < width - b; x++) {
arr = raster.getPixel(x, y, arr);
if (arr[0] == fg.getRed() && arr[1] == fg.getGreen() && arr[2] == fg.getBlue()) {
bi.setRGB(x, y, Color.WHITE.getRGB());
} else {
bi.setRGB(x, y, Color.BLACK.getRGB());
}
}
}
ImagePlus ip = new ImagePlus("watershed", bi);
return ip;
}
public CompositeContext createContext( ColorModel srcColorModel, ColorModel dstColorModel, RenderingHints hints )
{
final Composer c;
if ( srcColorModel.getNumColorComponents() > 1 )
{
if ( srcColorModel.hasAlpha() )
c = new ARGB2ARGB();
else
c = new RGB2ARGB();
}
else
c = new Gray2ARGB();
return new CompositeContext()
{
private Composer composer = c;
public void compose( Raster src, Raster dstIn, WritableRaster dstOut )
{
final int[] srcPixel = new int[ 4 ];
final int[] dstInPixel = new int[ 4 ];
for ( int x = 0; x < dstOut.getWidth(); x++ )
{
for ( int y = 0; y < dstOut.getHeight(); y++ )
{
src.getPixel( x, y, srcPixel );
dstIn.getPixel( x, y, dstInPixel );
composer.compose( srcPixel, dstInPixel, alpha );
dstOut.setPixel( x, y, dstInPixel );
}
}
}
public void dispose()
{}
};
}
public void runTest(Object context, int numReps) {
Raster ras = ((Context) context).ras;
int pixeldata[] = ((Context) context).pixeldata;
do {
ras.getPixel(numReps&7, 0, pixeldata);
} while (--numReps > 0);
}
public CompositeContext createContext( ColorModel srcColorModel, ColorModel dstColorModel, RenderingHints hints )
{
final Composer c;
if ( srcColorModel.getNumColorComponents() > 1 )
{
if ( srcColorModel.hasAlpha() )
c = new ARGB2ARGB();
else
c = new RGB2ARGB();
}
else
c = new Gray2ARGB();
return new CompositeContext()
{
private Composer composer = c;
public void compose( Raster src, Raster dstIn, WritableRaster dstOut )
{
final int[] srcPixel = new int[ 4 ];
final int[] dstInPixel = new int[ 4 ];
for ( int x = 0; x < dstOut.getWidth(); x++ )
{
for ( int y = 0; y < dstOut.getHeight(); y++ )
{
src.getPixel( x, y, srcPixel );
dstIn.getPixel( x, y, dstInPixel );
composer.compose( srcPixel, dstInPixel, alpha );
dstOut.setPixel( x, y, dstInPixel );
}
}
}
public void dispose()
{}
};
}
public CompositeContext createContext( ColorModel srcColorModel, ColorModel dstColorModel, RenderingHints hints )
{
final Composer c;
if ( srcColorModel.getNumColorComponents() > 1 )
{
if ( srcColorModel.hasAlpha() )
c = new ARGB2ARGB();
else
c = new RGB2ARGB();
}
else
c = new Gray2ARGB();
return new CompositeContext()
{
private Composer composer = c;
public void compose( Raster src, Raster dstIn, WritableRaster dstOut )
{
final int[] srcPixel = new int[ 4 ];
final int[] dstInPixel = new int[ 4 ];
for ( int x = 0; x < dstOut.getWidth(); x++ )
{
for ( int y = 0; y < dstOut.getHeight(); y++ )
{
src.getPixel( x, y, srcPixel );
dstIn.getPixel( x, y, dstInPixel );
composer.compose( srcPixel, dstInPixel, alpha );
dstOut.setPixel( x, y, dstInPixel );
}
}
}
public void dispose()
{}
};
}
public static double[][] getLevels(BufferedImage image) {
BufferedImage grayImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
Graphics g = grayImage.getGraphics();
g.drawImage(image, 0, 0, null);
g.dispose();
Raster imageData = grayImage.getData();
double[][] levels = new double[imageData.getWidth()][imageData.getHeight()];
for (int i=0; i<imageData.getWidth(); ++i) {
for (int j=0; j<imageData.getHeight(); ++j) {
levels[i][j] = imageData.getPixel(i, j, (double[]) null)[0];
}
}
return levels;
}
public Tensor<Float> convertBufferedImageToTensor(BufferedImage image) {
//if (image.getWidth()!=DESIRED_SIZE || image.getHeight()!=DESIRED_SIZE)
{
// also make it an RGB image
image = resize(image,DESIRED_SIZE, DESIRED_SIZE);
// image = resize(image,image.getWidth(), image.getHeight());
}
int width = image.getWidth();
int height = image.getHeight();
Raster r = image.getRaster();
int[] rgb = new int[3];
//int[] data = new int[width * height];
//image.getRGB(0, 0, width, height, data, 0, width);
float[][][][] rgbArray = new float[1][height][width][3];
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
//Color color = new Color(data[i * width + j]);
// rgbArray[0][i][j][0] = color.getRed() - MEAN_PIXEL[0];
// rgbArray[0][i][j][1] = color.getGreen() - MEAN_PIXEL[1];
// rgbArray[0][i][j][2] = color.getBlue() - MEAN_PIXEL[2];
rgb = r.getPixel(j,i,rgb);
rgbArray[0][i][j][0] = rgb[0] - MEAN_PIXEL[0];
rgbArray[0][i][j][1] = rgb[1] - MEAN_PIXEL[1];
rgbArray[0][i][j][2] = rgb[2] - MEAN_PIXEL[2];
}
}
return Tensor.create(rgbArray, Float.class);
}
public void runTest(Object context, int numReps) {
Raster ras = ((Context) context).ras;
int pixeldata[] = ((Context) context).pixeldata;
do {
ras.getPixel(numReps&7, 0, pixeldata);
} while (--numReps > 0);
}
public CompositeContext createContext( ColorModel srcColorModel, ColorModel dstColorModel, RenderingHints hints )
{
final Composer c;
if ( srcColorModel.getNumColorComponents() > 1 )
{
if ( srcColorModel.hasAlpha() )
c = new ARGB2ARGB();
else
c = new RGB2ARGB();
}
else
c = new Gray2ARGB();
return new CompositeContext()
{
private Composer composer = c;
public void compose( Raster src, Raster dstIn, WritableRaster dstOut )
{
final int[] srcPixel = new int[ 4 ];
final int[] dstInPixel = new int[ 4 ];
for ( int x = 0; x < dstOut.getWidth(); x++ )
{
for ( int y = 0; y < dstOut.getHeight(); y++ )
{
src.getPixel( x, y, srcPixel );
dstIn.getPixel( x, y, dstInPixel );
composer.compose( srcPixel, dstInPixel, alpha );
dstOut.setPixel( x, y, dstInPixel );
}
}
}
public void dispose()
{}
};
}
private double[] buildIntensFeatures(final Raster r, final int x, final int y, final double classVal) throws OrbitImageServletException {
// init
for (int i = 0; i < samples; i++) {
mean[i] = 0d;
}
if (r != null) // faster if raster is pre-assigned (e.g. the shape fits into memory)
{
buf = r.getPixels(x - windowSize, y - windowSize, (windowSize * 2) + 1, (windowSize * 2) + 1, buf);
p = r.getPixel(x, y, p); // mid-pixel
} else { // slower, but works for very large shapes
Raster r2 = bimg.getData(new Rectangle(x - windowSize, y - windowSize, (windowSize * 2) + 1, (windowSize * 2) + 1), featureDescription);
if (r2 == null) System.out.println("r2 is null!!");
buf = r2.getPixels(x - windowSize, y - windowSize, (windowSize * 2) + 1, (windowSize * 2) + 1, buf);
p = r2.getPixel(x, y, p);
}
for (int i = 0; i < samples; i++) {
mean[0] += p[i];
}
mean[0] /= (double) samples;
double[] feats = new double[featuresPerSample * samples + 1];
for (int i = 0; i < samples; i++) {
if ((i == 0) && (featureDescription.isSkipRed())) continue;
if ((i == 1) && (featureDescription.isSkipGreen())) continue;
if ((i == 2) && (featureDescription.isSkipBlue())) continue;
feats[(samples * 0) + i] = mean[i];
}
feats[feats.length - 1] = classVal;
//logger.trace(Arrays.toString(feats));
return feats;
}
private List<Ruling> getVerticalRulings(BufferedImage image) {
// get all vertical edges, which we'll define as a change in grayscale colour
// along a straight line of a certain length
ArrayList<Ruling> verticalRulings = new ArrayList<>();
Raster r = image.getRaster();
int width = r.getWidth();
int height = r.getHeight();
for (int y = 0; y < height; y++) {
int[] lastPixel = r.getPixel(0, y, (int[]) null);
for (int x = 1; x < width - 1; x++) {
int[] currPixel = r.getPixel(x, y, (int[]) null);
int diff = Math.abs(currPixel[0] - lastPixel[0]);
if (diff > GRAYSCALE_INTENSITY_THRESHOLD) {
// we hit what could be a line
// don't bother scanning it if we've hit a pixel in the line before
boolean alreadyChecked = false;
for (Line2D.Float line : verticalRulings) {
if (x == line.getX1() && y >= line.getY1() && y <= line.getY2()) {
alreadyChecked = true;
break;
}
}
if (alreadyChecked) {
lastPixel = currPixel;
continue;
}
int lineY = y + 1;
while (lineY < height) {
int[] linePixel = r.getPixel(x, lineY, (int[]) null);
int[] leftPixel = r.getPixel(x - 1, lineY, (int[]) null);
if (Math.abs(linePixel[0] - leftPixel[0]) <= GRAYSCALE_INTENSITY_THRESHOLD
|| Math.abs(currPixel[0] - linePixel[0]) > GRAYSCALE_INTENSITY_THRESHOLD) {
break;
}
lineY++;
}
int endY = lineY - 1;
int lineLength = endY - y;
if (lineLength > VERTICAL_EDGE_HEIGHT_MINIMUM) {
verticalRulings.add(new Ruling(new Point2D.Float(x, y), new Point2D.Float(x, endY)));
}
}
lastPixel = currPixel;
}
}
return verticalRulings;
}
@SuppressWarnings("SameParameterValue")
public static void checkImage(BufferedImage image, String path, String gfName) throws Exception {
String[] testDataVariant = {
"osx_hardware_rendering", "osx_software_rendering",
"osx_sierra_rendering", "osx_lowres_rendering",
"linux_rendering", "windows_rendering", "windows7_rendering"};
String testDataStr = System.getProperty("testdata");
assertNotNull("testdata property is not set", testDataStr);
File testData = new File(testDataStr, "quality" + File.separator + path);
assertTrue("Test data dir does not exist", testData.exists());
if (System.getProperty("gentestdata") == null) {
boolean failed = true;
StringBuilder failureReason = new StringBuilder();
for (String variant : testDataVariant) {
File goldenFile = new File(testData, variant + File.separator +
gfName);
if (!goldenFile.exists()) continue;
BufferedImage goldenImage = ImageIO.read(goldenFile);
assertNotNull("no registered ImageReader claims to be able to read the stream: "
+ goldenFile, goldenImage);
failed = true;
if (image.getWidth() != goldenImage.getWidth() ||
image.getHeight() != image.getHeight()) {
failureReason.append(variant).append(" : Golden image and result have different sizes\n");
continue;
}
Raster gRaster = goldenImage.getData();
Raster rRaster = image.getData();
int[] gArr = new int[3];
int[] rArr = new int[3];
failed = false;
scan:
for (int i = 0; i < gRaster.getWidth(); i++) {
for (int j = 0; j < gRaster.getHeight(); j++) {
gRaster.getPixel(i, j, gArr);
rRaster.getPixel(i, j, rArr);
assertTrue(gArr.length == rArr.length);
for (int k = 0; k < gArr.length; k++) {
if (gArr[k] != rArr[k]) {
failureReason.append(variant).append(" : Different pixels found ").
append("at (").append(i).append(",").append(j).append(")");
failed = true;
break scan;
}
}
}
}
if (!failed) break;
}
if (failed) throw new RuntimeException(failureReason.toString());
} else {
ImageIO.write(image, "png", new File(testData, gfName));
}
}
/**
* Check the sub-image of actualImage in the given rectangle area is contained in expectedImage at the same or
* nearby location if then, create ComparedRectangle with shift information and insert it into ComparedRectangles
* list.
*
* @param expectedImage
* @param actualImage
* @param ComparedRectangles list of ComparedRectangle
* @param rectangle sub-image area of actual image
* @return true if this rectangle is shifted
*/
public static boolean CheckShift(BufferedImage expectedImage, BufferedImage actualImage,
List<ComparedRectangleArea> ComparedRectangles, Rectangle rectangle) {
int minWidth = Math.min(expectedImage.getWidth(), actualImage.getWidth()), minHeight = Math.min(
expectedImage.getHeight(), actualImage.getHeight());
// set range to be checked
int x = (int) rectangle.getX(), y = (int) rectangle.getY(), w = (int) rectangle.getWidth(), h = (int) rectangle
.getHeight();
int maxShift = ComparisonParameterDefaults.getMaxShift();
int leftMove = Math.min(maxShift, x - 1);
int rightMove = Math.min(maxShift, minWidth - (x + w));
int topMove = Math.min(maxShift, y - 1);
int downMove = Math.min(maxShift, minHeight - (y + h));
Rectangle entireFrame = new Rectangle(x - leftMove, y - topMove, w + leftMove + rightMove, h + topMove
+ downMove);
BufferedImage entireImage = ImageUtils.getSubImage(expectedImage, entireFrame);
BufferedImage templateImage = ImageUtils.getSubImage(actualImage, rectangle);
double[][] integralImage = ImageUtils.calcIntegralImage(entireImage);
double sumTemplate = 0;
Raster r = templateImage.getRaster();
int[] dArray = new int[r.getNumDataElements()];
for (int i = 0; i < r.getWidth(); i++) {
for (int j = 0; j < r.getHeight(); j++) {
sumTemplate += r.getPixel(i, j, dArray)[0];
}
}
int templateWidth = templateImage.getWidth();
int templateHeight = templateImage.getHeight();
double topLeft, topRight, bottomLeft, bottomRight;
double sumEntire;
for (int i = 0; i <= topMove + downMove; i++) {
for (int j = 0; j <= leftMove + rightMove; j++) {
bottomRight = integralImage[i + templateHeight - 1][j + templateWidth - 1];
bottomLeft = (j == 0) ? 0 : integralImage[i + templateHeight - 1][j - 1];
topRight = (i == 0) ? 0 : integralImage[i - 1][j + templateWidth - 1];
topLeft = (j == 0 || i == 0) ? 0 : integralImage[i - 1][j - 1];
sumEntire = bottomRight - bottomLeft - topRight + topLeft;
if (Double.compare(sumEntire, sumTemplate) == 0) {
BufferedImage cropEntire = entireImage.getSubimage(j, i, templateWidth, templateHeight);
// If the template matches at this position, create new ComparedRectangle and add it in the list
if (ImageUtils.imageEquals(cropEntire, templateImage)) {
ComparedRectangleArea newMatch = new ComparedRectangleArea(rectangle, leftMove - j, topMove - i);
ComparedRectangles.add(newMatch);
return true;
}
}
}
}
return false;
}
private TMAPointsResult findCircles(PlanarImage img) {
double r = 6d;
double d;
Color classCol = OrbitImageAnalysis.getInstance().getModel().getClassShapes().get(1).getColor();
int red = classCol.getRed();
int green = classCol.getGreen();
int blue = classCol.getBlue();
int[] c = new int[4];
logger.trace("class color: " + classCol.toString());
final Raster raster = img.getData();
short[][] buf = new short[img.getWidth()][img.getHeight()]; // num tissue pixels buffer
for (int x = 0; x < img.getWidth(); x++)
for (int y = 0; y < img.getHeight(); y++) {
// x,y is center. Now count #tissue pixel in radius around center
for (int bx = x - (int) r; bx <= x + r; bx++) {
if (bx < 0 || bx >= img.getWidth()) continue;
for (int by = y - (int) r; by <= y + r; by++) {
if (by < 0 || by >= img.getHeight()) continue;
d = Point.distance(bx, by, x, y);
if (d <= r) {
c = raster.getPixel(bx, by, c);
if (c[0] == red && c[1] == green && c[2] == blue) {
buf[x][y]++;
}
}
}
}
}
BufferedImage resImg = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_RGB);
WritableRaster raster2 = resImg.getRaster();
for (int x = 0; x < resImg.getWidth(); x++)
for (int y = 0; y < resImg.getHeight(); y++) {
raster2.setPixel(x, y, new int[]{buf[x][y], buf[x][y], buf[x][y]});
//System.out.println(buf[x][y]);
}
// TODO: instead of UEP create TMPSpot lost, order (by score) and take highest scored spots
// and check for intersection (maybe with min threshold)
ImagePlus ip = new ImagePlus("TMAPoints", resImg);
thresholder.applyThreshold(ip);
edm.setup("points", null); // "points" for Ultimate points
edm.run(ip.getProcessor());
PlanarImage img1 = PlanarImage.wrapRenderedImage(ip.getBufferedImage());
List<Point> pList = reportPoints(img1, 1);
double radius = guessRadius(pList);
return new TMAPointsResult(pList, radius, resImg);
}