1from __future__ import print_function
2from __future__ import division
3import cv2 as cv
4import numpy as np
5import argparse
6import random as rng
7
8rng.seed(12345)
9
10def thresh_callback(val):
11    threshold = val
12
13    ## [Canny]
14    # Detect edges using Canny
15    canny_output = cv.Canny(src_gray, threshold, threshold * 2)
16    ## [Canny]
17
18    ## [findContours]
19    # Find contours
20    contours, _ = cv.findContours(canny_output, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
21    ## [findContours]
22
23    # Get the moments
24    mu = [None]*len(contours)
25    for i in range(len(contours)):
26        mu[i] = cv.moments(contours[i])
27
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))
33
34    # Draw contours
35    ## [zeroMat]
36    drawing = np.zeros((canny_output.shape[0], canny_output.shape[1], 3), dtype=np.uint8)
37    ## [zeroMat]
38    ## [forContour]
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)
43    ## [forContour]
44
45    ## [showDrawings]
46    # Show in a window
47    cv.imshow('Contours', drawing)
48    ## [showDrawings]
49
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)))
53
54## [setup]
55# Load source image
56parser = argparse.ArgumentParser(description='Code for Image Moments tutorial.')
57parser.add_argument('--input', help='Path to input image.', default='stuff.jpg')
58args = parser.parse_args()
59
60src = cv.imread(cv.samples.findFile(args.input))
61if src is None:
62    print('Could not open or find the image:', args.input)
63    exit(0)
64
65# Convert image to gray and blur it
66src_gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY)
67src_gray = cv.blur(src_gray, (3,3))
68## [setup]
69
70## [createWindow]
71# Create Window
72source_window = 'Source'
73cv.namedWindow(source_window)
74cv.imshow(source_window, src)
75## [createWindow]
76## [trackbar]
77max_thresh = 255
78thresh = 100 # initial threshold
79cv.createTrackbar('Canny Thresh:', source_window, thresh, max_thresh, thresh_callback)
80thresh_callback(thresh)
81## [trackbar]
82
83cv.waitKey()
84