OpenCV | OpenCV检测图像轮廓

简介: OpenCV | OpenCV检测图像轮廓

步骤

  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) 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) 

原图

image.png

输出图

image.png


目录
相关文章
|
1月前
|
算法 计算机视觉
OpenCV(四十三):Shi-Tomas角点检测
OpenCV(四十三):Shi-Tomas角点检测
25 0
|
1月前
|
计算机视觉
OpenCV(三十八):二维码检测
OpenCV(三十八):二维码检测
46 0
|
1月前
|
编解码 计算机视觉
OpenCV(三十六):霍夫直线检测
OpenCV(三十六):霍夫直线检测
25 0
|
1月前
|
计算机视觉 索引
OpenCV(三十五):凸包检测
OpenCV(三十五):凸包检测
24 0
|
1月前
|
存储 资源调度 算法
Opencv(C++)系列学习---SIFT、SURF、ORB算子特征检测
Opencv(C++)系列学习---SIFT、SURF、ORB算子特征检测
|
1月前
|
存储 算法 计算机视觉
OpenCV(四十二):Harris角点检测
OpenCV(四十二):Harris角点检测
28 0
|
16天前
|
编解码 计算机视觉 Python
opencv 图像金字塔(python)
opencv 图像金字塔(python)
|
1月前
|
存储 计算机视觉 C++
Opencv(C++)学习系列---特征点检测和匹配
Opencv(C++)学习系列---特征点检测和匹配
|
1月前
|
存储 计算机视觉
OpenCV(三十九):积分图像
OpenCV(三十九):积分图像
18 0
|
1月前
|
计算机视觉
OpenCV(三十四):轮廓外接最大、最小矩形和多边形拟合
OpenCV(三十四):轮廓外接最大、最小矩形和多边形拟合
79 0