#! usr/bin/python
# coding=utf-8
import numpy as np
import cv2
# opencv 轮廓检测
image = cv2.imread('test.jpg', 0)
image_copy = image.copy()
ret, thresh = cv2.threshold(image_copy, 127, 255, 0)
img, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
color = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
for c in contours:
x, y, w, h = cv2.boundingRect(c)
cv2.rectangle(color, (x, y), (x + w, y + h), (0, 0, 255), 1)
rect = cv2.minAreaRect(c)
box = cv2.boxPoints(rect)
box = np.int0(box)
cv2.drawContours(color, [box], 0, (0, 0, 255), 1)
(x, y), radius = cv2.minEnclosingCircle(c)
center = (int(x), int(y))
radius = int(radius)
cv2.circle(color, center, radius, (0, 0 ,255), 1)
# cv2.drawContours(color, contours, -1, (255, 0, 0), 2)
cv2.imshow('contour_image', color)
cv2.waitKey()
cv2.destroyAllWindow()
网友评论