Python Opencv实践 - 矩形轮廓绘制(直边矩形,最小外接矩形)

import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt

img = cv.imread("../SampleImages/stars.png")
plt.imshow(img[:,:,::-1])

img_gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
#通过cv.threshold转换为二值图
ret,thresh = cv.threshold(img_gray, 127, 255, 0)
plt.imshow(thresh, cmap=plt.cm.gray)

#轮廓检测
contours,hierarchy = cv.findContours(thresh, 1, 2)
#绘制轮廓
img_contours_org = img.copy()
img_contours_org = cv.drawContours(img_contours_org, contours, -1, (0,255,0), 2)
plt.imshow(img_contours_org[:,:,::-1])

img_rect_contour = img.copy()
for contour in contours:
    #1. 绘制直边界矩形
    #x,y,w,h = cv.boundingRect(contour)
    #contour: 轮廓信息
    #x,y,w,h: 矩形左上角(x,y)坐标,以及矩形的宽度和高度
    #参考资料:https://blog.csdn.net/hjxu2016/article/details/77833984
    x,y,w,h = cv.boundingRect(contour)
    img_rect_contour = cv.rectangle(img_rect_contour, (x,y), (x+w,y+h), (0,255,0), 2)
    #2. 绘制旋边界矩形结果
    #rect = cv.minAreaRect(contour)
    #contour:轮廓信息
    #rect: 最小外接矩阵的信息(中心(x,y),(w,h),旋转角度)
    #参考资料:https://blog.csdn.net/lanyuelvyun/article/details/76614872
    rect = cv.minAreaRect(contour)
    #使用boxPoints获得最小外接矩阵的4个顶点坐标
    box = cv.boxPoints(rect)
    #转换为int类型
    box = np.intp(box)
    #使用cv.polylines绘制外接矩形
    cv.polylines(img_rect_contour, [box], True, (0,0,255), 2)

plt.imshow(img_rect_contour[:,:,::-1])

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

亦枫Leonlew

希望这篇文章能帮到你

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值