OpenCV | OpenCV检测图像轮廓

举报
DrugAI 发表于 2021/07/15 04:44:28 2021/07/15
【摘要】 步骤 读取图像为灰度图像。使用cv2.threshold()函数获取阈值图像。使用cv2.findContours()并传递阈值图像和必要的参数。findContours()返回轮廓。您可以将其绘制在原始图像或空白图像上。 import cv2import numpy as np img = cv2.imread('original.png', cv2.IMREAD_UN...

步骤

  1. 读取图像为灰度图像。
  2. 使用cv2.threshold()函数获取阈值图像。
  3. 使用cv2.findContours()并传递阈值图像和必要的参数。
  4. findContours()返回轮廓。您可以将其绘制在原始图像或空白图像上。


      import cv2
      import numpy as np
      img = cv2.imread('original.png', cv2.IMREAD_UNCHANGED)
      #convert img to grey
      img_grey = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
      #set a thresh
      thresh = 100
      #get threshold image
      ret,thresh_img = cv2.threshold(img_grey, thresh, 255, cv2.THRESH_BINARY)
      #find contours
      img2, contours, hierarchy = cv2.findContours(thresh_img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
      #create an empty image for contours
      img_contours = np.zeros(img.shape)
      # draw the contours on the empty image
      cv2.drawContours(img_contours, contours, -1, (0,255,0), 3)
      #save image
      cv2.imwrite('contours.png',img_contours)
  
 

原图

输出图


参考

https://pythonexamples.org/python-opencv-cv2-find-contours-in-image/

 

文章来源: drugai.blog.csdn.net,作者:DrugAI,版权归原作者所有,如需转载,请联系作者。

原文链接:drugai.blog.csdn.net/article/details/103026587

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。