Java Code Examples for ij.process.ByteProcessor#get()

The following examples show how to use ij.process.ByteProcessor#get() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ImgGlyphDescriptor.java    From audiveris with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public double[] getFeatures (Glyph glyph,
                             int interline)
{
    final ByteProcessor buffer = ScaledBuffer.getBuffer(glyph, interline);
    buffer.invert(); // 0 for background, 255 for foreground

    // Layout: row by row
    final double[] doubles = new double[length()];
    int i = 0;

    for (int y = 0; y < ScaledBuffer.HEIGHT; y++) {
        for (int x = 0; x < ScaledBuffer.WIDTH; x++) {
            doubles[i++] = buffer.get(x, y);
        }
    }

    return doubles;
}
 
Example 2
Source File: CurveGap.java    From audiveris with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Compute the gap vector based on foreground pixels found in gap area.
 *
 * @param buf the binary buffer
 * @return the populated gap vector (in which a 1 value indicates a black pixel)
 */
public int[] computeVector (ByteProcessor buf)
{
    final Rectangle box = area.getBounds();

    for (int x = box.x, xBreak = box.x + box.width; x < xBreak; x++) {
        for (int y = box.y, yBreak = box.y + box.height; y < yBreak; y++) {
            if (area.contains(x, y)) {
                if (0 == buf.get(x, y)) {
                    populateVector(x - box.x, y - box.y);
                }
            }
        }
    }

    return vector;
}
 
Example 3
Source File: SheetDiff.java    From audiveris with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Count the number of foreground pixels in the provided image.
 *
 * @param filter the binary image
 * @return the number of foreground pixels
 */
private int getForeCount (ByteProcessor filter)
{
    final int width = filter.getWidth();
    final int height = filter.getHeight();
    int count = 0;

    for (int x = 0; x < width; x++) {
        for (int y = 0; y < height; y++) {
            if (filter.get(x, y) == 0) {
                count++;
            }
        }
    }

    return count;
}
 
Example 4
Source File: TimeBuilder.java    From audiveris with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * We use the NO_STAFF source of pixels.
 *
 * @return the projection on x-axis
 */
private IntegerFunction getProjection ()
{
    // Staff-free pixel source
    final ByteProcessor source = system.getSheet().getPicture().getSource(
            Picture.SourceKey.NO_STAFF);
    final int xMin = roi.x;
    final int xMax = (roi.x + roi.width) - 1;
    final IntegerFunction function = new IntegerFunction(xMin, xMax);

    for (int x = xMin; x <= xMax; x++) {
        short cumul = 0;

        for (int y = roi.y, yBreak = roi.y + roi.height; y < yBreak; y++) {
            if (source.get(x, y) == 0) {
                cumul++;
            }
        }

        function.setValue(x, cumul);
    }

    return function;
}
 
Example 5
Source File: BinaryStep.java    From audiveris with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Check whether the provided source has at least a gray pixel.
 *
 * @param source the source to inspect
 * @return true if at least one pixel is neither black nor white
 */
private boolean hasGray (ByteProcessor source)
{
    for (int i = source.getPixelCount() - 1; i >= 0; i--) {
        int val = source.get(i);

        if ((val != 0) && (val != 255)) {
            return true;
        }
    }

    return false;
}
 
Example 6
Source File: Template.java    From audiveris with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Collect the image foreground pixels located under the template foreground areas.
 *
 * @param box   absolute positioning of template box in global image
 * @param image global image to be read
 * @return the collection of foreground pixels, relative to template box.
 */
public List<Point> getForegroundPixels (Rectangle box,
                                        ByteProcessor image)
{
    final int imgWidth = image.getWidth();
    final int imgHeight = image.getHeight();
    final List<Point> fores = new ArrayList<>();

    for (PixelDistance pix : keyPoints) {
        if (pix.d != 0) {
            continue;
        }

        int nx = box.x + pix.x;
        int ny = box.y + pix.y;

        if ((nx >= 0) && (nx < imgWidth) && (ny >= 0) && (ny < imgHeight)) {
            // Check if we have some image foreground there
            int val = image.get(nx, ny);

            if (val == 0) {
                fores.add(new Point(pix.x, pix.y));
            }
        }
    }

    return fores;
}
 
Example 7
Source File: ChamferDistance.java    From audiveris with GNU Affero General Public License v3.0 5 votes vote down vote up
private void initializeToFore (ByteProcessor input,
                               DistanceTable output)
{
    for (int i = (input.getWidth() * input.getHeight()) - 1; i >= 0; i--) {
        if (input.get(i) == 0) {
            output.setValue(i, VALUE_TARGET); // reference pixel -> distance=0
        } else {
            output.setValue(i, VALUE_UNKNOWN); // non-reference pixel -> to be computed
        }
    }
}
 
Example 8
Source File: ChamferDistance.java    From audiveris with GNU Affero General Public License v3.0 5 votes vote down vote up
private void initializeToBack (ByteProcessor input,
                               DistanceTable output)
{
    for (int y = 0, h = input.getHeight(); y < h; y++) {
        for (int x = 0, w = input.getWidth(); x < w; x++) {
            if (input.get(x, y) == 0) {
                output.setValue(x, y, VALUE_UNKNOWN); // non-reference pixel -> to be computed
            } else {
                output.setValue(x, y, VALUE_TARGET); // reference pixel -> distance=0
            }
        }
    }
}
 
Example 9
Source File: BeamsBuilder.java    From audiveris with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Retrieve cue glyph instances out of an aggregate snapshot.
 *
 * @return the list of glyph instances found
 */
private List<Glyph> getCueGlyphs ()
{
    // Expand aggregate bounds using global direction
    Rectangle box = new Rectangle(bounds);
    box.grow(params.cueBoxDx, 0);

    if (globalDir != 0) {
        box.y += (globalDir * params.cueBoxDy);
    } else {
        box.grow(0, params.cueBoxDy);
    }

    // Take a small *COPY* of binary image and apply morphology
    Picture picture = sheet.getPicture();
    ByteProcessor whole = picture.getSource(Picture.SourceKey.BINARY);
    ByteProcessor buf = new ByteProcessor(box.width, box.height);

    for (int y = 0; y < box.height; y++) {
        for (int x = 0; x < box.width; x++) {
            int val = whole.get(box.x + x, box.y + y);
            buf.set(x, y, val);
        }
    }

    double beam = params.cueBeamRatio * sheet.getScale().getBeamThickness();

    return new SpotsBuilder(sheet).buildSpots(buf, box.getLocation(), beam, id);
}
 
Example 10
Source File: LedgersBuilder.java    From audiveris with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
protected double getValue (StickContext context)
{
    ByteProcessor pixelFilter = sheet.getPicture().getSource(
            Picture.SourceKey.NO_STAFF);

    Filament stick = context.stick;
    Rectangle box = stick.getBounds();
    int convexities = 0;

    // On each end of stick, we check that pixels just above and just below are white,
    // so that stick slightly stands out.
    // We use the stick bounds, regardless of the precise geometry inside.
    //
    //  X                                                         X
    //  +---------------------------------------------------------+
    //  |                                                         |
    //  |                                                         |
    //  +---------------------------------------------------------+
    //  X                                                         X
    //
    for (HorizontalSide hSide : HorizontalSide.values()) {
        int x = (hSide == LEFT) ? box.x : ((box.x + box.width) - 1);
        boolean topFore = pixelFilter.get(x, box.y - 1) == 0;
        boolean bottomFore = pixelFilter.get(x, box.y + box.height) == 0;
        boolean isConvex = !(topFore || bottomFore);

        if (isConvex) {
            convexities++;
        }
    }

    return convexities;
}
 
Example 11
Source File: StaffPattern.java    From audiveris with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Measure how well the pattern fits the pixel buffer at upper left location.
 *
 * @param location location of upper left corner of pattern
 * @param buffer   the image buffer to read foreground pixels from
 * @return the ratio of foreground pixels matched by the pattern
 */
public double evaluate (Point2D location,
                        ByteProcessor buffer)
{
    final int xMin = (int) Math.rint(location.getX());
    int trials = 0;
    int matches = 0;

    for (int index = 0; index < count; index++) {
        final double yMid = location.getY() + (index * interline);
        final int yMin = (int) Math.ceil(yMid - (line / 2.0));
        final int yMax = (int) Math.floor(yMid + (line / 2.0));

        for (int y = yMin; y <= yMax; y++) {
            for (int x = xMin; x < (xMin + width); x++) {
                trials++;

                if (0 == buffer.get(x, y)) {
                    matches++;
                }
            }
        }
    }

    double ratio = (double) matches / trials;

    return ratio;
}
 
Example 12
Source File: Picture.java    From audiveris with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Call-back triggered when sheet location has been modified.
 * Based on sheet location, we forward the INITIAL pixel gray level to
 * whoever is interested in it.
 *
 * @param event the (sheet) location event
 */
@Override
public void onEvent (LocationEvent event)
{
    if (initialImage == null) {
        return;
    }

    try {
        // Ignore RELEASING
        if (event.movement == MouseMovement.RELEASING) {
            return;
        }

        Integer level = null;

        // Compute and forward pixel gray level
        Rectangle rect = event.getData();

        if (rect != null) {
            Point pt = rect.getLocation();

            // Check that we are not pointing outside the image
            if ((pt.x >= 0) && (pt.x < getWidth()) && (pt.y >= 0) && (pt.y < getHeight())) {
                ByteProcessor src = getSource(SourceKey.INITIAL);

                if (src != null) {
                    level = src.get(pt.x, pt.y);
                }
            }
        }

        pixelService.publish(new PixelEvent(this, event.hint, event.movement, level));
    } catch (Exception ex) {
        logger.warn(getClass().getName() + " onEvent error", ex);
    }
}
 
Example 13
Source File: SheetDiff.java    From audiveris with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Computes the figure which best describes the level of
 * recognition reached on current sheet.
 *
 * @return the ratio of (filtered) different pixels with respect to the
 *         total foreground pixels of the input binary image.
 */
public double computeDiff ()
{
    final StopWatch watch = new StopWatch("computeDiff");
    final int width = sheet.getWidth();
    final int height = sheet.getHeight();
    final ByteProcessor in = new GlobalFilter(
            sheet.getPicture().getSource(Picture.SourceKey.BINARY),
            constants.binaryThreshold.getValue()).filteredImage();

    watch.start("count input");
    inputCount = getInputCount();

    watch.start("output");

    ByteProcessor out = new ByteProcessor(getOutput());
    out.threshold(constants.binaryThreshold.getValue());

    // Compute input XOR output
    watch.start("xor");

    final ByteProcessor xor = new ByteProcessor(width, height);
    ByteUtil.raz(xor); // xor.invert();

    for (int x = 0; x < width; x++) {
        for (int y = 0; y < height; y++) {
            if (in.get(x, y) != out.get(x, y)) {
                xor.set(x, y, 0);
            }
        }
    }

    // Filter the data
    watch.start("median filter");

    xor.medianFilter();

    watch.start("filtered to disk");
    ImageUtil.saveOnDisk(xor.getBufferedImage(), sheet.getId() + ".filtered");
    watch.start("count filtered");

    // Count all filtered differences
    final int count = getForeCount(xor);
    final double ratio = (double) count / inputCount;

    logger.info(
            "Delta {}% ({} differences wrt {} input pixels)",
            String.format("%4.1f", 100 * ratio),
            count,
            inputCount);

    if (constants.printWatch.isSet()) {
        watch.print();
    }

    // Display the filtered differences
    if (OMR.gui != null) {
        sheet.getStub().getAssembly().addViewTab(
                SheetTab.DIFF_TAB,
                new ScrollView(new MyView(xor)),
                new BoardsPane(new PixelBoard(sheet)));
    }

    return ratio;
}
 
Example 14
Source File: Picture.java    From audiveris with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Debugging routine, that prints a basic representation of a
 * rectangular portion of the selected image.
 *
 * @param key   the selected image key
 * @param title an optional title for this image dump
 * @param xMin  x first abscissa
 * @param xMax  x last abscissa
 * @param yMin  y first ordinate
 * @param yMax  y last ordinate
 */
public void dumpRectangle (SourceKey key,
                           String title,
                           int xMin,
                           int xMax,
                           int yMin,
                           int yMax)
{
    ByteProcessor source = getSource(key);
    StringBuilder sb = new StringBuilder();

    sb.append(String.format("%n"));

    if (title != null) {
        sb.append(String.format("%s%n", title));
    }

    // Abscissae
    sb.append("     ");

    for (int x = xMin; x <= xMax; x++) {
        sb.append(String.format("%4d", x));
    }

    sb.append(String.format("%n    +"));

    for (int x = xMin; x <= xMax; x++) {
        sb.append(" ---");
    }

    sb.append(String.format("%n"));

    // Pixels
    for (int y = yMin; y <= yMax; y++) {
        sb.append(String.format("%4d", y));
        sb.append("|");

        for (int x = xMin; x <= xMax; x++) {
            int pix = source.get(x, y);

            if (pix == 255) { // White background
                sb.append("   .");
            } else {
                sb.append(String.format("%4d", pix));
            }
        }

        sb.append(String.format("%n"));
    }

    sb.append(String.format("%n"));

    logger.info(sb.toString());
}
 
Example 15
Source File: MedianGrayFilter.java    From audiveris with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void filter (final ByteProcessor input,
                    final ByteProcessor output)
{
    final int width = input.getWidth();
    final int height = input.getHeight();
    final int[] histogram = new int[256];
    Arrays.fill(histogram, 0);

    for (int y = 0; y < height; y++) {
        for (int x = 0; x < width; x++) {
            // To address specific behavior at image boundaries,
            // reduce radius to not use pixels outside the image.
            int rad = radius;

            if ((x - rad) < 0) {
                rad = x;
            }

            if ((y - rad) < 0) {
                rad = y;
            }

            if ((x + rad) >= width) {
                rad = width - 1 - x;
            }

            if ((y + rad) >= height) {
                rad = height - 1 - y;
            }

            Arrays.fill(histogram, 0); // Brute force!

            for (int i = x - rad; i <= (x + rad); i++) {
                for (int j = y - rad; j <= (y + rad); j++) {
                    int val = input.get(i, j);
                    histogram[val]++;
                }
            }

            // Pick up the median value
            final int side = (2 * rad) + 1;
            final int medianCount = ((side * side) + 1) / 2;
            int median = 255;
            int sum = 0;

            while (sum < medianCount) {
                sum += histogram[median];
                median--;
            }

            output.set(x, y, median + 1);
        }
    }
}
 
Example 16
Source File: AreaUtil.java    From audiveris with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Perform core analysis on a vertical shape.
 *
 * @param filter     source of foreground / background
 * @param leftLimit  limit on left side
 * @param rightLimit limit on right side
 * @return the CoreData measured
 */
public static CoreData verticalCore (ByteProcessor filter,
                                     GeoPath leftLimit,
                                     GeoPath rightLimit)
{
    // Inspect each horizontal row of the stick
    int largestGap = 0; // Largest gap so far
    int lastBlackY = -1; // Ordinate of last black row
    int lastWhiteY = -1; // Ordinate of last white row
    int whiteCount = 0; // Count of rows where item is white (broken)

    final int yMin = (int) Math.ceil(leftLimit.getFirstPoint().getY());
    final int yMax = (int) Math.floor(leftLimit.getLastPoint().getY());

    for (int y = yMin; y <= yMax; y++) {
        final int xMin = (int) Math.floor(leftLimit.xAtY(y));
        final int xMax = (int) Math.ceil(rightLimit.xAtY(y));

        // Make sure the row is not empty
        boolean empty = true;

        for (int x = xMin; x <= xMax; x++) {
            if (filter.get(x, y) == 0) {
                empty = false;

                break;
            }
        }

        if (empty) {
            whiteCount++;
            lastWhiteY = y;

            continue;
        }

        // End of gap?
        if ((lastWhiteY != -1) && (lastBlackY != -1)) {
            largestGap = Math.max(largestGap, lastWhiteY - lastBlackY);
            lastWhiteY = -1;
        }

        lastBlackY = y;
    }

    int height = yMax - yMin + 1;
    double whiteRatio = (double) whiteCount / height;

    return new CoreData(height, largestGap, whiteRatio);
}
 
Example 17
Source File: Template.java    From audiveris with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Collect the image foreground pixels located under the template foreground areas,
 * with some additional margin.
 *
 * @param box     absolute positioning of template box in global image
 * @param image   global image to be read
 * @param dilated true for applying dilation before processing
 * @return the collection of foreground pixels, relative to template box.
 */
public List<Point> getForegroundPixels (Rectangle box,
                                        ByteProcessor image,
                                        boolean dilated)
{
    final List<Point> fores = getForegroundPixels(box, image);

    if (!dilated) {
        return fores;
    }

    int dilation = InterlineScale.toPixels(pointSize / 4, constants.dilation);

    // Populate an enlarged buffer with these foreground pixels
    final Rectangle bufBox = new Rectangle(box);
    bufBox.grow(dilation, dilation);

    final ByteProcessor buf = new ByteProcessor(bufBox.width, bufBox.height);
    ByteUtil.raz(buf); //buf.invert();

    for (Point p : fores) {
        buf.set(p.x + dilation, p.y + dilation, 0);
    }

    // Dilate the foreground areas
    for (int i = 0; i < dilation; i++) {
        buf.dilate();
    }

    // Retrieve the new collection of foreground pixels
    fores.clear();

    for (int y = 0; y < bufBox.height; y++) {
        for (int x = 0; x < bufBox.width; x++) {
            if (buf.get(x, y) == 0) {
                fores.add(new Point(x - dilation, y - dilation));
            }
        }
    }

    return fores;
}
 
Example 18
Source File: ColorImages.java    From MorphoLibJ with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Creates a new color ImageStack from the red, green and blue ImageStack
 * instances. Each channel must contains instances of ByteProcessor.
 * 
 * @param red
 *            the image for the red channel (must contain ByteProcessor instances)
 * @param green
 *            the image for the green channel (must contain ByteProcessor instances)
 * @param blue
 *            the image for the blue channel (must contain ByteProcessor instances)
 * @return the color image corresponding to the concatenation of the three
 *         channels
 * @throws IllegalArgumentException
 *             if one of the ImageStack does not contain instances of ByteProcessor
 */
public static final ImageStack mergeChannels(ImageStack red, 
		ImageStack green, ImageStack blue)
{
	// check validity of input
	if (!(red.getProcessor(1) instanceof ByteProcessor))
		throw new IllegalArgumentException("Input channels must be instances of ByteProcessor");
	if (!(green.getProcessor(1) instanceof ByteProcessor))
		throw new IllegalArgumentException("Input channels must be instances of ByteProcessor");
	if (!(blue.getProcessor(1) instanceof ByteProcessor))
		throw new IllegalArgumentException("Input channels must be instances of ByteProcessor");
	
	int width = red.getWidth();
	int height = red.getHeight();
	int depth = red.getSize();
	ImageStack result = ImageStack.create(width, height, depth, 24);
	
	for (int z = 1; z <= depth; z++)
	{
		// extract current slices
		ByteProcessor redSlice = (ByteProcessor) red.getProcessor(z);
		ByteProcessor greenSlice = (ByteProcessor) green.getProcessor(z);
		ByteProcessor blueSlice = (ByteProcessor) blue.getProcessor(z);
		ColorProcessor rgbSlice =  (ColorProcessor) result.getProcessor(z);

		for (int y = 0; y < height; y++)
		{
			for (int x = 0; x < width; x++)
			{
				int r = redSlice.get(x, y);
				int g = greenSlice.get(x, y);
				int b = blueSlice.get(x, y);
				int rgbCode = (r << 16) | (g << 8) | b;
				rgbSlice.set(x, y, rgbCode);
			}
		}
		
		result.setProcessor(rgbSlice, z);
	}
	
	return result;	
}