亲宝软件园·资讯

展开

python opencv目标外接图形

DanCheng-studio 人气:0

当使用cv2.findContours函数找到图像中的目标后,我们通常希望使用一个集合区域将图像包围起来,这里介绍opencv几种几何包围图形。

简介

无论使用哪种几何外接方法,都需要先进行轮廓检测。

当我们得到轮廓对象后,可以使用boundingRect()得到包裹此轮廓的最小正矩形,minAreaRect()得到包裹轮廓的最小矩形(允许矩阵倾斜),minEnclosingCircle()得到包裹此轮廓的最小圆形。

最小正矩形和最小外接矩形的区别如下图所示:

实现

这里给出上述5中外接图形在python opencv上的实现:

①. 边界矩形

import cv2
import numpy as np

img = cv2.imread('/home/pzs/图片/test.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
thresh, binary = cv2.threshold(gray, 180, 255, cv2.THRESH_BINARY_INV)
binary, contours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
cv2.imshow('binary', binary)
cv2.waitKey(0)

for cnt in contours:
    x,y,w,h = cv2.boundingRect(cnt)
    cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 1)

cv2.imshow('image', img)
cv2.waitKey(0)

②. 最小外接矩形

import cv2
import numpy as np

img = cv2.imread('/home/pzs/图片/test.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
thresh, binary = cv2.threshold(gray, 180, 255, cv2.THRESH_BINARY_INV)
binary, contours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
cv2.imshow('binary', binary)
cv2.waitKey(0)

for cnt in contours:
    rect = cv2.minAreaRect(cnt)
    box = cv2.boxPoints(rect)
    box = np.int0(box)
    cv2.drawContours(img, [box], 0, (0, 0, 255), 2)


cv2.imshow('image', img)
cv2.waitKey(0)

③. 最小外接圆

import cv2
import numpy as np

img = cv2.imread('/home/pzs/图片/test.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
thresh, binary = cv2.threshold(gray, 180, 255, cv2.THRESH_BINARY_INV)
binary, contours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
cv2.imshow('binary', binary)
cv2.waitKey(0)

for cnt in contours:
    (x, y), radius = cv2.minEnclosingCircle(cnt)
    center = (int(x), int(y))
    radius = int(radius)
    cv2.circle(img, center, radius, (255, 0, 0), 2)

cv2.imshow('image', img)
cv2.waitKey(0)

加载全部内容

相关教程
猜你喜欢
用户评论