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])
相关推荐
酷可达拉斯4 分钟前
Linux操作系统-shell编程(0)
linux·运维·服务器·python·云计算
W658034196 分钟前
2026年AI编程工具实测横评:Claude Code v2.1、Cursor 3.0、Trae SOLO、Copilot、Windsurf 谁更好用?
python·copilot·ai编程
深念Y17 分钟前
开发者如何清理和迁移C盘堆积的垃圾
c语言·开发语言
snow@li18 分钟前
技术栈对应:Vue (前端) + SpringBoot (Java 后端) =》 Python 全场景配套
python
2501_9095091033 分钟前
DAY 28
开发语言·python
码云骑士38 分钟前
71-Agent记忆系统-短期记忆-长期记忆-向量知识库三层架构
python·架构
卷无止境39 分钟前
Python 的 exec 与 eval :动态代码执行的能力、风险与工程实践
后端·python
user-猴子40 分钟前
从零构建 2048 游戏,解析“Python-Use”范式的完整闭环
开发语言·python·游戏
郝学胜_神的一滴1 小时前
Python 高级编程 025:二分利器bisect模块:优雅维系有序序列,极致优化检索性能
python·pycharm
qq_401700411 小时前
Qt容器性能优化:QVector、QHash、QMap到底应该怎么选?
开发语言·qt·性能优化