【发布时间】:2011-01-10 01:49:35
【问题描述】:
我想知道是否有一种“智能”方法可以根据某些特征分割图像。
图像为 300x57,黑白(实际上是灰度,但大多数颜色是黑色或白色),它由两个主要特征(我们称之为斑点)组成,由黑色空间隔开,每个斑点的宽度和高度,斑点的位置也不同,斑点永远不会重叠!
这是图像“看起来”的样子:
-------------------------
----WWW---------WWWWW----
---WWWWWWW----WWWWWW-----
-----WWWW-------WWW------
-------------------------
生成的拆分将是这样的:
------------ -------------
----WWW----- ----WWWWW----
---WWWWWWW-- --WWWWWW-----
-----WWWW--- ----WWW------
------------ -------------
为了分割图像,我计划采取的步骤:
- 将图像从一侧扫描到另一侧。
- 确定斑点的边缘。
- 测量两个内边缘之间的距离。
- 在内距离的中间分割图像。
- 将这两个图像保存为单独的文件。
如果我标准化图像宽度会很好,这样我的所有图像在保存时都有统一的宽度。
我没有图像处理方面的经验,所以我不知道这样做的有效方法是什么。我目前正在使用 BufferedImage,获取宽度/高度,迭代每个像素等。我的问题没有错误的解决方案,但我正在寻找更高效的解决方案(更少的代码 + 更快)。我也一直在研究 java.awt.Graphics...
如果我能得到一些想法来更有效地完成这项任务,我将不胜感激。我想坚持使用 Java 的内置库,那么在这种情况下使用 BufferedImage 或 Graphics2D 是最有效的吗?
编辑: 以下是阅读建议后的代码:
public void splitAndSaveImage( BufferedImage image ) throws IOException
{
// Process image ------------------------------------------
int height = image.getHeight();
int width = image.getWidth();
boolean edgeDetected = false;
double averageColor = 0;
int threshold = -10;
int rightEdge = 0;
int leftEdge = 0;
int middle = 0;
// Scan the image and determine the edges of the blobs.
for(int w = 0; w < width; ++w)
{
for(int h = 0; h < height; ++h)
{
averageColor += image.getRGB(w, h);
}
averageColor = Math.round(averageColor/(double)height);
if( averageColor /*!=-1*/< threshold && !edgeDetected )
{
// Detected the beginning of the right blob
edgeDetected = true;
rightEdge = w;
}else if( averageColor >= threshold && edgeDetected )
{
// Detected the end of the left blob
edgeDetected = false;
leftEdge = leftEdge==0? w:leftEdge;
}
averageColor = 0;
}
// Split the image at the middle of the inside distance.
middle = (leftEdge + rightEdge)/2;
// Crop the image
BufferedImage leftImage = image.getSubimage(0, 0, middle, height);
BufferedImage rightImage = image.getSubimage(middle, 0, (width-middle), height);
// Save the image
// Save to file -------------------------------------------
ImageIO.write(leftImage, "jpeg", new File("leftImage.jpeg"));
ImageIO.write(rightImage, "jpeg", new File("rightImage.jpeg"));
}
【问题讨论】:
-
注意:检测到右边缘后,可以简单地跳出for循环。
标签: java graphics image-processing image-manipulation