# 标识圆形目标

### 步骤 1：读取一个图像

`pills_etc.png` 中进行读取。

```RGB = imread("pillsetc.png"); imshow(RGB)```

### 步骤 2：阈值化图像

```I = im2gray(RGB); bw = imbinarize(I); imshow(bw)```

### 步骤 3：预处理图像

```minSize = 30; bw = bwareaopen(bw,minSize); imshow(bw)```

```se = strel("disk",2); bw = imclose(bw,se); imshow(bw)```

```bw = imfill(bw,"holes"); imshow(bw)```

### 步骤 4：找到边界

`[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：确定哪些对象为圆形

`stats = regionprops(L,"Circularity","Centroid");`

`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")```