C# OpenCV 강좌 : 제 44강 - 거리 변환
거리 변환(Distance Transform)
DistTransform
함수를 이용하여 이진화 이미지
에서 가장 가까운 흑색(픽셀값 0)픽셀까지의 거리를 계산합니다.
주로, 이진화
적용 시 서로 붙어 있는 물체를 구분하는 방법으로 사용합니다.
원본(Source, src)
은 영상이나 이미지를 사용합니다.
-
영상 사용하기
: [3강 바로가기][3강] -
이미지 사용하기
: [4강 바로가기][4강]
메인 코드
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenCvSharp;
namespace Project
{
class OpenCV : IDisposable
{
IplImage dist;
public IplImage DistTransform(IplImage src)
{
dist = new IplImage(src.Size, BitDepth.F32, 1);
IplImage bin = new IplImage(src.Size, BitDepth.U8, 1);
Cv.CvtColor(src, bin, ColorConversion.BgrToGray);
Cv.Threshold(bin, bin, 50, 255, ThresholdType.Binary);
Cv.Dilate(bin, bin, null, 2);
Cv.Erode(bin, bin, null, 2);
Cv.DistTransform(bin, dist, DistanceType.L2, 3);
//Cv.Threshold(dist, dist, 50, 255, ThresholdType.Binary);
return dist;
}
public void Dispose()
{
if (dist != null) Cv.ReleaseImage(dist);
}
}
}
세부 코드
dist = new IplImage(src.Size, BitDepth.F32, 1);
IplImage bin = new IplImage(src.Size, BitDepth.U8, 1);
결과를 표시할 이미지인 dist
와 이진화 이미지 bin
을 선언합니다.
dist
이미지는 정밀도를 F32
를 사용합니다.
Cv.CvtColor(src, bin, ColorConversion.BgrToGray);
Cv.Threshold(bin, bin, 50, 255, ThresholdType.Binary);
bin
이미지에 이진화를 적용합니다.
Cv.Dilate(bin, bin, null, 2);
Cv.Erode(bin, bin, null, 2);
팽창
과 침식
을 이용하여 이진화 이후 나타나는 노이즈를 제거합니다.
Cv.DistTransform(bin, dist, DistanceType.L2, 3);
Cv.DistTransform()
를 사용하여 가장 가까운 흑색 픽셀까지의 거리를 계산합니다.
Cv.DistTransform(이진화 이미지, 결과, 거리 유형, 마스크 크기)
를 의미합니다.
- 거리 유형
DistanceType.User
: 사용자 지정 거리DistanceType.L1
: \(L1 = \vert x1-x2 \vert + \vert y1-y2 \vert\)DistanceType.L2
: \(L2 = {\sqrt{(x1-x2)^2 + (y1-y2)^2 }}\)DistanceType.C
: \(C = max(\vert x1-x2 \vert,\vert y1-y2 \vert)\)DistanceType.L12
: \(L12 = 2*{\sqrt{1+x*x/2}-1)}\),L12=L1-L2
DistanceType.Fair
: \(Fair = c^2*({\vert x \vert/c-\log(1+\vert x \vert/c)}\),c=1.3998
DistanceType.Welsch
: \(Welsch = {c^2}/{2*(1-\exp(-(x/c)^2))}\),c=2.9846
DistanceType.Huber
: \(Huber = \vert x \vert \lt c \text{ ? } {x^2}/2 \text{ : } c*(\vert x \vert -c/2)\),c=1.345
Cv.Threshold(dist, dist, 50, 255, ThresholdType.Binary);
거리 변환을 통해 얻어낸 이미지를 이용하여 다시 이진화를 적용해 붙어있는 이미지를 구분 할 수 있습니다.
출력 결과
이진화 이미지
DistTransform 이미지
DistTransform + 이진화 이미지
공유하기


댓글 남기기