• Python OpenCV轮廓排序(按照面积大小)


    OpenCV轮廓排序(按照面积大小),原图如下:

    代码如下:

    import cv2
    import numpy as np
    
    # putText函数使用的字体定义
    font = cv2.FONT_HERSHEY_SIMPLEX
    PI = 3.1415926
     
    # 读取图片、灰度转换、OTSU阈值
    img = cv2.imread("test.png")
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    ret,thresh = cv2.threshold(gray,0,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
    # 查看二值化结果
    cv2.imshow("thres", thresh)
    cv2.imwrite("thres.jpg", thresh)
    
    # 轮廓查找
    _, contours,hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
    
    def cnt_area(cnt):
      area = cv2.contourArea(cnt)
      return area
    
    contours.sort(key = cnt_area, reverse=False)
    for i in range(0, len(contours)):
      (x, y, w, h) = cv2.boundingRect(contours[i])
      cv2.rectangle(img,(x,y),(x+w, y+h),(255,0,0),2, cv2.LINE_AA)
      cv2.putText(img,"No.%d"%(i+1),(x,y-5),font,0.8,(255,0,0),2)
    
    cv2.imshow("contours", img)
    cv2.imwrite("result1.jpg",img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
           
    

    reverse=False(默认)降序排列,reverse=True升序排列

    效果如如下:

    更多相关文章咨询欢迎关注:OpenCV与AI深度学习

  • 相关阅读:

    2018.10.18 常用API部分测试题
    2018.10.18课堂笔记HashMap之前
    JavaScript 的 this 原理
    vue h5转换uni-app
    Vue.js 3.0 新特性预览
    ES6模块与CommonJS的区别
    同源策略和跨域问题
    一口气了解 babel
    媒体查询,移动端常见布局以及其他
  • 原文地址:https://www.cnblogs.com/stq054188/p/12175869.html
Copyright © 2020-2023  润新知