1 from __future__ import print_function
2 from __future__ import division
10 def thresh_callback(val):
14 # Detect edges using Canny
15 canny_output = cv.Canny(src_gray, threshold, threshold * 2)
20 _, contours, _ = cv.findContours(canny_output, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
24 mu = [None]*len(contours)
25 for i in range(len(contours)):
26 mu[i] = cv.moments(contours[i])
28 # Get the mass centers
29 mc = [None]*len(contours)
30 for i in range(len(contours)):
31 # add 1e-5 to avoid division by zero
32 mc[i] = (mu[i]['m10'] / (mu[i]['m00'] + 1e-5), mu[i]['m01'] / (mu[i]['m00'] + 1e-5))
36 drawing = np.zeros((canny_output.shape[0], canny_output.shape[1], 3), dtype=np.uint8)
39 for i in range(len(contours)):
40 color = (rng.randint(0,256), rng.randint(0,256), rng.randint(0,256))
41 cv.drawContours(drawing, contours, i, color, 2)
42 cv.circle(drawing, (int(mc[i][0]), int(mc[i][1])), 4, color, -1)
47 cv.imshow('Contours', drawing)
50 # Calculate the area with the moments 00 and compare with the result of the OpenCV function
51 for i in range(len(contours)):
52 print(' * Contour[%d] - Area (M_00) = %.2f - Area OpenCV: %.2f - Length: %.2f' % (i, mu[i]['m00'], cv.contourArea(contours[i]), cv.arcLength(contours[i], True)))
56 parser = argparse.ArgumentParser(description='Code for Image Moments tutorial.')
57 parser.add_argument('--input', help='Path to input image.', default='stuff.jpg')
58 args = parser.parse_args()
60 src = cv.imread(cv.samples.findFile(args.input))
62 print('Could not open or find the image:', args.input)
65 # Convert image to gray and blur it
66 src_gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY)
67 src_gray = cv.blur(src_gray, (3,3))
72 source_window = 'Source'
73 cv.namedWindow(source_window)
74 cv.imshow(source_window, src)
78 thresh = 100 # initial threshold
79 cv.createTrackbar('Canny Thresh:', source_window, thresh, max_thresh, thresh_callback)
80 thresh_callback(thresh)