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])
相关推荐
wjs20242 小时前
状态模式(State Pattern)
开发语言
我命由我123452 小时前
Kotlin 数据容器 - List(List 概述、创建 List、List 核心特性、List 元素访问、List 遍历)
java·开发语言·jvm·windows·java-ee·kotlin·list
liulilittle2 小时前
C++ TAP(基于任务的异步编程模式)
服务器·开发语言·网络·c++·分布式·任务·tap
im_AMBER3 小时前
学习日志19 python
python·学习
励志要当大牛的小白菜4 小时前
ART配对软件使用
开发语言·c++·qt·算法
mortimer6 小时前
安装NVIDIA Parakeet时,我遇到的两个Pip“小插曲”
python·github
@昵称不存在6 小时前
Flask input 和datalist结合
后端·python·flask
爱装代码的小瓶子6 小时前
数据结构之队列(C语言)
c语言·开发语言·数据结构
赵英英俊7 小时前
Python day25
python
东林牧之7 小时前
Django+celery异步:拿来即用,可移植性高
后端·python·django