我有一个类似于以下的图像。我想分离两个数字7
和4
,如图所示,因为我想为这两个对象中的每一个都有一个边界框。
我怎么能用OpenCV做到这一点?我不知道,我怎么能这样做,并且正在考虑使用Sobel算子是否有某种方法。我厌倦的唯一一件事就是获得Sobel。
s = cv2.Sobel(img, cv2.CV_64F,1,0,ksize=5)
但不知道如何从这里开始。
要分割和检测图像中的图形,主要思想如下:
cv2.cvtColor()
将图像转换为灰度cv2.GaussianBlur()
模糊图像cv2.Canny()
找到边缘cv2.findContours()
查找轮廓cv2.boundingRect()
获取边界矩形
使用Numpy切片查找每个轮廓的ROI
使用cv2.Rectangle()
绘制边界框矩形产量
检测到轮廓:2
import numpy as np
import cv2
original_image = cv2.imread("1.png")
image = original_image.copy()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (3, 3), 0)
canny = cv2.Canny(blurred, 120, 255, 1)
cv2.imshow("canny", canny)
# Find contours in the image
cnts = cv2.findContours(canny.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
contours = []
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
cv2.rectangle(original_image,(x,y),(x+w,y+h),(0,255,0),3)
contours.append(c)
cv2.imshow("detected", original_image)
print('contours detected: {}'.format(len(contours)))
cv2.waitKey(0)
按照步骤:
您可能需要根据大小或位置过滤轮廓。