import numpy as np
import cv2
if __name__ == '__main__':
import sys
try: fn = sys.argv[1]
except: fn = 'E:\\1.BMP'
print __doc__
global m #全局变量
def callback(*argv):
m=cv2.getTrackbarPos('select', 'forshow')
forshow=np.zeros((h,w,3),np.uint8)#cv2接口创建矩阵
cv2.drawContours( forshow, contours0,m, (0,0,255), 1, cv2.CV_AA, hierarchy,3 )#m为所描绘的轮廓 m = hierarchy[idx][0]
cv2.imshow('forshow',forshow)
img = cv2.imread(fn, 2)
h,w=img.shape[0:2]
contours0, hierarchy = cv2.findContours( img.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)#参数分别为src,mode,method
#CV_RETR_TREE 即所有轮廓 CV_RETR_EXTERNAL 外部轮廓
#CV_CHAIN_APPROX_SIMPLE 只留下脚点 CV_CHAIN_APPROX_NONE 所有点
forshow=np.zeros((h,w,3), np.uint8)
cv2.namedWindow('forshow')
cv2.createTrackbar('select', 'forshow', 0, 20, callback)#设置回调
m=cv2.getTrackbarPos('select', 'forshow')
cv2.drawContours( forshow, contours0,m, (0,0,255), 1, cv2.CV_AA, hierarchy,3 ) #m为所描绘的轮廓 m = hierarchy[idx][0]
cv2.imshow('forshow',forshow)
print hierarchy
while True:
ch = 0xFF & cv2.waitKey(0)
if ch == 27:
break
cv2.destroyAllWindows()
通过回调函数callback来改变golba m的值,从而描绘我们所需要的轮廓