一、框标定代码
import cv2
import numpy as np
from sobel算子边缘检测 import sobel_cal
MIN_BOX = 2500
def draw_min_rect_circle(img, cnts):
img = np.copy(img)
for cnt in cnts:
x, y, w, h = cv2.boundingRect(cnt)
if w * h < MIN_BOX:
continue
print(x, y, x + w, y + h)
cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
return img
def run():
imgs = cv2.imread('img/20.JPG')
imgs, image = sobel_cal(imgs)
thresh = cv2.GaussianBlur(image, (5, 5), 0)
thresh = cv2.Canny(thresh, 0, 104)
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
"""
[[[-1 -1 -1 -1]]] :hierarchy # cv2.Canny()
[[[ 1 -1 -1 -1]
[ 2 0 -1 -1]
[ 3 1 -1 -1]
[-1 2 -1 -1]]] :hierarchy # cv2.threshold()
"""
imgs = draw_min_rect_circle(imgs, contours)
cv2.imshow("contours", imgs)
cv2.waitKey()
if __name__ == '__main__':
run()
二、结果展示
(1)待处理图像
(2)二值化后的图像
(3)框标定后的图像
参考
python+openCV利用函数cv2.findContours()和cv2.drawContours查找并绘制轮廓