python opencv3 轮廓检测


git:https://github.com/linyi0604/Computer-Vision

 1 # coding:utf8
 2 
 3 import cv2  4 import numpy as np  5 
 6 # 创建一个200*200 的黑色空白图像
 7 img = np.zeros((200, 200), dtype=np.uint8)  8 # 在图像的中央位置 放置一个100*100的白色方块
 9 img[50:150, 50: 150] = 255
10 
11 cv2.imshow("image", img) 12 # 二值化操作
13 ret, thresh = cv2.threshold(img, 127, 255, 0) 14 """
15 ret, dst = cv2.threshold(src, thresh, value, type) 16 参数: 17  src: 原图像 18  thresh: 阈值 19  value: 新值 大于或小于阈值的值将赋新值 20  type: 方法类型,有如下取值: 21  cv2.THRESH_BINARY 黑白二值 22  cv2.THRESH_BINARY_INV 黑白二值翻转 23  cv2.THRESH_TRUNC 得到多像素值 24  cv2.THRESH_TOZERO 25  cv2.THRESH_TOZERO_INV 26 返回值: 27  ret: 得到的阈值值 28  dst: 阈值化后的图像 29 """
30 
31 # 得到 修改后的图像, 轮廓, 轮廓的层次
32 image, contours, hierarchy = cv2.findContours( 33  thresh, 34  cv2.RETR_TREE, 35  cv2.CHAIN_APPROX_SIMPLE 36 ) 37 
38 """
39 img, contours, hierarchy = cv2.findContours(输入图像, 层次类型, 逼近方法) 40 参数: 41  输入图像: 该方法会修改输入图像,建议传入输入图像的拷贝 42  层次类型: 43  cv2.RETR_TREE 会得到图像中整体轮廓层次 44  cv2.RETR_EXTERNAL 只得到最外面的轮廓 45  逼近方法: 46 
47 返回值: 48  img: 修改后的图像 49  contours: 图像的轮廓 50  hierarchy: 图像和轮廓的层次 51     
52 """
53 # 原图像转换成bgr图像
54 color = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) 55 # 用绿色 在原图像上画出轮廓
56 img = cv2.drawContours(color, contours, -1, (0, 255, 255), 2) 57 
58 cv2.imshow("contours", color) 59 cv2.waitKey() 60 cv2.destroyAllWindows()

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM