둥근 객체 식별하기
이 예제에서는 경계선 추적 루틴인 bwboundaries
를 사용하여 원형률을 기준으로 객체를 분류하는 방법을 보여줍니다.
1단계: 영상 읽어 들이기
pills_etc.png
를 읽어 들입니다.
RGB = imread("pillsetc.png");
imshow(RGB)
2단계: 영상 이진화하기
bwboundaries
를 사용한 경계선 추적을 준비하기 위해 영상을 흑백으로 변환합니다.
I = im2gray(RGB); bw = imbinarize(I); imshow(bw)
3단계: 영상 전처리하기
모폴로지 함수를 사용하여, 원하는 객체에 속하지 않는 픽셀을 제거합니다.
픽셀 수가 30개 미만인 모든 객체를 제거합니다.
minSize = 30; bw = bwareaopen(bw,minSize); 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 title("Objects with Boundaries in White")
5단계: 둥근 객체 확인하기
regionprops
함수를 사용하여 모든 객체의 원형성과 중심을 추정합니다. 이 원형성 메트릭은 이상적인 원인 경우 1이고 다른 형태인 경우 1보다 작습니다.
stats = regionprops(L,"Circularity","Centroid");
이러한 분류 과정은 적합한 임계값을 설정하여 조정할 수 있습니다. 이 예제에서는 알약만 원형으로 분류하기 위해 임계값으로 0.94
를 사용합니다.
threshold = 0.94;
감지된 경계선을 루프를 사용해 순환합니다. 각 객체에 다음을 수행합니다.
(x,y) 경계선 좌표와 원형성 측정값을 가져옵니다
원형성 측정값과 임계값을 비교합니다. 원형성이 임계값을 초과하면 중심의 위치를 계산하고 중심을 검은색 원으로 표시합니다.
객체 위에 노란색 텍스트로 원형성 측정값을 표시합니다.
for k = 1:length(B) % Obtain (X,Y) boundary coordinates corresponding to label "k" boundary = B{k}; % Obtain the circularity corresponding to label "k" circ_value = stats(k).Circularity; % Display the results circ_string = sprintf("%2.2f",circ_value); % Mark objects above the threshold with a black circle if circ_value > threshold centroid = stats(k).Centroid; plot(centroid(1),centroid(2),"ko"); end text(boundary(1,2)-35,boundary(1,1)+13,circ_string,Color="y",... FontSize=14,FontWeight="bold") end title("Centroids of Circular Objects and Circularity Values")
참고 항목
bwboundaries
| imbinarize
| bwareaopen
| imclose
| strel
| imfill
| label2rgb
| regionprops