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])
相关推荐
ellis1970几秒前
Lua协程coroutine库用法
开发语言·lua
Hello.Reader10 分钟前
Flink DataStream「全分区窗口处理」mapPartition / sortPartition / aggregate / reduce
大数据·python·flink
网安INF10 分钟前
Python核心数据结构与函数编程
数据结构·windows·python·网络安全
nwsuaf_huasir20 分钟前
matlab构造带通巴特沃斯滤波器进行滤波
开发语言·matlab
救救孩子把21 分钟前
从 JDK 8 到 JDK 23:HotSpot 垃圾回收器全景演进与深度剖析
java·开发语言·jvm·jdk
列兵阿甘25 分钟前
知微传感Dkam系列3D相机SDK例程篇:Python设置相机触发模式
python·数码相机·3d
格林威26 分钟前
短波红外相机的简单介绍和场景应用
人工智能·数码相机·计算机视觉·目标跟踪·视觉检测·工业相机·工业镜头
清辞85338 分钟前
C++入门(底层知识C与C++的不同)
开发语言·c++·算法
fqbqrr42 分钟前
2510C++,api设计原则,不除零
开发语言·c++
~kiss~1 小时前
图像处理~多尺度边缘检测算法
图像处理·算法·计算机视觉