Python Opencv实践 - 矩形轮廓绘制(直边矩形,最小外接矩形)

news/2024/7/21 7:47:05 标签: 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])

 


http://www.niftyadmin.cn/n/4997983.html

相关文章

Pygame中Trivia游戏解析6-3

3.3 Trivia类的show_question()函数 Trivia类的show_question()函数的作用是显示题目。主要包括显示题目框架、显示题目内容和显示题目选项等三部分。 3.3.1 显示题目的框架 在show_question()函数中,通过以下代码显示题目的框架。 print_text(font1, 210, 5, &q…

OpenCV(十七):拉普拉斯图像金字塔

1.拉普拉斯图像金字塔原理 拉普拉斯图像金字塔是一种多尺度图像表示方法,通过对高斯金字塔进行差分运算得到。它能够提供图像在不同尺度上的细节信息,常用于图像处理任务如图像增强、边缘检测等。 下面是拉普拉斯图像金字塔的原理和步骤: 构…

js数组中添加、删除、更改、查询元素方法

数组添加元素 1.Array.push() 追加到后面 – 原数组 let arry [1,2,3,4]; array.push(5,6) 2.Array.unshift()追加到前面 – 原数组 let array [1,2,3,4]; array.unshift(2,4) 3. Array.splice(索引位置,个数,添加的元素) – 原数组 let array [1,2,3,4,5]; arr…

【进阶之路】pytest自动化测试框架从0-1精通实战

前言 1、运行方式 命令行模式: pytest -s login.py主函数模式: if __name__ __main__:pytest.main(["-s", "login.py"])pytest.ini运行: 在 pytest.ini 文件中配置 pytest 的运行参数。 注意点: 位置&…

MySQL中的索引事务(2)事务----》数据库运行的原理知识+面试题~

本篇文章建议读者结合:MySQL中的索引事务(1)索引----》数据库运行的原理知识面试题~_念君思宁的博客-CSDN博客此时,如果你根据name来查询,查到叶子节点得到的只是主键id,还需要通过主键id去主键的B树里面在…

TopSAP天融信 LINUX客户端 CentOS版安装

TopSAP天融信 LINUX客户端 CentOS版安装 下载客户端安装运行 下载客户端 项目需要用到CentOS环境下的天融信客户端,可以下载LINUX版 下载地址 https://app.topsec.com.cn/ X86_64(或AMD64)架构客户端deb包:V3.5.2.36.2 MD5 :EC032529A8D3A645B7368F28E…

C++系列--this指针的用途

this指针的用途 this指针的本质this指针的用途this指针区分成员变量和形参this作为成员函数返回值 this指针的本质 this指针本身是一个成员函数的形参,相当于Python中的self。在调用成员函数时将对象的地址作为实参传递给 this。this形参是隐式的,它并不…