본문 바로가기

컴퓨터비전

5. Morphology

* Morphology 

▷ structuring element는 길이가 3 pixel인 십자(+)형을 사용

▷ dilation / erosion / opening / closing 수행


- 주요 소스코드

/* 팽창 연산 */
void dilation(int width, int height){ 
	int t= width*height;					//크기 저장 
	int *dst;								//동적 할당
	dst = (int *) malloc (sizeof(int)* t);

	for(i=0; i<width*height; i++){
		dst[i]=0;	//초기값 설정
	}
	
	for(i=0; i<height; i++){ 
		for(j=0; j<width; j++){ 
			if(buffer[i*width+j]==255){ 
				//픽셀의 밝기값이 255이면, 그 주변 (십자모양) 의 밝기 값을 변경
				//임의의 변수에다 저장
				 dst[(i*width)+j-1] = 255;
				 dst[(i*width)+j+1] = 255;
				 dst[(i-1)*width+j] = 255; 
				 dst[(i+1)*width+j] = 255; 				
				 dst[i*width+j] = 255; 
			} 
		} 
	} 
	// 영상 출력
	for(i=0; i<height; i++){ 
		for(j=0; j<width; j++){
			//임의의 변수에 저장된 값이 255면,밝기는 255;
			if(dst[i*width+j] == 255) 
				buffer[i*width+j] = 255;
			//임의의 변수에 저장된 값이 0이면,밝기는 255;
			else
				buffer[i*width+j] = 0;
		}
	} 

	free(dst);	//동적 할당 해제 
} 


/*침식 연산*/
void erosion(int width, int height){ 
	int t= width*height;	//크기 설정
	int *dst;				//동적 할당
	dst = (int *) malloc (sizeof(int)* t);

	for(i=0; i<width*height; i++){
		dst[i]=0;//초기값 설정
	}

	for(i=0; i<height; i++){ 
		for(j=0; j<width; j++){ 
			//밝기값이 255이고
			if(buffer[i*width+j] == 255){
				//그 주변 (십자 모양)에 0이 하나라도 있으면 
				if(buffer[(i-1)*width+j] == 0 || buffer[(i+1)*width+j] == 0 || buffer[i*width+j-1] == 0 || buffer[i*width+j+1] == 0) 
					//임의의 변수에 0 저장
					dst[i*width+j] = 0; 
				//하나라도 0이아니라면, 모두 255라면, 255 저장
				else 
					dst[i*width+j] = 255; 
			} 
		} 
	} 
	//영상 출력
	for(i=0; i<height; i++){ 
		for(j=0; j<width; j++){ 
			//임의의 변수의 값이 255이면
			if(dst[i*width+j] == 255) 
				//밝기는 255임
				buffer[i*width+j] = 255; 
			//변수 값이 255가 아니라면
			else 
				//밝기는 0임
				buffer[i*width+j] = 0; 
		} 
	} 
	free(dst);
} 


/* 열림 연산 */
void opening(int width, int height){ 
	//침식 연산 적용 후, 
	erosion(width, height);
	//팽창 연산 
	dilation(width, height); 
} 


/* 닫힘 연산 */
void closing(int width, int height){ 
	//팽창 연산 적용 후, 
	dilation(width, height);
	//침식 연산 
	erosion(width, height); 
}