【发布时间】:2017-08-08 16:25:47
【问题描述】:
我正在编写 Java 代码,它应该检测像素区域并创建一个包含相互连接的像素坐标的列表。 对于我想创建一个新列表的每个区域。
我写了一个方法,它应该首先检测区域的边缘,然后检查像素是否连接到另一个。我交出一张黑白图像并将其转换为二维像素阵列。在每个索引中,我设置了图像等效像素的颜色。但它不起作用。
我的问题:是否有任何其他解决方案来分隔黑白图像的黑色区域以获得列出的坐标?
示例:
我将此图像保存到 2D 整数数组中,如果颜色为黑色,则此索引处的值为“1”,否则如果颜色为白色,则为“-1”。
我想获得 2 个列表(因为有 2 个单独的区域)
第一个列表:坐标[(1,1),(2,1),(0,2),(1,2),(2,2)]
第二个列表:坐标[(6,2),(4,3),(5,3),(6,3),(7,3),(4,4) ,(5,4),(6,4)]
我的代码:
private static List<Group> detectGroups(BufferedImage image) {
int[][] colorArray = imageToColorArray(image);
List<Coordinate> edgeCoordinates = new ArrayList<Coordinate>();
List<Group> pixelGroups = new ArrayList<Group>(); // empty now
// Detect Edges
for (int y = 1; y < colorArray[0].length - 1; y++) {
for (int x = 1; x < colorArray.length - 1; x++) {
if (colorArray[x][y] == black && colorArray[x - 1][y] == white
|| colorArray[x][y] == black && colorArray[x + 1][y] == white
|| colorArray[x][y] == black && colorArray[x][y - 1] == white
|| colorArray[x][y] == black && colorArray[x][y + 1] == white) {
colorArray[x][y] = edge;
edgeCoordinates.add(new Coordinate(x, y));
}
}
}
// Detect Groups
for (int i = 0; i < edgeCoordinates.size(); i++) {
Coordinate index = edgeCoordinates.get(i);
int x = index.getX();
int y = index.getY();
Coordinate c = new Coordinate(x, y);
Coordinate topLeftFromPixel = new Coordinate(x - 1, y - 1);
Coordinate topMiddleFromPixel = new Coordinate(x, y - 1);
Coordinate topRightFromPixel = new Coordinate(x + 1, y - 1);
Coordinate middleLeftFromPixel = new Coordinate(x - 1, y);
Coordinate middleRightFromPixel = new Coordinate(x + 1, y);
Coordinate bottomLeftFromPixel = new Coordinate(x - 1, y + 1);
Coordinate bottomMiddleFromPixel = new Coordinate(x, y + 1);
Coordinate bottomRightFromPixel = new Coordinate(x + 1, y + 1);
if (pixelGroups.isEmpty()) {
Group group = new Group();
group.addCoordinate(c);
pixelGroups.add(group);
} else {
/*
* Überprüfe ob die Pixel sich berühren und ermittle Pixelgruppen und erstelle
* falls nötig eine neue Gruppe
*/
for (int j = 0; j < pixelGroups.size(); j++) {
List<Coordinate> coordinates = pixelGroups.get(j).getCoordinates();
for (int l = 0; l < coordinates.size(); l++) {
Coordinate k = coordinates.get(l);
if (k.equals(topLeftFromPixel) || k.equals(topMiddleFromPixel) || k.equals(topRightFromPixel)
|| k.equals(middleLeftFromPixel) || k.equals(middleRightFromPixel)
|| k.equals(bottomLeftFromPixel) || k.equals(bottomMiddleFromPixel)
|| k.equals(bottomRightFromPixel)) {
pixelGroups.get(j).addCoordinate(c);
} else {
Group newGroup = new Group();
newGroup.addCoordinate(c);
pixelGroups.add(0, newGroup);
}
}
}
}
}
return pixelGroups;
}
【问题讨论】:
-
光栅大小是否已知?它可以改变吗?什么是像素区域?那些大的黑色方块应该代表像素吗?还是您要处理的示例图像,而不仅仅是像素的缩放视图?
-
@Piglet 我上面展示的图像代表了一个放大的图像。每个黑盒子都是一个像素,在盒子里面我写了坐标来更好地理解这个问题。像素区域是黑色像素的组合。
-
google blob检测,连通分量,区域增长,图像处理中很常见的问题
标签: java image-processing