轮廓检测,然后判断轮廓大小,识别位置
- import cv2
-
-
- def cv_show(img): # 展示图片
- cv2.imshow("img", img)
- cv2.waitKey(0)
- cv2.destroyAllWindows()
-
-
- img = cv2.imread("bg.png")
- gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 灰度图片
-
- img2 = cv2.GaussianBlur(gray, (5, 5), 0) # 高斯模糊
- v1 = cv2.Canny(img2, 20, 80) # 边缘检测, 20和80分别为两个阈值
- cv_show(v1)
-
- counts, _ = cv2.findContours(v1, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # 轮廓检测
-
- result = img.copy()
- color = (0, 255, 0)
- for c in counts:
- area = cv2.contourArea(c, True)
- x, y, w, h = cv2.boundingRect(c) # 计算x,y,宽,高
- if w > 100 or w < 50 or h > 70 or h < 50: # 按照实际缺口的大小调整过滤条件
- continue
-
- print(x, y, w, h)
- cv2.rectangle(result, (x, y), (x + w, y + h), color, 1) # 画出矩形框
-
- cv_show(result) # 展示最终结果图
-