使用OpenCV绘制矩形轮廓框,一般包括如下步骤:
1: [367,201 367,210 371,201 371,210]
2: [362,195 362,197 363,195 363,197]
3: [297,187 297,190 301,187 301,190]
4: [396,182 396,184 398,182 398,184]
5: [371,168 371,190 394,168 394,190]
6: [382,166 382,169 387,166 387,169]
7: [211,160 211,189 238,160 238,189]
8: [377,148 377,163 402,148 402,163]
9: [308,148 308,217 353,148 353,217]
10: [315,193 315,215 348,193 348,215]
11: [277,148 277,188 311,148 311,188]
12: [241,147 241,190 274,147 274,190]
13: [179,132 179,189 235,132 235,189]
14: [355,129 355,192 372,129 372,192]
附上自己写的实验代码:
# coding=utf-8
import cv2
# 原图像路径
origin_pic = cv2.imread('./origin.jpg')
# 文档路径,用于记录轮廓框坐标
txt_file = open('./contours.txt', 'w')
# 要先转换成单通道灰度图像才能进行后续的图像处理
pic = cv2.cvtColor(origin_pic, cv2.COLOR_BGR2GRAY)
# 阈值处理,将前景全填充为白色,背景全填充为黑色
_, pic = cv2.threshold(src=pic, thresh=200, maxval=255, type=1)
# 中值滤波,去除椒盐噪声
pic = cv2.medianBlur(pic, 5)
# 边缘检测,得到的轮廓列表
_1, contours, _2 = cv2.findContours(pic, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# 根据轮廓列表,循环在原始图像上绘制矩形边界
for i in range(len(contours)):
cnt = contours[i]
x, y, w, h = cv2.boundingRect(cnt)
origin_pic = cv2.rectangle(origin_pic, (x, y), (x+w, y+h), (255, 0, 0), 2)
txt_file.write('{}: [{},{} {},{} {},{} {},{}]\n'.format(i+1, x, y, x, y+h, x+w, y, x+w, y+h))
cv2.imwrite('./rectangle.jpg', origin_pic)
txt_file.close()
cv2.imshow('', origin_pic)
cv2.waitKey(0)
cv2.destroyAllWindows()