对图像中的图形进行分割和检测,主要思路如下:
- 使用
cv2.cvtColor()将图像转换为灰度
- 用
cv2.GaussianBlur()模糊图像
- 使用
cv2.Canny() 查找边缘
- 使用
cv2.findContours() 查找轮廓并使用从左到右排序
imutils.contours.sort_contours() 确保当我们遍历轮廓时,它们的顺序正确
- 遍历每个轮廓
- 使用
cv2.boundingRect()获取边界矩形
- 使用 Numpy 切片查找每个轮廓的 ROI
- 使用
cv2.rectangle()绘制边界框矩形
Canny 边缘检测
检测到的轮廓
裁剪和保存的 ROIs
输出
Contours Detected: 2
代码
import numpy as np
import cv2
from imutils import contours
# Load image, grayscale, Gaussian blur, Canny edge detection
image = cv2.imread("1.png")
original = image.copy()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (3,3), 0)
canny = cv2.Canny(blurred, 120, 255, 1)
# Find contours
contour_list = []
ROI_number = 0
cnts = cv2.findContours(canny, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
cnts, _ = contours.sort_contours(cnts, method="left-to-right")
for c in cnts:
# Obtain bounding rectangle for each contour
x,y,w,h = cv2.boundingRect(c)
# Find ROI of the contour
roi = image[y:y+h, x:x+w]
# Draw bounding box rectangle, crop using Numpy slicing
cv2.rectangle(image,(x,y),(x+w,y+h),(0,255,0),3)
ROI = original[y:y+h, x:x+w]
cv2.imwrite('ROI_{}.png'.format(ROI_number), ROI)
contour_list.append(c)
ROI_number += 1
print('Contours Detected: {}'.format(len(contour_list)))
cv2.imshow("image", image)
cv2.imshow("canny", canny)
cv2.waitKey()