Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.awt.Color;
- import java.awt.Rectangle;
- import java.awt.image.BufferedImage;
- import java.io.File;
- import java.io.IOException;
- import javax.imageio.ImageIO;
- import javax.swing.ImageIcon;
- import javax.swing.JLabel;
- import javax.swing.JOptionPane;
- public class Test {
- public static void main(String[] args) throws IOException {
- BufferedImage img = ImageIO.read(new File("/Users/swhitehead/Downloads/47hb1.png"));
- Rectangle bounds = getBounds(img, Color.WHITE);
- System.out.println(bounds);
- BufferedImage trimmed = img.getSubimage(bounds.x, bounds.y, bounds.width, bounds.height);
- JOptionPane.showMessageDialog(null, new JLabel(new ImageIcon(trimmed)));
- }
- public static Rectangle getBounds(BufferedImage img, Color fillColor) {
- int top = getYInset(img, 20, 0, 1, fillColor);
- int bottom = getYInset(img, 20, img.getHeight() - 1, -1, fillColor);
- int left = getXInset(img, 0, top, 1, fillColor);
- int right = getXInset(img, img.getWidth() - 1, top, -1, fillColor);
- return new Rectangle(left, top, right - left, bottom - top);
- }
- public static int getYInset(BufferedImage img, int x, int y, int step, Color fillColor) {
- while (new Color(img.getRGB(x, y), true).equals(fillColor)) {
- y += step;
- }
- return y;
- }
- public static int getXInset(BufferedImage img, int x, int y, int step, Color fillColor) {
- while (new Color(img.getRGB(x, y), true).equals(fillColor)) {
- x += step;
- }
- return x;
- }
- }
- import static marvin.MarvinPluginCollection.*;
- import java.awt.Rectangle;
- import marvin.image.MarvinImage;
- import marvin.io.MarvinImageIO;
- public class BoardSegmentation {
- public BoardSegmentation() {
- MarvinImage imageOriginal = MarvinImageIO.loadImage("./res/board.png");
- MarvinImage image = imageOriginal.clone();
- thresholding(image, 250);
- Rectangle rect = getBoundingBox(image);
- crop(imageOriginal, image, rect.x, rect.y, rect.width, rect.height);
- MarvinImageIO.saveImage(image, "./res/board_cropped.png");
- }
- public Rectangle getBoundingBox(MarvinImage image) {
- Rectangle r = new Rectangle();
- r.x = -1; r.y = -1; r.width = -1; r.height = -1;
- for(int y=0; y<image.getHeight(); y++) {
- for(int x=0; x<image.getWidth(); x++) {
- if(image.getIntColor(x, y) == 0xFF000000) {
- if(r.x == -1 || x < r.x) { r.x = x; }
- if(r.width == -1 || x > r.x + r.width) { r.width = x - r.x; }
- if(r.y == -1 || x < r.y) { r.y = y; }
- if(r.height == -1 || y > r.y + r.height) { r.height = y - r.y; }
- }
- }
- }
- return r;
- }
- public static void main(String[] args) {
- new BoardSegmentation();
- }
- }
Add Comment
Please, Sign In to add comment