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])
相关推荐
摆烂且佛系2 分钟前
FastByteArrayOutputStream和ByteArrayInputStream有什么区别
java·开发语言
Chandler2410 分钟前
Go语言:json 作用和语法
开发语言·golang·json
凤年徐12 分钟前
【C/C++】自定义类型:结构体
c语言·开发语言·c++·经验分享·笔记·算法
chilavert31818 分钟前
关于Python 实现接口安全防护:限流、熔断降级与认证授权的深度实践
python·网络安全
能来帮帮蒟蒻吗30 分钟前
Python -将MP4文件转为GIF图片
开发语言·python·学习·视频
忆源34 分钟前
【Qt】之音视频编程2:QtAV的使用篇
开发语言·qt·音视频
suoxiao77742 分钟前
通过anaconda安装jupyter
ide·python·jupyter
程序员阿鹏1 小时前
Git的安装和配置(idea中配置Git)
java·开发语言·ide·git·intellij-idea·idea
百锦再1 小时前
MK米客方德SD NAND:无人机存储的高效解决方案
人工智能·python·django·sqlite·android studio·无人机·数据库开发
景天科技苑1 小时前
【Rust trait特质】如何在Rust中使用trait特质,全面解析与应用实战
开发语言·后端·rust·trait·rust trait·rust特质