实验四、用 OpenCV 统计物体数量

一、实验简介

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

二、实验目的

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

三、实验步骤

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

实验步骤

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

实验代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import cv2
import matplotlib.pyplot as plt
import numpy as np
%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)

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

实验步骤

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

实验代码

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 matplotlib.pyplot as plt
import numpy as np
%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)

四、思考分析

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

实验四、用 OpenCV 统计物体数量
https://flowerdown.org/posts/20221015-102108.html
作者
Unrealfeather
发布于
2022年10月15日
许可协议