系统设计与开发 实验报告-4

1. 实验内容

传统的计数方法常依赖于人眼目视计数,不仅计数效率低,且容易计数错误。通常现实中的对象不会完美地分开,需要通过进一步的图像处理将对象分开并计数。巩固对 OpenCV 的基础操作的使用,适当地增加 OpenCV 在图像处理方向的进阶操作,例如利用 Canny 算子等算法进行图像分割。

2. 实验目的

通过本实验能够综合利用 OpenCV 在图像处理的方向的应用。

3. 程序清单

3.1 任务一

简单图像物体数量统计:物体之间没有重叠、数量较少、边界清晰,与背景颜色差别大;

3.1.1 实验步骤

使用 cv2.imread() 导入图片后,进行灰度处理和边缘提取,再按照边缘数量计算硬币数量。

3.1.2 实验代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import cv2
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
# 导入图片
image = cv2.imread("8.png")
# 灰度模糊处理
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (11, 11), 0)
# 边缘提取
edged = cv2.Canny(blurred, 30, 150)
(cnts, _) = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
print("There are {} coins in the picture. ".format(len(cnts)))
# 在原图中显示
coins = image.copy()
cv2.drawContours(coins, cnts, -1, (255, 0, 0), 2)
plt.imshow(coins)

3.2 任务二

较复杂图像物体数量统计:物体之间有重叠、数量较多、边界模糊,与背景颜色接近、不同种物体等因素;

3.2.1 实验步骤

在实验一的基础上加上距离变换,再进一步腐蚀保留每个识别物体最核心的部分作为识别体供 OpenCV 系统进行边缘描绘;

3.2.2 实验代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import cv2
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
# 导入图片
img = cv2.imread("003.png")
# 灰度模糊处理
image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img_1 = cv2.GaussianBlur(image, (11, 11), 0)
ret, img_2 = cv2.threshold(img_1, 127, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
# 腐蚀
kernel = np.ones((5, 30), int)
img_3 = cv2.erode(img_2, kernel, iterations=1)
# 膨胀
kernel = np.ones((3, 3), int)
img_4 = cv2.dilate(img_3, kernel, iterations=1)
# 边缘提取
contours, hierarchy = cv2.findContours(img_4, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)[-2:]
print("There are {} coins in the picture. ".format(len(contours)))
# 在原图中显示
cv2.drawContours(img, contours, -1, (0, 0, 255), 5)
plt.imshow(img)

4. 分析与思考

  1. 计算机进行图片色彩空间读取时都是按照 B-G-R 的顺序,所以每次展示图片的时候都需要将图片色彩空间转化为 RGB 形式。
  2. 当图片中的物体贴近时,可利用腐蚀将相近的物体进一步缩小到一个点再进行计算。

系统设计与开发 实验报告-4
https://flowerdown.org/posts/20221015-102108
作者
Unrealfeathers
发布于
2022年10月15日
许可协议