C# OpenCV 강좌 : 제 51강 - 피부색 검출
피부색 검출(Skin Detector)

영상이나 이미지에서 피부색과 흡사한 픽셀들을 검출하는 알고리즘입니다.
원본(Source, src)은 영상이나 이미지를 사용합니다.
메인 코드
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenCvSharp;
using OpenCvSharp.CPlusPlus;
namespace Project
{
class OpenCV : IDisposable
{
IplImage skin;
public IplImage SkinDetection(IplImage src)
{
skin = new IplImage(src.Size, BitDepth.U8, 3);
IplImage output = new IplImage(src.Size, BitDepth.U8, 1);
Cv.Copy(src, skin);
CvAdaptiveSkinDetector detector = new CvAdaptiveSkinDetector(1, MorphingMethod.ErodeDilate);
detector.Process(src, output);
for (int x = 0; x < src.Width; x++)
{
for (int y = 0; y < src.Height; y++)
{
if (output[y, x].Val0 != 0)
{
skin[y, x] = CvColor.Green;
}
}
}
return skin;
}
public void Dispose()
{
if (skin != null) Cv.ReleaseImage(skin);
}
}
}세부 코드
using OpenCvSharp.CPlusPlus;CvAdaptiveSkinDetector 함수를 사용하기 위해서는 네임스페이스에 using OpenCvSharp.CPlusPlus;를 선언해야 사용할 수 있습니다.
skin = new IplImage(src.Size, BitDepth.U8, 3);
IplImage output = new IplImage(src.Size, BitDepth.U8, 1);결과용 이미지인 skin과 계산용 이미지인 output을 생성합니다.
CvAdaptiveSkinDetector detector = new CvAdaptiveSkinDetector(1, MorphingMethod.ErodeDilate);detector를 선언하여 피부색을 검출하기 위해 생성자를 만듭니다. new CvAdaptiveSkinDetector(1, 모폴로지 연산 방법)입니다.
첫 번째 인수는 samplingDivdier를 의미하며, 1의 값을 고정적으로 사용합니다.
-
MorphingMethod.*: 모폴로지 연산 방법입니다.MorphingMethod.None: 모폴로지 연산을 수행하지 않음MorphingMethod.Erode: 모폴로지 침식만 적용MorphingMethod.ErodeDilate: 모폴로지 침식 후 팽창 적용MorphingMethod.ErodeErode: 모포롤지 침식 후 침식 적용
detector.Process(src, output);피부색 검출 알고리즘을 실행합니다. detector.Process(원본, 결과)입니다. 원본이미지에서 계산을 수행하며, 결과이미지에 검출 결과를 저장합니다.
for (int x = 0; x < src.Width; x++)
{
for (int y = 0; y < src.Height; y++)
{
...
}
}이중 for문을 이용하여 이미지의 너비와 높이만큼 반복하여 모든 픽셀에 대해 검사합니다.
if (output[y, x].Val0 != 0)
{
...
}검출용 이미지인 output의 (x, y)의 픽셀의 값이 흑색이 아니라면, 피부색으로 가정합니다. Val0는 첫 번째 엘리먼트 요소를 의미합니다.
skin[y, x] = CvColor.Green;if문에 부합한다면 결과이미지 (x, y) 좌표의 색상을 초록색으로 변경합니다.
출력 결과

공유하기
Kakao
Naver
Twitter
LinkedIn
Facebook
댓글 남기기