SMIL 1.1.2
Loading...
Searching...
No Matches
inertia_moments.py
1from smilPython import *
2from math import *
3
4# Load an image
5imIn = Image("https://smil.cmm.minesparis.psl.eu/images/tools.png")
6imIn.show()
7
8imThr = Image(imIn)
9topHat(imIn, imThr, hSE(20))
10threshold(imThr, imThr)
11
12imLbl = Image(imIn, "UINT16")
13label(imThr, imLbl)
14imLbl.showLabel()
15
16def 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# Compute Blobs
47blobs = computeBlobs(imLbl)
48
49# Compute Inertia Matrices
50
51mats = blobsMoments(imIn, blobs)
52bboxes = blobsBoundBox(imLbl)
53imDraw = Image(imIn)
54
55print("{:5s} {:>5s} {:>5s} {:>6s}".format("Label", "A", "B", "Theta"))
56for b in blobs.keys():
57 mat = xc, yc, A, B, theta = fitRectangle(mats[b])
58 #print(str(b) + "\t" + str(A) + "\t" + str(B) + "\t" + str(theta))
59 print(f"{b:5d} {A:>5d} {B:>5d} {theta:6.3f}")
60 dx = A / 2 * cos(pi - theta)
61 dy = A / 2 * sin(pi - theta)
62 drawLine(imDraw, int(xc - dx), int(yc - dy), int(xc + dx), int(yc + dy), b)
63 dx = B / 2 * sin(theta)
64 dy = B / 2 * cos(theta)
65 drawLine(imDraw, int(xc - dx), int(yc - dy), int(xc + dx), int(yc + dy), b)
66
67
68print("on Overlay")
69imIn.getViewer().drawOverlay(imDraw)
70
71print("after overlay")
72input()
73