import cv2 as cv2
import matplotlib.pyplot as plt
import numpy as np
def cv_show(name,img):
cv2.imshow(name,img)
cv2.waitKey(0)
cv2.destroyAllWindows()
if __name__ == "__main__":
#图像轮廓识别步骤
#1.导入图片
img = cv2.imread(r'E:\iu.png')
#2.转化为灰度图减少计算量
grey = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
#3.二值化图像提高精度
ret,thresh1 = cv2.threshold(grey, 150, 255, cv2.THRESH_BINARY)
# cv_show('thresh',thresh1)
#4.绘制轮廓
contours, hierarchy = cv2.findContours(thresh1,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
draw_img = img.copy()
res = cv2.drawContours(draw_img,contours,-1,(0,0,255),2) #后面三个参数的意思分别是:-1:全部轮廓;(0,0,255)以红色通道展示;2:轮廓线条宽度
cv_show('res',res)
结果:
PS:
1.使用img.copy()的目的是避免修改原图,轮廓就不会被保存在原图上
2.可能运行会在findContours中产生not enough values to unpack的错误,网上代码都是:
binary, contours, hierarchy = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
已经不需要第一个binary输出了,所以直接:
contours, hierarchy = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
然后cv2 imshow就可以了