OpenCV轮廓、边界框、最小矩形、最小闭圆检测

import cv2
import numpy as np

# 函数cv2.pyrDown()是降低图像分辨率,变为原来一半
img = cv2.pyrDown(cv2.imread("G:/Python_code/OpenCVStudy/images/timg.jpg", cv2.IMREAD_UNCHANGED))

# 将图片转化为灰度,再进行二值化
ret, thresh = cv2.threshold(cv2.cvtColor(img.copy(), cv2.COLOR_BGR2GRAY), 127, 255, cv2.THRESH_BINARY)
image, contours, hier = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

for c in contours:
    # 边界框:
    # find bounding box coordinates
    # boundingRect()将轮廓转化成(x,y,w,h)的简单边框,cv2.rectangle()画出矩形[绿色(0, 255, 0)]
    x, y, w, h = cv2.boundingRect(c)
    cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)

    # 最小矩形区域:
    # 1 计算出最小矩形区域 2 计算这个的矩形顶点 3 由于计算出来的是浮点数,而像素是整型,所以进行转化 4 绘制轮廓[红色(0, 0, 255)]
    # find minimum area
    rect = cv2.minAreaRect(c)
    # calculate coordinates of the minimum area rectangle
    box = cv2.boxPoints(rect)
    # normalize coordinates to integers
    box = np.int0(box)
    # draw contours
    cv2.drawContours(img, [box], 0, (0, 0, 255), 3)

    # 最小闭圆的轮廓:
    # calculate center and radius of minimum enclosing circle[蓝色(255, 0, 0)]
    (x, y), radius = cv2.minEnclosingCircle(c)
    # cast to integers
    center = (int(x), int(y))
    radius = int(radius)
    # draw the circle
    img = cv2.circle(img, center, radius, (255, 0, 0), 2)

# 轮廓检测:绘制轮廓
cv2.drawContours(img, contours, -1, (255, 0, 0), 1)
cv2.imshow("contours", img)

cv2.waitKey()
cv2.destroyAllWindows()

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值