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])
相关推荐
AI技术控18 小时前
TimesNet 论文解读:把一维时间序列变成二维变化建模的通用时序骨干
人工智能·python
我还记得那天18 小时前
用C语言实现一个简易扫雷小游戏
c语言·开发语言
段ヤシ.18 小时前
回顾Java知识点,面试题汇总Day10(持续更新)
java·开发语言·spring
小明同学0118 小时前
C++后端项目:统一大模型接入 SDK(二)
开发语言·c++
And_Ii18 小时前
leetCode 146. LRU 缓存
python·链表
我不是懒洋洋18 小时前
【C++】类和对象( 类的定义、实例化、 this指针、 C++和C语言实现Stack对比)
c语言·开发语言·数据结构·c++·经验分享·算法·visual studio
Perry 12318 小时前
Java中的多态
java·开发语言
乐迪信息19 小时前
乐迪信息:港口夜间船舶巡查难,AI摄像机法全天候监测
人工智能·物联网·算法·计算机视觉·目标跟踪
sali-tec19 小时前
C# 基于OpenCv的视觉工作流-章74-线-线距离
图像处理·人工智能·opencv·算法·计算机视觉
2501_9307077819 小时前
使用C#代码拆分 PowerPoint 演示文稿
开发语言·c#·powerpoint