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

时间:2022-07-27
本文章向大家介绍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]

以上这篇Python实现图片查找轮廓、多边形拟合、最小外接矩形代码就是小编分享给大家的全部内容了,希望能给大家一个参考。