2012-08-08 40 views
2

我具有黑白點(像素)的圖像。我需要爲包含該白點的x,y座標的每個不同的白色像素簇創建不同的集合(例如,如果我有三個未連接的白色圖像島的黑色圖像,我需要生成三組座標)。任何人都可以建議我這個算法嗎?用於在黑白圖像上查找未連接區域(島)的算法

單元連接如果abs(x1-x2) <=1 && abs(y1-y2)<=1

+0

如果圖像爲黑色和白色的確實,一個在計算上更有效的測試連接細胞將被'is_not_connected = A [N,M]^A [N-1,M]; //表示異或,不是指數!'。 B/W是你的圖像嗎? – 2012-08-10 08:09:37

+0

投票結束,作爲工具rec。 – 2016-04-29 21:42:31

回答

2

Region growing,應該這樣做。該鏈接回答了一個不同的問題,但基本算法應該適合您的需求。你只需要傳遞另一個參數,它告訴集羣的編號。從1開始,每當你進入一個新的羣集,增加這個值。

這個新的參數將代替1代表前景,2代表背景。這會給你所有羣集的總數,以及它們的所有位置。

0

這使用洪水填充算法。找到連接區域的數量 import com.sun.corba.se.spi.presentation.rmi.IDLNameTranslator;

import javax.xml.transform.Source; 
import java.awt.*; 
import java.awt.font.ImageGraphicAttribute; 
import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.util.Collections; 

/** 
* Created by IntelliJ IDEA. 
* User: ruzbeh 
* Date: 6/29/12 
* Time: 12:58 AM 
* To change this template use File | Settings | File Templates. 
*/ 
public class Solution { 


    static int[][] img; 

    static void compLabel(int i, int j, int m,int n) { 
     if(i<0 || j<0 ||i > n-1||j > n-1) return; 
     if (img[i][j] == 1) { 
      img[i][j] = m; 
      compLabel(i - 1, j - 1, m,n); 
      compLabel(i - 1, j, m,n); 
      compLabel(i - 1, j + 1, m,n); 
      compLabel(i, j - 1, m,n); 
      compLabel(i, j + 1, m,n); 
      compLabel(i + 1, j - 1, m,n); 
      compLabel(i + 1, j, m,n); 
      compLabel(i + 1, j + 1, m,n); 
     } 
    } 


    public static void main(String[] args) throws IOException { 
     BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 

     int T = Integer.parseInt(br.readLine()); 
     for (int t = 0; t < T; t++) { 
      int n = Integer.parseInt(br.readLine()); 
      img = new int[n][n]; 
      int label = 2; 
      for (int i = 0; i < n; i++) { 
       int j = 0; 
       for (String str : br.readLine().split(" ")) { 
        int value = Integer.parseInt(str); 

        img[i][j] = value; 

        j++; 
       } 

      } 
      for (int y = 0; y < n; y++) 
       for (int x = 0; x < n; x++) 
        if (img[x][y] == 1) { 
         compLabel(x, y, ++label,n); 
        } 

      System.out.println(label - 2); 
     } 
    } 
}