둥근 객체 식별하기
이 예제에서는 경계선 추적 루틴인 bwboundaries
를 사용하여 원형률을 기준으로 객체를 분류하는 방법을 보여줍니다.
1단계: 영상 읽어 들이기
pills_etc.png
를 읽어 들입니다.
RGB = imread('pillsetc.png');
imshow(RGB)
2단계: 영상 이진화하기
bwboundaries
를 사용한 경계선 추적을 준비하기 위해 영상을 흑백으로 변환합니다.
I = rgb2gray(RGB); bw = imbinarize(I); imshow(bw)
3단계: 잡음 제거하기
모폴로지 함수를 사용하여, 원하는 객체에 속하지 않는 픽셀을 제거합니다.
픽셀 수가 30개 미만인 모든 객체를 제거합니다.
bw = bwareaopen(bw,30); imshow(bw)
펜 뚜껑의 간격을 채웁니다.
se = strel('disk',2);
bw = imclose(bw,se);
imshow(bw)
각 경계로 둘러싸인 영역을 추정하는 데 regionprops
를 사용할 수 있도록 모든 구멍을 채웁니다.
bw = imfill(bw,'holes');
imshow(bw)
4단계: 경계선 찾기
외부 경계선에만 초점을 둡니다. 'noholes'
옵션을 지정하면 bwboundaries
가 내부 윤곽선을 찾는 것을 방지하기 때문에 처리 속도가 빨라집니다.
[B,L] = bwboundaries(bw,'noholes');
레이블 행렬을 표시하고 각 경계를 그립니다.
imshow(label2rgb(L,@jet,[.5 .5 .5])) hold on for k = 1:length(B) boundary = B{k}; plot(boundary(:,2),boundary(:,1),'w','LineWidth',2) end
5단계: 둥근 객체 확인하기
각 객체의 면적과 둘레를 측정합니다. 그러한 결과를 기반으로, 객체의 원형률을 나타내는 단순한 메트릭을 만듭니다.
이 메트릭은 원에 대해서만 1이고, 다른 모든 형태에 대해서는 1보다 작습니다. 이러한 구분 과정은 적합한 임계값을 설정하여 조정할 수 있습니다. 이 예제에서는 알약만 원형으로 분류하기 위해 임계값 0.94
를 사용합니다.
regionprops
를 사용하여, 모든 객체의 면적 추정값을 얻습니다. bwboundaries
에서 반환된 레이블 행렬은 regionprops
에서 다시 사용할 수 있습니다.
stats = regionprops(L,'Area','Centroid'); threshold = 0.94; % loop over the boundaries for k = 1:length(B) % obtain (X,Y) boundary coordinates corresponding to label 'k' boundary = B{k}; % compute a simple estimate of the object's perimeter delta_sq = diff(boundary).^2; perimeter = sum(sqrt(sum(delta_sq,2))); % obtain the area calculation corresponding to label 'k' area = stats(k).Area; % compute the roundness metric metric = 4*pi*area/perimeter^2; % display the results metric_string = sprintf('%2.2f',metric); % mark objects above the threshold with a black circle if metric > threshold centroid = stats(k).Centroid; plot(centroid(1),centroid(2),'ko'); end text(boundary(1,2)-35,boundary(1,1)+13,metric_string,'Color','y',... 'FontSize',14,'FontWeight','bold') end title(['Metrics Closer to 1 Indicate that ',... 'the Object is Approximately Round'])
참고 항목
bwboundaries
| imbinarize
| bwareaopen
| imclose
| strel
| imfill
| label2rgb
| regionprops