def search_max_area_triangulation(self, polygon, base_first=False, quiet=True): polygon.multi_area = 0 polygon.triangulation = [] if len(polygon) <= 2: return polygon """ Is polygon known ? """ isBestSplitDone = self.search_in_optimize_done(polygon) if isBestSplitDone != None: polygon = self.optimized_polygon_done[isBestSplitDone] #print "Polygon already optimize :",polygon.triangulation, polygon.multi_area return polygon #print "Polygon not optimized :",polygon if len(polygon) == 3: triangle = Triangle(polygon.verts, self.a, exterior=True, suboptimal=self.suboptimal) triangle.findArea() triangle = self.best_area_under(triangle, quiet=False) return triangle self.polygon_max_area_triangulation(polygon, base_first=base_first, quiet=quiet) #print "Optimized polygon added : ", polygon bisect.insort_left(self.optimized_polygon_done, polygon) return polygon
def nerve(self, spheres): '''Given a set of spheres @return edges: (sphere1, sphere2) pairs @return triangle_set: triangle set @return graph_dict: dictionary{ sphere1:[sphere2, sphere3,...] } @return edge_tri_dict: dictionary{ (sphere1, sphere2): triangle, .... } @return sphere_tri_dict: dictionary{ sphere1: [triangle1, tri2...], ... }''' edges = []; triangle_set = []; graph_dict = {}; edge_tri_dict = {}; sphere_tri_dict = {} for i in range(0, len(spheres)): sphere1 = spheres[i]; for j in range(0, len(spheres)): sphere2 = spheres[j]; if not sphere1.intersects(sphere2) or sphere1 == sphere2: continue; if not (sphere1, sphere2) in edges: edges.append( (sphere1, sphere2) ); self.__add2dict__(sphere1, sphere2, graph_dict); for sphere3 in spheres: if sphere1 == sphere3 or sphere2 == sphere3: continue; if sphere1.intersects(sphere3) and sphere2.intersects(sphere3): triangle = Triangle(sphere1, sphere2, sphere3); if triangle.is_filled(): triangle_set.append(triangle); self.__add2dict__((sphere1,sphere2), triangle, edge_tri_dict); self.__add2dict__((sphere2,sphere1), triangle, edge_tri_dict); self.__add2dict__((sphere1,sphere3), triangle, edge_tri_dict); self.__add2dict__((sphere3,sphere1), triangle, edge_tri_dict); self.__add2dict__((sphere2,sphere3), triangle, edge_tri_dict); self.__add2dict__((sphere3,sphere2), triangle, edge_tri_dict); no_same_tri_set = []; same = []; for tri1 in triangle_set: if tri1 in same: continue; no_same_tri_set.append(tri1); for tri2 in triangle_set: if tri1 == tri2: continue; if tri1.spheres[0] == tri2.spheres[0] or tri1.spheres[0] == tri2.spheres[1] or tri1.spheres[0] == tri2.spheres[2]: if tri1.spheres[1] == tri2.spheres[0] or tri1.spheres[1] == tri2.spheres[1] or tri1.spheres[1] == tri2.spheres[2]: if tri1.spheres[2] == tri2.spheres[0] or tri1.spheres[2] == tri2.spheres[1] or tri1.spheres[2] == tri2.spheres[2]: #triangle_set.remove(tri2); same.append(tri2); print "initially we have {0} triangles".format(len(triangle_set)) for tri in no_same_tri_set: self.__add2dict__(tri.spheres[0], tri, sphere_tri_dict); self.__add2dict__(tri.spheres[1], tri, sphere_tri_dict); self.__add2dict__(tri.spheres[2], tri, sphere_tri_dict); return edges, no_same_tri_set, graph_dict, edge_tri_dict, sphere_tri_dict;
def Triangle_output(a, b, c): Triangle_input.Triangle_input_a(a) Triangle_input.Triangle_input_b(b) Triangle_input.Triangle_input_c(c) num = Triangle_input.num test_num = Triangle_input.test_num if compare(a) == "请输入正整数或正小数" or compare(b) == "请输入正整数或正小数" or compare( c) == "请输入正整数或正小数": # print(num) print("您输入的三个值分别为%s,%s,%s" % (a, b, c)) print("您输入的三个值不符合要求:请输入正整数或正小数") # 打印日志消息 logger().info('输入不符合正整数或正小数') return "输入值错误" else: print("您输入的三个值分别为%s,%s,%s" % (a, b, c)) print("您输入的三个值组合结果为:") result = Triangle.Triangle_PK(num['a'], num['b'], num['c']) # 打印日志消息 logger().info('判断成功返回判断结果:' + result) return result # a = input("输入组成三角形的第一个数:") # b = input("输入组成三角形的第二个数:") # c = input("输入组成三角形的第三个数:") # Triangle_output(a,b,c)
def test3(self): #Scalene test a=3 b=4 c=5 expected = "Scalene triangle" actual = Triangle.classify_triangle(a,b,c) self.assertEqual(expected, actual, "Test for Isosceles fails.")
def render(SceneLoaded, Scale, Light, CamDist, Fdist): Scene = SceneLoaded Screen = [] projection_plane = Plane(Vector(0, CamDist, 0), Vector(1, 0, 0), Vector(0, 0, 1)) focalPoint = Vector(0, CamDist + Fdist, 0) #Sort by Y value all triangles (oclusion) Scene.sort(key=lambda tri: tri.centre.y) for triangle in Scene: triangle.shade(Light) triangle.v1 = triangle.v1 * Scale triangle.v2 = triangle.v2 * Scale triangle.v3 = triangle.v3 * Scale for triangle in Scene: try: V1 = Line(triangle.v1, focalPoint - triangle.v1).plane_intersect( projection_plane) # Three lines from the vertices to the plane V2 = Line(triangle.v2, focalPoint - triangle.v2).plane_intersect( projection_plane) # V3 = Line(triangle.v3, focalPoint - triangle.v3).plane_intersect( projection_plane) # Screen.append(Triangle(V1, V2, V3, color=triangle.color)) except: pass draw(Screen)
def main(): rand_levels = input("Enter number of levels: ") # rand_levels = random.randint(2,15) t = Triangle(int(rand_levels)) # print(repr(t)) print "\nSimulated Annealing" print "###############################" anneal(t, rand_levels)
def fan_triangulation(self, perim, center, base_first=False): print "perim :", perim print "center : ", center n = len(perim) tri = [] if center in perim: arg_center = perim.index(center) #fan_perim = np.roll(perim,-arg_center) if arg_center > 1: for i in xrange(n): if (i != arg_center) and ((i + 1) % n != arg_center): tri.append( Triangle([perim[i], perim[(i + 1) % n], center], self.a, True, suboptimal=self.suboptimal)) else: if arg_center == 0: for i in xrange(1, n - 1): tri.append( Triangle( [center, perim[i % n], perim[(i + 1) % n]], self.a, True, suboptimal=self.suboptimal)) else: #arg_center == 1: for i in xrange(n - 2): tri.append( Triangle([perim[-i], center, perim[-i - 1]], self.a, True, suboptimal=self.suboptimal)) else: for i in xrange(n): tri.append( Triangle([perim[i], perim[(i + 1) % n], center], self.a, True, suboptimal=self.suboptimal)) # Test because buildgraph return false # if base_first and not (tri[0][0] in perim[0:2] and tri[0][1] in perim[0:2]): # print "reverse" # tri.reverse() print "tri :", [t.verts for t in tri] return tri
def search_max_MULTI_triangulation(self, polygon, base_first=False, quiet=True): polygon.multi_area = 0 polygon.triangulation = [] if len(polygon) <= 2: return polygon if len(polygon) == 3: triangle = Triangle(polygon.verts, self.a, exterior=True, suboptimal=self.suboptimal) triangle.findArea() triangle = self.best_multi_under(triangle, quiet=False) return triangle base_perim = self.select_base_first(polygon) candidates = [] for l in base_perim: for poly in l: sub_candidates = triangles_in_perim_sorting_by_area( self.a, poly.verts, self.suboptimal, base_first=True, quiet=quiet) sub_candidates = sub_candidates[0:self.attempts] candidates += sub_candidates attempts = len(candidates) # in case attempts > len candidates tour = 0 display_message(self.a, quiet, "Searching ...", newline=True) for triangle in candidates: triangle.verts = list(np.roll(triangle.verts, 1)) display_progression_triangle( self.a, self.a.quiet, tour, attempts, "attemps, optimized=" + str(len(self.optimized_polygon_done))) triangle = self.best_multi_under(triangle, quiet) if triangle.multi_area > polygon.multi_area: polygon.triangulation = [triangle] polygon.multi_area = triangle.multi_area tour += 1 display_progression_triangle( self.a, self.a.quiet, tour, attempts, "attemps, optimized=" + str(len(self.optimized_polygon_done))) return polygon
def CalculateColour(aTriangle): AmbColour = [0.0, 0.0, 0.0] AmbColour[R] = ambientMatR * ambientLightR AmbColour[G] = ambientMatG * ambientLightG AmbColour[B] = ambientMatB * ambientLightB DiffuseColour = [0.0, 0.0, 0.0] DiffuseFactor = Diffuse(aTriangle.normal, Triangle.AveragePoint(aTriangle)) #print(DiffuseFactor) DiffuseColour[R] = DiffuseFactor * diffuseMatR * lightSourceR DiffuseColour[G] = DiffuseFactor * diffuseMatG * lightSourceG DiffuseColour[B] = DiffuseFactor * diffuseMatB * lightSourceB #print(DiffuseColour[R],DiffuseColour[G],DiffuseColour[B]) SpecularColour = [0.0, 0.0, 0.0] SpecularFactor = Specular(aTriangle.normal, Triangle.AveragePoint(aTriangle)) #print(SpecularFactor) SpecularColour[R] = SpecularFactor * specularMatR * lightSourceR SpecularColour[G] = SpecularFactor * specularMatG * lightSourceG SpecularColour[B] = SpecularFactor * specularMatB * lightSourceB #print(SpecularColour[R],SpecularColour[G],SpecularColour[B]) endColour = [0.0, 0.0, 0.0] endColour[R] = AmbColour[R] + DiffuseColour[R] + SpecularColour[R] endColour[G] = AmbColour[G] + DiffuseColour[G] + SpecularColour[G] endColour[B] = AmbColour[B] + DiffuseColour[B] + SpecularColour[B] #if >1, clamp the values if endColour[R] > 1.0: endColour[R] = 1.0 if endColour[G] > 1.0: endColour[G] = 1.0 if endColour[B] > 1.0: endColour[B] = 1.0 return Colour.Colour(endColour[R], endColour[G], endColour[B])
class TestTriangleMethods(unittest.TestCase): a = Triangle.Triangle(3, 4, 5) b = Triangle.Triangle(0, 0, 0) c = Triangle.Triangle(3, 4, 17) d = Triangle.Triangle(3, 4, 3) e = Triangle.Triangle(3, 3, 3) f = Triangle.Triangle(3, 4, 6) def test_isTriangle(self): self.assertEqual(self.a.isTriangle(), True) self.assertEqual(self.b.isTriangle(), False) self.assertEqual(self.c.isTriangle(), False) self.assertEqual(self.d.isTriangle(), True) def test_isEquilateral(self): self.assertEqual(self.a.isEquilateral(), False) self.assertEqual(self.e.isEquilateral(), True) self.assertEqual(self.b.isEquilateral(), False) def test_isIsosceles(self): self.assertEqual(self.d.isIsosceles(), True) self.assertEqual(self.f.isIsosceles(), False) self.assertEqual(self.e.isIsosceles(), True) def test_isScalene(self): self.assertEqual(self.f.isScalene(), True) self.assertEqual(self.c.isScalene(), False) self.assertEqual(self.a.isScalene(), True)
def __init__(self, center, triangles): self.center = center self.defects = len(triangles) if self.defects == 0: pass elif self.defects == 1: self.firstFinger = triangles[0].fingerA self.lastFinger = triangles[0].fingerB elif self.defects == 2: self.firstFinger = triangles[0].fingerA self.secondFinger = th.averagePoint(triangles[0].fingerB, triangles[1].fingerA) self.lastFinger = triangles[1].fingerB elif self.defects == 3: self.firstFinger = triangles[0].fingerA self.secondFinger = th.averagePoint(triangles[0].fingerB, triangles[1].fingerA) self.middleFinger = th.averagePoint(triangles[1].fingerB, triangles[2].fingerA) self.lastFinger = triangles[2].fingerB elif self.defects == 4: self.firstFinger = triangles[0].fingerA self.secondFinger = th.averagePoint(triangles[0].fingerB, triangles[1].fingerA) self.middleFinger = th.averagePoint(triangles[1].fingerB, triangles[2].fingerA) self.fourthFinger = th.averagePoint(triangles[2].fingerB, triangles[3].fingerA) self.lastFinger = triangles[3].fingerB
def search_optimize_keys_triangulation(self, perim): #print "search_optimize_keys_triangulation:", perim best_area = 0 final_tri = [] if len(perim) <= 2: return final_tri, best_area delaunay_args, delaunay_points = self.sub_Delaunay_triangluation_in_perim( perim) #print "preferences: ",preferences #[0:attempts] for tri in delaunay_args[0:attempts]: current_tri = [] area = 0 linksGraph = self.a.to_undirected() for triangle in tri.simplices: t0 = Triangle([ delaunay_points[triangle[0]], delaunay_points[triangle[1]], delaunay_points[triangle[2]] ], self.a, True, suboptimal=self.suboptimal) links_Triangle(t0, linksGraph) t0.findContents() current_tri += [t0] for t in current_tri: #print "t0.area=", t0.area # TODO : Not always optimal triangulation # TODO : add optimal option to maxAREA_Split ? sub_area, sub_added_linked = t.maxKEY_Split(linksGraph) area += t.area + sub_area if area > best_area or True: #if best_area >0: #print "best found !" #print "Old tri :",[tri.verts for tri in final_tri]," old area =", best_area #print "New tri :",[tri.verts for tri in current_tri]," new area =", area best_area = area final_tri = current_tri return final_tri, best_area
def delone(p): p.sort(key=lambda x: x[0]) t1 = Triangle.Triangle([p[0], p[1], p[2]]) tr.append(t1) tr_arr.append(p[0]) tr_arr.append(p[1]) tr_arr.append(p[2]) is_first = False i_min = 0 i_max = 0 for i in range(len(p) - 1): if not lab1.point_left([p[i], p[i + 1]], p): if is_first: i_max = i + 1 else: is_first = True i_min = i print(i_max, i_min)
def FileRead(triangleList, fileName): f = open(fileName, "r") vertexList = [] for line in f: data = line data = data.split() if data[0] == "v": x = float(data[1]) y = float(data[2]) z = float(data[3]) point = [x, y, z, 1] vertexList.append(point) elif data[0] == "f": vec1 = vertexList[int(data[1]) - 1] vec2 = vertexList[int(data[2]) - 1] vec3 = vertexList[int(data[3]) - 1] triangleList.append(Triangle.Triangle(vec1, vec2, vec3, [1, 1, 1])) f.close() return triangleList
def main(): # This generates the triangle. print "Levels \t Dynamic Time \t Dynamic Weight \t Greedy Time \t Greedy Weight \t Simulated Annealing Time \t Simulated Annealing Weight" for levels in range(50, 5000, 50): t = Triangle(levels) start = time.clock() dynamic = algorithms.solveDynamic(t) end = time.clock() dynamicTime = end - start start = time.clock() greedy = algorithms.solveGreedy(t) end = time.clock() greedyTime = end - start start = time.clock() simWeight, simPath = simulated_anneal(t) end = time.clock() simTime = end - start # simPath = print_pretty(simPath) print("%s \t %s \t\t %s \t\t\t %s \t\t\t\t %s \t\t\t\t %s \t\t\t %s") % (levels, dynamicTime, dynamic, greedyTime, greedy, simTime, simWeight)
def drawDefects(self, image, color, internRadius, externRadius): if self.defects == 0: cv2.circle(image, th.listToTuple(self.center), internRadius, color, externRadius) elif self.defects == 1: # 2 Fingers cv2.circle(image, th.listToTuple(self.firstDefect), internRadius, color, externRadius) elif self.defects == 2: # 3 Fingers cv2.circle(image, th.listToTuple(self.center), internRadius, color, externRadius) cv2.circle(image, th.listToTuple(self.firstDefect), internRadius, color, externRadius) cv2.circle(image, th.listToTuple(self.lastDefect), internRadius, color, externRadius) elif self.defects == 3: # 4 Fingers cv2.circle(image, th.listToTuple(self.center), internRadius, color, externRadius) cv2.circle(image, th.listToTuple(self.firstDefect), internRadius, color, externRadius) cv2.circle(image, th.listToTuple(self.secondDefect), internRadius, color, externRadius) cv2.circle(image, th.listToTuple(self.lastDefect), internRadius, color, externRadius) elif self.defects == 4: # 5 Fingers cv2.circle(image, th.listToTuple(self.center), internRadius, color, externRadius) cv2.circle(image, th.listToTuple(self.firstDefect), internRadius, color, externRadius) cv2.circle(image, th.listToTuple(self.secondDefect), internRadius, color, externRadius) cv2.circle(image, th.listToTuple(self.defectMiddleFinger), internRadius, color, externRadius) cv2.circle(image, th.listToTuple(self.lastDefect), internRadius, color, externRadius)
import Line import Triangle import mathhelp print('\ttriangleLineIntesect') for i in range(0, 100000): l = Line.Line((0, 0, 0), (1, 0, 6)) t = Triangle.Triangle((-1, -1, 3), (1, -1, 3), (0, 1, 3)) mathhelp.triangleLineIntersect(t, l)
import module3 import fib import Person import Triangle # module3.foo() # fib.main() Person.main() a = int(input('a')) b = int(input('b')) c = int(input('c')) if Triangle.is_valid(a, b, c): t = Triangle(a, b, c) print(t.perimeter()) # 也可以通过给类发消息来调用对象方法但是要传入接收消息的对象作为参数 # print(Triangle.perimeter(t)) print(t.area()) # print(Triangle.area(t)) else: print('无法构成三角形.')
# -*- coding: utf-8 -*- import numpy as np import random from Triangle import * from Data_CSV_Valid import * from deap import base, creator, tools from operator import attrgetter ruleLength, dontCarePB = 12, 0.8 triangle = Triangle() dataset = LoadDataCSVValid() validatedata, validateeachClassAmout = dataset.get_validate_data() classLabel = dataset.get_classLabel() creator.create("FitnessMax", base.Fitness, weights=(1.0, )) creator.create("MichiganRule", list, fitness=creator.FitnessMax, classLabel='-1', examples=[], correctCount=0, misCount=0) toolbox = base.Toolbox() toolbox.register("rules", triangle.createRule, ruleLength, dontCarePB) toolbox.register("MichiganRule", tools.initIterate, creator.MichiganRule, toolbox.rules) toolbox.register("population", tools.initRepeat, list, toolbox.MichiganRule) # load_rules with open('selectrule_12.csv', 'r') as f: f_csv = csv.reader(f) rules = [] for row in f_csv:
getFileInput = True sideCounter = 0 triangleTemp = [[], [], []] while (getFileInput): line = f.readline() if (not line == ''): triangleList.append(line) else: getFileInput = False if (GROUPING_METHOD == 'ROW'): for triangleString in triangleList: triangleValues = triangleString.split() triangle = Triangle.Triangle(int(triangleValues[0]), int(triangleValues[1]), int(triangleValues[2])) if (triangle.isValid()): validTriangles = validTriangles + 1 elif (GROUPING_METHOD == 'COLUMN'): for triangleString in triangleList: sideCounter = sideCounter + 1 if (sideCounter > NUM_SIDES): for constructedTriangle in triangleTemp: triangle = Triangle.Triangle(constructedTriangle[0], constructedTriangle[1], constructedTriangle[2]) if (triangle.isValid()): validTriangles = validTriangles + 1 sideCounter = 1 triangleTemp = [[], [], []]
def iterativeFramePointFinder(vCoords, vIndices, d_kPoints): """ Finds registration transformation Freg between rigid body B and bone through iterative closest point finding. :param vCoords: coordinates of all vertices on mesh :param vIndices: indices of vertices for each triangle on mesh :param d_kPoints: starting positions of tip of rigid body A :type vCoords: np.array([np.float64]) 3 x N :type vIndices: np.array([np.float64]) 3 x M :type d_kPoints: pc.PointCloud :return c_kPoints: Transformed tip positions in bone coordinate system :return F_reg: Registration frame between bone and rigid body B :rtype c_kPoints: pc.PointCloud :rtype F_reg: fr.Frame """ F_reg = fr.Frame(np.identity(3), np.zeros([3, 1])) nIters = 0 triangles = [] for i in range(vIndices.shape[1]): t = tr.Triangle(pc.PointCloud(vCoords[:, vIndices[:, i]])) triangles.append(t) triangles = np.array(triangles) print('Building tree...') tree = ctn.CovTreeNode(triangles, vIndices.shape[1]) old_pts = None c_kPoints = None prev_error = collections.deque(maxlen=4) prev_error.append(0) print('\nStarting ICP:') while nIters < 40: s_i = d_kPoints.transform(F_reg) if nIters == 0: # First guess is infinity old_pts = pc.PointCloud(s_i.data + np.inf) c_kPoints = icpm.ICPmatch(s_i, vCoords, vIndices, tree=tree, oldpts=old_pts, usetree=True) # Update guess old_pts = c_kPoints deltaF_reg = s_i.register(c_kPoints) F_regNew = deltaF_reg.compose(F_reg) if isClose(.000001, F_reg, F_regNew, prev_error): return c_kPoints, F_regNew print('Iteration: ' + str(nIters) + ', error = ' + str(prev_error[-1])) F_reg = F_regNew nIters += 1 return c_kPoints, F_reg
import Triangle as tri import Square as sq import Circle as cr a = 8 b = 5 c = mul(a,b) print(c) print("For Area of Triangle") height = 8 base = 6 tria = tri.area(height,base) print(tria) print("Perimeter of Triangle") s1 = int(input("S1 value:")) s2 = int(input("S2 value:")) s3 = int(input("S3 value:")) tri1 = tri.perimeter(s1,s2,s3) print(tri1) print("Area of Square") side = int(input("Give Side of square value:")) sq1 = sq.area(side) print(sq1)
def makeTriangle(self, i, j, k, a, d, s): vi = self.vertices[i] vj = self.vertices[j] vk = self.vertices[k] return Triangle(vi.pos, vj.pos, vk.pos, vi.dir.normalize(), vj.dir.normalize(), vk.dir.normalize(), a, d, s)
#test triangle data #create a list of values triangleList = [] #read triangle data from a file triangleList = AppInfo.FileRead(triangleList, fileName) copyList = [] #transform each of the triangles by the world matrix #also, create the normals and calculate the color of lighting for t in triangleList: t = Triangle.MultiplyTriangle(t, AppInfo.worldMatrix) t = Triangle.MultiplyTriangle(t, AppInfo.viewMatrix) t.normal = Triangle.CreateTransformedNormal(t) t.colour = Lighting.CalculateColour(t) copyList.append(t) triangleList = copyList copyList = [] #get rid of unneeded triangles in the copylist for t in triangleList: #t.normal = Triangle.CreateTransformedNormal(t) if Triangle.TestForCull(t) == False: copyList.append(t) #set the triangleList to point at the new copylist
for t in triangleList: averagePt = Triangle.AveragePoint(t) if averagePt[2] < 1.0 or averagePt[2] > 0.0 : copyList.append(t) triangleList = copyList copyList = [] for t in triangleList: t.AveragePoint = Triangle.AveragePoint(t) #sort triangles by z triangleList = bubbleSortTriangles(triangleList) #draw triangles for t in triangleList: Triangle.drawTriangle(t,windowSurface,t.colour) #print(t.AveragePoint[2]) pygame.display.update() while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() IncludesAndConstants.sys.exit()
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys sys.path.append("../lib") import Triangle input=open("input.txt").read() print Triangle.solve_triangle(input)
def PerspDiv(aTriangle): aTriangle.p1 = perspectiveDivision(aTriangle.p1) aTriangle.p2 = perspectiveDivision(aTriangle.p2) aTriangle.p3 = perspectiveDivision(aTriangle.p3) return Triangle.Triangle(aTriangle.p1, aTriangle.p2, aTriangle.p3, aTriangle.colour)
# -*- coding: utf-8 -*- import numpy as np import random from Triangle import * from Data_CSV import * from deap import base, creator, tools from operator import attrgetter ruleLength, dontCarePB = 12, 0.8 CXPB, MUTPB = 0.5, 0.4 ElistPoolSize = 10 ClassNumber = 10 triangle = Triangle() dataset = LoadDataCSV() traindata, eachClassAmout = dataset.get_train_data() validatedata, validateeachClassAmout = dataset.get_validate_data() classLabel = dataset.get_classLabel() creator.create("FitnessMax", base.Fitness, weights=(1.0, )) creator.create("MichiganRule", list, fitness=creator.FitnessMax, classLabel='-1', examples=[], correctCount=0, misCount=0) toolbox = base.Toolbox() toolbox.register("rules", triangle.createRule, ruleLength, 1) toolbox.register("MichiganRule", tools.initIterate, creator.MichiganRule, toolbox.rules) toolbox.register("population", tools.initRepeat, list, toolbox.MichiganRule) toolbox.register("mate", tools.cxTwoPoint)
def TRIY(tri): return tri.centre.y SCENE.sort(key=TRIY) for triangle in SCENE: triangle.shade(LIGHT) triangle.v1=triangle.v1*scale triangle.v2=triangle.v2*scale triangle.v3=triangle.v3*scale for triangle in SCENE: try: V1=Line(triangle.v1,FOCAL_POINT-triangle.v1).plane_intersect(projection_plane)# Three lines from the vertices to the plane V2=Line(triangle.v2,FOCAL_POINT-triangle.v2).plane_intersect(projection_plane)# V3=Line(triangle.v3,FOCAL_POINT-triangle.v3).plane_intersect(projection_plane)# #print("V1 = {};\nV2 = {};\nV3 = {};\n".format(Line(triangle.v1,FOCAL_POINT-triangle.v1), # Line(triangle.v2,FOCAL_POINT-triangle.v2), # Line(triangle.v3,FOCAL_POINT-triangle.v3)) # ) SCREEN.append(Triangle(V1,V2,V3,color=triangle.color)) #print(V1,V2,V3) except: pass #print(SCREEN) dump = open("debug.txt","w+") for triangle in SCREEN: dump.write("{} \n".format(str(triangle))) draw(SCREEN) canvas.pack() tkinter.mainloop()
def drawLines(self, image, color, lineThickness): if self.defects == 0: pass elif self.defects == 1: # 2 Fingers cv2.line(image, th.listToTuple(self.firstDefect), th.listToTuple(self.firstFinger), color, lineThickness) cv2.line(image, th.listToTuple(self.firstDefect), th.listToTuple(self.lastFinger), color, lineThickness) elif self.defects == 2: # 3 Fingers cv2.line(image, th.listToTuple(self.firstDefect), th.listToTuple(self.firstFinger), color, lineThickness) cv2.line(image, th.listToTuple(self.firstDefect), th.listToTuple(self.secondFinger), color, lineThickness) cv2.line(image, th.listToTuple(self.lastDefect), th.listToTuple(self.secondFinger), color, lineThickness) cv2.line(image, th.listToTuple(self.lastDefect), th.listToTuple(self.lastFinger), color, lineThickness) elif self.defects == 3: # 4 Fingers cv2.line(image, th.listToTuple(self.firstDefect), th.listToTuple(self.firstFinger), color, lineThickness) cv2.line(image, th.listToTuple(self.firstDefect), th.listToTuple(self.secondFinger), color, lineThickness) cv2.line(image, th.listToTuple(self.secondDefect), th.listToTuple(self.secondFinger), color, lineThickness) cv2.line(image, th.listToTuple(self.secondDefect), th.listToTuple(self.middleFinger), color, lineThickness) cv2.line(image, th.listToTuple(self.lastDefect), th.listToTuple(self.middleFinger), color, lineThickness) cv2.line(image, th.listToTuple(self.lastDefect), th.listToTuple(self.lastFinger), color, lineThickness) elif self.defects == 4: # 5 Fingers cv2.line(image, th.listToTuple(self.firstDefect), th.listToTuple(self.firstFinger), color, lineThickness) cv2.line(image, th.listToTuple(self.firstDefect), th.listToTuple(self.secondFinger), color, lineThickness) cv2.line(image, th.listToTuple(self.secondDefect), th.listToTuple(self.secondFinger), color, lineThickness) cv2.line(image, th.listToTuple(self.secondDefect), th.listToTuple(self.middleFinger), color, lineThickness) cv2.line(image, th.listToTuple(self.defectMiddleFinger), th.listToTuple(self.middleFinger), color, lineThickness) cv2.line(image, th.listToTuple(self.defectMiddleFinger), th.listToTuple(self.fourthFinger), color, lineThickness) cv2.line(image, th.listToTuple(self.lastDefect), th.listToTuple(self.fourthFinger), color, lineThickness) cv2.line(image, th.listToTuple(self.lastDefect), th.listToTuple(self.lastFinger), color, lineThickness)
def imageProcessing(self): self.hand.resetModel() ret, im = self.camera.read() im = cv2.flip(im, 1) self.imOrig = im.copy() self.imNoFilters = im.copy() # Bluring im = cv2.blur(im, (self.settings["smooth"], self.settings["smooth"])) # Filtering the hand (Skin color) filter_ = self.filterSkin(im) # Erosion filter_ = cv2.erode( filter_, cv2.getStructuringElement( cv2.MORPH_ELLIPSE, (self.settings["erode"], self.settings["erode"]))) # Dilation filter_ = cv2.dilate( filter_, cv2.getStructuringElement( cv2.MORPH_ELLIPSE, (self.settings["dilate"], self.settings["dilate"]))) # Recognition of contours contours, hierarchy = cv2.findContours(filter_, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE) # Filtering the contours allIdex = [] for index in range(len(contours)): area = cv2.contourArea(contours[index]) if area < self.settings['minArea']: allIdex.append(index) allIdex.sort(reverse=True) for index in allIdex: contours.pop(index) self.hand.contours = contours # No contours if len(contours) == 0: return # Getting Information of contours allIdex = [] index_ = 0 for cnt in contours: tempIm = im.copy() tempIm = cv2.subtract(tempIm, im) # Detect fingers hull = cv2.convexHull(cnt) self.last = None self.Data["hulls"] = 0 for hu in hull: if self.last == None: fingerPoint = tuple(hu[0]) self.hand.fingers.append(fingerPoint) else: distance = mh.distance(self.last, tuple(hu[0])) if distance > 40: # Filtering Points self.Data["hulls"] += 1 fingerPoint = tuple(hu[0]) self.hand.fingers.append(fingerPoint) self.last = tuple(hu[0]) # Calculate the center of the hand M = cv2.moments(cnt) centroid_x = int(M['m10'] / M['m00']) centroid_y = int(M['m01'] / M['m00']) self.hand.centerOfHand = (centroid_x, centroid_y) # Calculate the defects (space between the fingers) hull = cv2.convexHull(cnt, returnPoints=False) angles = [] defects = cv2.convexityDefects(cnt, hull) if defects == None: return # Generate the triangle, defect and angle list for i in range(defects.shape[0]): s, e, f, d = defects[i, 0] if d > 1000: start = tuple(cnt[s][0]) end = tuple(cnt[e][0]) far = tuple(cnt[f][0]) triangle = tr.Triangle(far, start, end) self.hand.triangles.append(triangle) self.hand.defects.append(far) self.hand.angles.append(triangle.angle()) self.Data["defects"] = len(self.hand.defects) # Calculate the number of fingers anglesLess90 = filter(lambda a: a < 90, self.hand.angles) self.Data["angles less 90"] = len(anglesLess90) self.Data["fingers"] = len(anglesLess90) + 1 self.Data["fingers history"].append(len(anglesLess90) + 1) self.hand.draw(tempIm, ch.colorSettings, 1, mh.radious) if len(self.Data["fingers history"]) > 10: self.Data["fingers history"].pop(0) self.imOrig = cv2.add(self.imOrig, tempIm) index_ += 1 # Show the information if self.debugMode: yPos = 10 pos = 20 addText(self.imOrig, ("Angles less 90: " + str(self.Data["angles less 90"])), (yPos, pos)) pos += 20 addText(self.imOrig, ("Hulls: " + str(self.Data["hulls"])), (yPos, pos)) pos += 20 addText(self.imOrig, ("Defects: " + str(self.Data["defects"])), (yPos, pos)) pos += 20 addText(self.imOrig, ("Fingers: " + str(self.Data["fingers"])), (yPos, pos)) pos += 20 addText(self.imOrig, ("Fingers history: " + str(self.Data["fingers history"])), (yPos, pos)) # Show the results cv2.imshow("HSB - Computational geometry - Lattke & Mindelis", self.imOrig)
pygame.init() window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT), 0, 32) clock = pygame.time.Clock() shapesList = [] shapeTypesTuple = ('square', 'rectangle', 'circle', 'triangle') for i in range(0, N_SHAPES): thisType = random.choice(shapeTypesTuple) if thisType == 'square': oShape = Square(window) elif thisType == 'rectangle': oShape = Rectangle(window) elif thisType == 'circle': oShape = Circle(window) else: # must be triangle oShape = Triangle(window) shapesList.append(oShape) statusLine = pygwidgets.DisplayText(window, (4,4), \ 'Click on shapes', fontSize=28) # main loop while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() if event.type == MOUSEBUTTONDOWN: for oShape in shapesList: if oShape.clickedInside(event.pos):
#Chapter 7 - Exercise #5 #inherit.py #.py is a Python file #Save the three class files then start a new Python script by #making features of both derived classes available from Rectangle import * from Triangle import * #Next, create an instance of each derived class rect = Rectangle() trey = Triangle() #Now, call the class method inherited from the base class, #passing arguments to assign to the class variables rect.set_values(4, 5) trey.set_values(4, 5) #Finally, display the result of manipulating the class #variables inherited from the base class print('Rectangle Area:', rect.area()) print('Triangle Area:', trey.area())
from Rectangle import * from Triangle import * rect = Rectangle() trey = Triangle() rect.set_values( 4 , 5 ) trey.set_values( 4 , 5 ) print( 'Rectangle Area:' , rect.area() ) print( 'Triangle Area:' , trey.area() )