Python图片查找轮廓、多边形拟合、最小外接矩形操作实例

1、概述

       经常用到轮廓查找和多边形拟合等opencv操作,因此记录以备后续使用。本文代码中的阈值条件对图片没有实际意义,仅仅是为了测试。

       原图为:
                                       在这里插入图片描述

2、测试代码:

import cv2
import numpy as np

img = cv2.imread('/home/yasin/coffe.jpg')
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

_, contours, hierarchy = cv2.findContours(img_gray, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

cv2.drawContours(img, contours, -1, (255, 0, 255), 1)
cv2.namedWindow('Result of drawContours', 0)
cv2.imshow('Result of drawContours', img)
cv2.waitKey()


cnt = 0
for i in range(len(contours)):
    arclen = cv2.arcLength(contours[i], True)
    epsilon = max(3, int(arclen * 0.02))   # 拟合出的多边形与原轮廓最大距离,可以自己设置,这里根据轮廓周长动态设置
    approx = cv2.approxPolyDP(contours[i], epsilon, False) # 轮廓的多边形拟合
    area = cv2.contourArea(contours[i])     # 计算面积
    rect = cv2.minAreaRect(contours[i])
    box = np.int0(cv2.boxPoints(rect))      # 计算最小外接矩形顶点
    h = int(rect[1][0])
    w = int(rect[1][1])
    if min(h, w) == 0:
        ration = 0
    else:
        ration = max(h,w) /min(h,w)   # 长宽比

    # 对长宽比,轮廓面积,拟合出的多边形顶点数做筛选
    if ration < 10 and area > 20 and area < 4000 and approx.shape[0] > 3 :
        # 对满足条件的轮廓画出轮廓的拟合多边形
        cv2.polylines(img, [approx], True, (0, 255, 0), 1)

cv2.namedWindow('Result of filtered', 0)
cv2.imshow('Result of filtered', img)
cv2.waitKey()

       画出的所有轮廓:
                                                          在这里插入图片描述
       在原轮廓基础上画出筛选后的轮廓(绿色部分,没有实际意义):
                                       
                                       
                                                          在这里插入图片描述

  • 3
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

南洲.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值