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])
相关推荐
Sheeep18 分钟前
学习Pytest + Hypothesis——能帮你发现你自己都没想到的 bug
python·测试
jndingxin36 分钟前
OPenCV CUDA模块目标检测----- HOG 特征提取和目标检测类cv::cuda::HOG
人工智能·opencv·目标检测
come1123438 分钟前
Claude 写 PHP 项目的完整小白教程
开发语言·php
虾球xz42 分钟前
CppCon 2015 学习:Concurrency TS Editor’s Report
开发语言·c++·学习
板鸭〈小号〉1 小时前
命名管道实现本地通信
开发语言·c++
清醒的兰1 小时前
OpenCV 图像像素的逻辑操作
人工智能·opencv·计算机视觉
刘维克1 小时前
(预发布)[阿维笔记]分析优化CloudStudio高性能工作空间的GPU训练速度和效果
深度学习·计算机视觉
站大爷IP1 小时前
用Python打造办公效率神器:从数据到文档的全流程自动化实践
python
hongjianMa1 小时前
ModuleNotFoundError No module named ‘torch_geometric‘未找到
python
火兮明兮2 小时前
Python训练第四十五天
开发语言·python