Recursion의 응용 - Counting Cells in a Blob

Juju·2023년 3월 4일
0

현재 픽셀이 image color 라면 먼저 현재 픽셀을 카운트 한다. (count = 1).
현재 픽셀이 중복된 카운트되는것을 방지하기 위해 다른 색으로 칠한다.
현재 픽셀에 이웃한 모든 픽셀들에 대해서
그 픽셀이 속한 blob의 크기를 카운트하여 카운터에 더해준다.
카운터를 반환한다.

현재 인접한 8개의 픽셀중 픽셀에 속한 blob의 카운터를 더해준다. 카운터를 반환한다.

x=5, y=3 이라고 가정, 픽셀이 포함된 blob의 크기를 계산하는 것이 목적.

화살표의 blob은 count = 1이다.

인접한 8개의 픽셀을 북쪽 1번 북동쪽 2번 동쪽 3번 동남 4번 으로 순서가 매겨진다.

북쪽 픽셀이 포함된 blob의 크기는 0. count의 값은 변화가 없다.


count 1 + 3 = 4

count = 4 + 9 = 13

count = 13 + 0 + 0 + 0

북서쪽 까지 완료하면 총 13이 된다.

Algorithm for countCells(x,y)
if pixel(x,y) { 
	outside the grid
   	the result is 0; }
else if  pixel(x,y) {
	not an image pixel or already counted
    the result is 0; }
else  {
	set the colour of the pixel (x,y) to a read color;
    the result is 1 plus the number of cells in each piece of
    	the blob that includes a nearest meighbour; }

java code

private int BACKGROUND = 0;
private int IMAGE = 1;
private int ALREADY = 2;

public int countCells(int x, int y) {
	int result;
    if(x<0 || x>=N || y<0 || y>= N)
    	return 0;
	else if (gird[x][y] != IMAGE)
    	return 0;
    else {
    	gird[x][y] = ALREADY;
        retrun 1 + countCells(x-1, y+1) + countCells(x, y+1)
        + countCells(x+1, y+1) + countCells(x-1, y)
        + countCells(x+1, y) + countCells(x-1, y-1)
        + countCells(x, y-1) + countCells(x+1, y-1);
    }
}
profile
짤막한 기록들..

0개의 댓글