欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

Python实现图片查找轮廓、多边形拟合、最小外接矩形代码

时间:2021-09-26 10:15:42|栏目: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()

画出的所有轮廓:

在原轮廓基础上画出筛选后的轮廓(绿色部分,没有实际意义):

补充知识:OpenCV python 轮廓(连通域)最小外接圆形

原图:[cc.jpg]

import cv2
import numpy as np

def main():

  # 1.导入图片
  img_src = cv2.imread("cc.jpg")

  # 2.灰度化,二值化
  img_gray = cv2.cvtColor(img_src, cv2.COLOR_BGR2GRAY)
  ret, img_bin = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY)

  # 3.连通域分析
  img_bin, contours, hierarchy = cv2.findContours(img_bin,
                 cv2.RETR_LIST,
                 cv2.CHAIN_APPROX_SIMPLE)

  # 4.获取最小外接圆 圆心 半径
  center, radius = cv2.minEnclosingCircle(contours[0])
  center = np.int0(center)

  # 5.绘制最小外接圆
  img_result = img_src.copy()
  cv2.circle(img_result, tuple(center), int(radius), (255, 255, 255), 2)

  # 6.显示结果图片
  cv2.imshow("img_src", img_src)
  cv2.imshow("img_result", img_result)

  cv2.waitKey()
  cv2.destroyAllWindows()

if __name__ == '__main__':
  main()

处理结果:[img_sult.jpg]

上一篇:pandas 使用insert插入一列

栏    目:Python代码

下一篇:python自动化UI工具发送QQ消息的实例

本文标题:Python实现图片查找轮廓、多边形拟合、最小外接矩形代码

本文地址:http://www.codeinn.net/misctech/177370.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有