SMIL  0.8
 All Classes Functions Variables Groups Pages
inertia_moments.py

1 from smilPython import *
2 from math import *
3 
4 # Load an image
5 imIn = Image("http://cmm.ensmp.fr/~faessel/smil/images/tools.png")
6 imIn.show()
7 
8 imThr = Image(imIn)
9 topHat(imIn, imThr, hSE(20))
10 threshold(imThr, imThr)
11 
12 imLbl = Image(imIn, "UINT16")
13 label(imThr, imLbl)
14 imLbl.showLabel()
15 
16 def fitRectangle(mat):
17  m00, m10, m01, m11, m20, m02 = mat
18 
19  if m00==0:
20  return 0, 0, 0, 0, 0
21 
22  # COM
23  xc = int (m10/m00)
24  yc = int (m01/m00)
25 
26  # centered matrix (central moments)
27  u00 = m00
28  u20 = m20 - m10**2/m00
29  u02 = m02 - m01**2/m00
30  u11 = m11 - m10*m01/m00
31 
32  # eigen values
33  delta = 4*u11**2 + (u20-u02)**2
34  I1 = (u20+u02+sqrt(delta))/2
35  I2 = (u20+u02-sqrt(delta))/2
36 
37  theta = 0.5 * atan2(-2*u11, (u20-u02))
38 
39  # Equivalent rectangle
40  # I1 = a**2*S/12, I2 = b**2*S/12
41  a = int (sqrt(12*I1/u00))
42  b = int (sqrt(12*I2/u00))
43 
44  return xc, yc, a, b, theta
45 
46 
47 # Compute Blobs
48 blobs = computeBlobs(imLbl)
49 
50 
51 # Compute Inertia Matrices
52 
53 mats = measInertiaMatrices(imIn, blobs)
54 bboxes = measBoundBoxes(imLbl)
55 
56 imDraw = Image(imIn)
57 
58 print("Label\tA\tB\tTheta")
59 for b in blobs.keys():
60  mat = xc, yc, A, B, theta = fitRectangle(mats[b])
61  print(str(b) + "\t" + str(A) + "\t" + str(B) + "\t" + str(theta))
62  dx = A/2*cos(pi-theta)
63  dy = A/2*sin(pi-theta)
64  drawLine(imDraw, int(xc-dx), int(yc-dy), int(xc+dx), int(yc+dy), b)
65  dx = B/2*sin(theta)
66  dy = B/2*cos(theta)
67  drawLine(imDraw, int(xc-dx), int(yc-dy), int(xc+dx), int(yc+dy), b)
68 imIn.getViewer().drawOverlay(imDraw)