python-图片处理+轮廓提取

上一篇代码讲过如何得到黑白图的代码。

效果如下,也可看下面的代码,也包含在里面了

然后获取轮廓的代码:

contours,heriachy = cv2.findContours(binary,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)

import cv2
import numpy as np
 
img = cv2.imread("img.jpg")   #读取图片
w,h = img.shape[:-1]  #获取长宽
print(w,h)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)  #变为灰度图 
ret, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)   ## 阈值分割得到二值化图片
# cv2.namedWindow('binary', cv2.WINDOW_AUTOSIZE)
# cv2.imshow('binary', binary)
# cv2.waitKey(0)

# binary = binary >2   #得到图片通道的逻辑值


# '''
# [[False False False ... False False False]
#  [False False False ... False False False]
#  [False False False ... False False False]
#  ...
#  [False False False ... False False False]
#  [False False False ... False False False]
#  [False False False ... False False False]]
# '''
# # 创建全为0的背景图
# fg_image = np.zeros(img.shape[:-1], dtype=np.uint8)
# # 创建全为255的背景图
# fg_image2 = np.ones(img.shape[:-1], dtype=np.uint8)*255

# FG_img = np.where(binary,fg_image,fg_image2) #参数1为Ture返回参数2,否则参数3


contours,heriachy = cv2.findContours(binary,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
for i ,contour in enumerate(contours):
    cv2.drawContours(img,contours,i,(0,0,255),2)
    #第一个参数指在哪幅图上绘制轮廓信息,第二个参数是轮廓本身,第三个参数是指定绘制哪条轮廓
    #第四个参数是绘图的颜色,第五个参数是绘制的线宽 输入-1则表示填充
    print(i)
cv2.imshow("detect contours",img)
cv2.waitKey(0)

猜你喜欢

转载自blog.csdn.net/qq_34904125/article/details/123311372