def _predict_one(self, index, new_corners): ''' predict position of corner index @param index: @param new_corners: ''' # predicting by taking vectors form near corners along the sides # and solving linear equation for intersection L = len(new_corners) nb = (index + 1) % L b = new_corners[nb] nd = (index - 1 + L) % L d = new_corners[nd] assert isinstance(b, Corner) v1 = b.get_prediction_vector(True, self.corners[nb]) v2 = d.get_prediction_vector(False, self.corners[nd]) p1 = b.p p2 = d.p (p, _) = solve_linear(v1, v2, p1, p2) point = add(b.p, v1, p) cor = Corner([d.p, point, b.p], imgtime=b.time) cor.compute_change(self.corners[index]) cor.is_predicted = True if cor.similarity < self.avg_sim * 2: new_corners[index] = cor
def test_get_prediction_vector(self): points = [(1, 5), (3, 0), (5, 6)] v1 = vector(points[1], points[0]) v2 = vector(points[1], points[2]) angle = vectorAngle(v1, v2) c = Corner(points, 1, imgtime=1) c1 = Corner(points, 1, imgtime=1) ans = c.get_prediction_vector(True, c1) self.assertAlmostEqual(ans[0], v1[0], 6) self.assertAlmostEqual(ans[1], v1[1], 6) ans = c.get_prediction_vector(False, c1) self.assertAlmostEqual(ans[0], v2[0], 6) self.assertAlmostEqual(ans[1], v2[1], 6)
def test_get_prediction_vector(self): points = [(1,5),(3,0),(5,6)] v1 = vector(points[1],points[0]) v2 = vector(points[1],points[2]) angle = vectorAngle(v1,v2) c= Corner(points,1,imgtime=1) c1= Corner(points,1,imgtime=1) ans= c.get_prediction_vector(True, c1) self.assertAlmostEqual(ans[0],v1[0],6) self.assertAlmostEqual(ans[1],v1[1],6) ans= c.get_prediction_vector(False, c1) self.assertAlmostEqual(ans[0],v2[0],6) self.assertAlmostEqual(ans[1],v2[1],6)
def test_append_candidates(self): c = Corner([(0,0),(0,1),(1,1)], 1, (0,0),imgtime=1) conts = [(1,1),(2,2),(3,2),(2,3)] data=[conts,list(reversed(conts)),\ list(reversed(conts[2:]+conts[:2])),\ conts[2:]+conts[:2]] cr= (0,0,5,6) for i in range(4): result = [] c._append_candidates_from_conts(cr, result, data[i],0) self.assertTrue(len(result)==1,result) cor = result[0] self.assertTrue(cor.p==(2,3) and cor.prev==(3,2),(cor.p,cor.prev))
def test_append_candidates(self): c = Corner([(0, 0), (0, 1), (1, 1)], 1, (0, 0), imgtime=1) conts = [(1, 1), (2, 2), (3, 2), (2, 3)] data=[conts,list(reversed(conts)),\ list(reversed(conts[2:]+conts[:2])),\ conts[2:]+conts[:2]] cr = (0, 0, 5, 6) for i in range(4): result = [] c._append_candidates_from_conts(cr, result, data[i], 0) self.assertTrue(len(result) == 1, result) cor = result[0] self.assertTrue(cor.p == (2, 3) and cor.prev == (3, 2), (cor.p, cor.prev))
def _predict_neighbours(self, a, b, new_corners): if a == b + 1 or (b == 3 and a == 0): a, b = b, a na = (a + 3) % 4 v1 = new_corners[na].get_prediction_vector(False, self.corners[na]) nb = (b + 1) % 4 v2 = new_corners[nb].get_prediction_vector(True, self.corners[nb]) ap = add(new_corners[na].p, v1) bp = add(new_corners[nb].p, v2) cor_a = Corner([new_corners[na].p, ap, bp], 1, imgtime=new_corners[na].time) cor_b = Corner([ap, bp, new_corners[nb].p], 1, imgtime=new_corners[na].time) cor_b.is_predicted = cor_a.is_predicted = True cor_a.compute_change(self.corners[a], self.image) cor_b.compute_change(self.corners[b], self.image) if cor_a.different: if cor_b.different: return else: new_corners[b] = cor_b self._predict_one(a, new_corners) else: new_corners[a] = cor_a if cor_b.different: self._predict_one(b, new_corners) else: new_corners[b] = cor_b
def _predict_from_one(self, a, new_corners): vec = new_corners[a].get_prediction_vector(True, self.corners[a]) pa = (a + 3) % 4 p1 = add(new_corners[a].p, vec) vec = (-vec[0],-vec[1]) vec=rotateVec(vec, self.corners[pa].angle) pp1= add(p1,vec) cor_p = Corner([pp1, p1, new_corners[a].p], 1, imgtime=new_corners[a].time) vec = new_corners[a].get_prediction_vector(False, self.corners[a]) na = (a + 1) % 4 p2 = add(new_corners[a].p, vec) vec = (-vec[0],-vec[1]) vec=rotateVec(vec, self.corners[na].angle) np2= add(p1,vec) cor_n = Corner([new_corners[a].p, p2, np2], 1, imgtime=new_corners[a].time) cor_p.is_predicted = cor_n.is_predicted = True cor_p.compute_change(self.corners[pa], self.image) cor_n.compute_change(self.corners[na], self.image) da= (a + 2) % 4 if cor_p.different: if cor_n.different: return else: new_corners[na] = cor_n self._predict_neighbours(pa, da, new_corners) else: new_corners[pa] = cor_p if cor_n.different: self._predict_neighbours(na, da, new_corners) else: new_corners[na] = cor_n self._predict_one(da, new_corners)
def setUp(self): size = 100 offset = 20 so = size - offset angle = 45 move = (0, 0) scale = 0.5 center = (size / 2, size / 2) time = 1 points = [(offset, offset), (so, offset), (so, so), (offset, so)] img = cv.CreateImage((size, size), 8, 1) cv.SetZero(img) points = rotate_points(points, center, angle) corners = [Corner(points, 0), Corner(points, 1), Corner(points, 2), Corner(points, 3)] npoints = rotate_points(points, center, 3) npoints = map(lambda x:add((2, 2), int_point(x)), npoints) npoints = standarize_contours(npoints) ncorners = [Corner(npoints, 0,imgtime=1), Corner(npoints, 1,imgtime=1), Corner(npoints, 2,imgtime=1), Corner(npoints, 3,imgtime=1)] for i, cor in enumerate(ncorners): cor.compute_change(corners[i]) self.points = npoints self.old_corners = corners self.corners = ncorners self.size = size cv.AddS(img, 255, img) self.draw_img = img self.timg = cv.CloneImage(img) self.tmp_img = cv.CloneImage(img) pass
def getDuplicateSwayze(self): query = """ select url, count(*) from swayze group by url having count(*) > 1 """ corner = Corner() corner.cur.execute(query)
def stats(points): global prop_max, prop_min, angle_max, angle_min, rot_max, angle_diff_max, angle_diff_min a = length(vector(points[0], points[1])) b = length(vector(points[1], points[2])) c = length(vector(points[2], points[3])) d = length(vector(points[3], points[0])) if a > c: a, c = c, a if b > d: b, d = d, b if c == 0.0: pass else: # print "sides a/c:", a/c if (c - a) / c > prop_max: prop_max = (c - a) / c if (c - a) / c < prop_min: prop_min = (c - a) / c if d == 0.0: pass else: # print "sides b/d", b/d if (d - b) / d > prop_max: prop_max = (d - b) / d if (d - b) / d < prop_min: prop_min = (d - b) / d corners = Corner.get_corners(points) for cor in corners: if cor.angle < angle_min: angle_min = cor.angle if cor.angle > angle_max: angle_max = cor.angle if cor.rotation > rot_max: rot_max = cor.rotation a, b, c, d = [c.angle for c in corners] if a > c: a, c = c, a if b > d: b, d = d, b if (c - a) / c > angle_diff_max: angle_diff_max = (c - a) / c if (c - a) / c < angle_diff_min: angle_diff_min = (c - a) / c # print "angle diff a/c", (c-a)/c if (d - b) / d > angle_diff_max: angle_diff_max = (d - b) / d if (d - b) / d < angle_diff_min: angle_diff_min = (d - b) / d # print "angle diff b/d", (d-b)/d if angle_diff_max > 0.90: pass
def setup_corners(self): self.corners = [] for row in range(self.max_row + 1): for column in range(self.max_col + 1): lines = [] if column > 0: lines.append(self.horizontal_walls[row][column - 1]) if row > 0: lines.append(self.vertical_walls[row - 1][column]) if column < self.max_col: lines.append(self.horizontal_walls[row][column]) if row < self.max_row: lines.append(self.vertical_walls[row][column]) self.corners.append(Corner(row, column, lines))
def _light_block(self, x, y, ox=0, oy=0, intensity=ubyte(255), is_corner=False, iteration=0): """ Recursive light function x, y - position ox, oy - offset by x and y intensity - light instensity from 0 to 255 is_corner - is this a top-left, top-right, bottom-left or bottom-right corner of a light layer iteration - iteration number to avoid endless recursion """ if iteration >= LIGHT_RADIUS or intensity < 26: raise Exception # Out of light range x += ox y += oy self.world.set_light(x, y, intensity) dropoff = 0.55 if self.world.get_light_source( self.world.get_block(x, y)) == 0 else 0.99 #dropoff = self.world.blocks_data.get(getblock(x, y), {}).get('light_dropoff') if (ox != 0 or oy != 0) and is_corner: # One of corners for offset in corner_iters[Corner((ox, oy))]: self._light_offset(x, y, offset, dropoff, intensity, iteration, is_corner and all(offset)) elif ox != 0 or oy != 0: # One of sides self._light_offset(x, y, (ox, oy), dropoff, intensity, iteration) else: # Initial point for corner in CORNERS: for offset in corner_iters[corner]: self._light_offset(x, y, offset, dropoff, intensity, iteration, True) for side in SIDES: for offset in corner_iters[side]: self._light_offset(x, y, offset, dropoff, intensity, iteration)
def make_graph(self): for h_line in self.horizon_lines: coeff_x, coeff_y, bias = h_line.eq for v_line in self.vertical_lines: cx, cy, b = v_line.eq A = np.array([[coeff_x, coeff_y], [cx, cy]]) B = np.array([bias, b]) root = Corner(np.linalg.solve(A, B).astype(int)) h_line.corners.append(root) v_line.corners.append(root) self.corners.append(root) for line in self.lines: line.line_link() self.walker = Walker(self.corners)
def _prepare_corners(self, npoints): L = len(npoints) ncorners = [] for i, point in enumerate(npoints): prev = vector(point, npoints[(i - 1 + L) % L]) next = vector(point, npoints[(i + 1) % L]) #prev= add(point,prev,3.0/random.randint(3,int(length(prev)))) #next = add(point,next, 3.0/random.randint(3,int(length(next)))) #prev=(int(prev[0])+random.randint(-1,1),int(prev[1])+random.randint(-1,1)) #next = (int(next[0]+random.randint(-1,1)),int(next[1])+random.randint(-1,1)) prev = add(point, prev, 0.3) next = add(point, next, 0.3) prev = (int(prev[0]), int(prev[1])) next = (int(next[0]), int(next[1])) ncorners.append(Corner([prev, point, next], 1,imgtime=2)) return ncorners
def _unlight_block(self, x, y, ix, iy, unlit_blocks, ox=0, oy=0, is_corner=False): """ Recursive light deletion function x, y - position ix, iy - initial position unlit_blocks - list of blocks which light was deleted (to relight them) ox, oy - offset by x and y is_corner - is this a top-left, top-right, bottom-left or bottom-right corner of a light layer """ if (abs(x - ix) >= LIGHT_RADIUS or abs(y - iy) >= LIGHT_RADIUS or (x, y) in unlit_blocks): raise Exception if (ox != 0 or oy != 0) and is_corner: # One of corners for offset in corner_iters[Corner((ox, oy))]: self._unlight_offset(x, y, ix, iy, offset, unlit_blocks, is_corner and all(offset)) elif ox != 0 or oy != 0: # One of sides self._unlight_offset(x, y, ix, iy, (ox, oy), unlit_blocks) else: # Initial point for corner in CORNERS: for offset in corner_iters[corner]: self._unlight_offset(x, y, ix, iy, offset, unlit_blocks, True) for side in SIDES: for offset in corner_iters[side]: self._unlight_offset(x, y, ix, iy, offset, unlit_blocks) #""" self.world.set_light(x, y, 0) unlit_blocks.add((x, y))
def _predict(self,npoints): cv.FillConvexPoly(self.draw_img, npoints, (0,0,0)) corners = Corner.get_corners(npoints) tcorners = list(corners) for i,cor in enumerate(corners): print cor.p if not(0<=cor.p[0]<self.size and 0<=cor.p[1]<self.size): tcorners[i]=None CP = CornerPredictor(self.corners, 1, self.tmp_img, self.timg, self.draw_img) print "predicting....",tcorners ncorners = CP.predict_corners(tcorners) print 'done' for i,cor in enumerate(ncorners): v=vector(corners[i].p,cor.p) print length(v), cor.toString() self.assertTrue(length(v)<5,"Wrong prediction!Corner: %d \ Expected: (%d,%d) received (%d,%d)" \ %(i,corners[i].p[0],corners[i].p[1],cor.p[0],cor.p[1])) print ncorners
def test_validate_corners(self): print self.corners print self.old_corners ncorners = self._prepare_corners(self.points) c= ncorners[0] prev = add(c.prev,(2,0)) p = add(c.p,(1,1)) next= add(c.next,(2,0)) ncorners[0] = Corner([prev,p,next],1,imgtime=2) ncorners[0].compute_change(self.corners[0]) res = list(ncorners) res[0]=None print ncorners for i,cor in enumerate(ncorners): cor.draw(self.draw_img) cor.compute_change(self.corners[i]) db.show(self.draw_img,"main") CP = CornerPredictor(self.corners, 1, self.tmp_img, self.timg, self.draw_img) CP.validate_corners(ncorners) self.assertEqual(ncorners,res, "First corner is invalid:"+ncorners.__repr__())
def stats(points): global prop_max, prop_min, angle_max, angle_min, rot_max, angle_diff_max, angle_diff_min a = length(vector(points[0], points[1])) b = length(vector(points[1], points[2])) c = length(vector(points[2], points[3])) d = length(vector(points[3], points[0])) if a > c: a, c = c, a if b > d: b, d = d, b if c == 0.0: pass else: #print "sides a/c:", a/c if (c - a) / c > prop_max: prop_max = (c - a) / c if (c - a) / c < prop_min: prop_min = (c - a) / c if d == 0.0: pass else: #print "sides b/d", b/d if (d - b) / d > prop_max: prop_max = (d - b) / d if (d - b) / d < prop_min: prop_min = (d - b) / d corners = Corner.get_corners(points) for cor in corners: if cor.angle < angle_min: angle_min = cor.angle if cor.angle > angle_max: angle_max = cor.angle if cor.rotation > rot_max: rot_max = cor.rotation a, b, c, d = [c.angle for c in corners] if a > c: a, c = c, a if b > d: b, d = d, b if (c - a) / c > angle_diff_max: angle_diff_max = (c - a) / c if (c - a) / c < angle_diff_min: angle_diff_min = (c - a) / c #print "angle diff a/c", (c-a)/c if (d - b) / d > angle_diff_max: angle_diff_max = (d - b) / d if (d - b) / d < angle_diff_min: angle_diff_min = (d - b) / d #print "angle diff b/d", (d-b)/d if angle_diff_max > 0.90: pass
def set_new_position(self, points_or_corners, offset=True, scale=1): ''' Sets new position for this marker using points (in order) @param points_or_corners: list of points or corners @param offset: if true, image ROI is checked and points are shifted ''' if len(points_or_corners) > 0 and type(points_or_corners[0]) == tuple: self.predicted = -1 points = points_or_corners img = self.m_d.img (x, y, _, _) = rect = cv.GetImageROI(img) if offset and (x, y) <> (0, 0): points = map(lambda z: add((x, y), z), points) cv.ResetImageROI(img) crit = (cv.CV_TERMCRIT_EPS + cv.CV_TERMCRIT_ITER, 30, 0.1) if (scale > 1): points = cv.FindCornerSubPix(self.m_d.gray_img, points, (scale * 2 + 4, scale * 2 + 4), (-1, -1), crit) else: points = cv.FindCornerSubPix(self.m_d.gray_img, points, (3, 3), (-1, -1), crit) ncorners = Corner.get_corners(points, self.m_d.time) if len(self.corners) <> 0: for i, cor in enumerate(ncorners): cor.compute_change(self.corners[i]) cv.SetImageROI(img, rect) else: ncorners = points_or_corners self.predicted += len(filter(lambda x: x.is_predicted, ncorners)) for i, c in enumerate(ncorners): c.black_inside = self.black_inside # if len(self.corners)==4: # if dist_points(c.p, self.corners[i].p)<4: # c.p=self.corners[i].p self.corners = ncorners self.area = abs(cv.ContourArea(self.points)) self.last_seen = self.m_d.time self.model_view = None
def set_new_position(self, points_or_corners, offset=True, scale=1): ''' Sets new position for this marker using points (in order) @param points_or_corners: list of points or corners @param offset: if true, image ROI is checked and points are shifted ''' if len(points_or_corners) > 0 and type(points_or_corners[0]) == tuple: self.predicted = -1 points = points_or_corners img = self.m_d.img (x, y, _, _) = rect = cv.GetImageROI(img) if offset and (x, y) <> (0, 0): points = map(lambda z: add((x, y), z), points) cv.ResetImageROI(img) crit = (cv.CV_TERMCRIT_EPS + cv.CV_TERMCRIT_ITER, 30, 0.1) if (scale > 1): points = cv.FindCornerSubPix(self.m_d.gray_img, points, (scale * 2 + 4, scale * 2 + 4), (-1, -1), crit) else: points = cv.FindCornerSubPix(self.m_d.gray_img, points, (3, 3), (-1, -1), crit) ncorners = Corner.get_corners(points, self.m_d.time) if len(self.corners) <> 0: for i, cor in enumerate(ncorners): cor.compute_change(self.corners[i]) cv.SetImageROI(img, rect) else: ncorners = points_or_corners self.predicted += len(filter(lambda x:x.is_predicted, ncorners)) for i,c in enumerate(ncorners): c.black_inside=self.black_inside # if len(self.corners)==4: # if dist_points(c.p, self.corners[i].p)<4: # c.p=self.corners[i].p self.corners = ncorners self.area = abs(cv.ContourArea(self.points)) self.last_seen = self.m_d.time self.model_view = None
def getRandSwayzeColors(self): # return ['http://home.comcast.net/~patrick.swayze/patrickcloseup.jpg', "#123456", "#223344", "445566"] corner = Corner() query = """ SELECT swayze_id FROM colors WHERE fake = 0 ORDER BY RAND() LIMIT 1 """ corner.cur.execute(query) for row in corner.cur: swayze_id = row[0] query = "SELECT swayze.url, colors.color FROM swayze INNER JOIN colors ON swayze.id = colors.swayze_id WHERE swayze_id = " + str( swayze_id) corner.cur.execute(query) colors = [] for row in corner.cur: url = row[0] colors.append(row[1]) return [url, colors]
#!/usr/bin/env python from SwayzeBaby import SwayzeBaby from corner import Corner import urllib swayze = SwayzeBaby() corner = Corner() swaykeys = ["", "Skatetown, U.S.A.", "The Outsiders","Uncommon Valor","Grandview, U.S.A. ","Red Dawn ","Youngblood ","Dirty Dancing ","Steel Dawn ","Tiger Warsaw ","Road House ","Next of Kin ","Ghost ","Point Break ","City of Joy ","Father Hood ","Tall Tale ","To Wong Foo Thanks for Everything, Julie Newmar ","Three Wishes ","Black Dog ","Letters from a Killer ","Forever Lulu ","Green Dragon ","Donnie Darko ","Waking Up in Reno ","One Last Dance ","11:14 ","Dirty Dancing: Havana Nights ","Keeping Mum ","The Fox and the Hound 2 ","Jump! ","Christmas in Wonderland ","Powder Blue "] # swaykeys = ["Letters from a Killer ","Forever Lulu ","Green Dragon ","Donnie Darko ","Waking Up in Reno ","One Last Dance ","11:14 ","Dirty Dancing: Havana Nights ","Keeping Mum ","The Fox and the Hound 2 ","Jump! ","Christmas in Wonderland ","Powder Blue "] # swaykeys = [""] for keyword in swaykeys: query = "swayze " + keyword results = swayze.fetchAllSwayze(query) for key, value in results.iteritems(): url = key title = value # url = urllib.unquote(url) try: title = urllib.unquote(title) title = title.encode('ascii', 'ignore') title = title.replace('"', '\\"') title = title.replace("'", "\\'") query = "INSERT INTO swayze (url, title) VALUES (%s, %s)" corner.cur.execute(query, (url, title ) ) except(UnicodeEncodeError): continue
#!/usr/bin/env python import pymysql from SwayzeBaby import SwayzeBaby from corner import Corner #Here's a counter to count how many images we've processed x = 1 #instantiate our objects swayze = SwayzeBaby() selector = Corner() insertor = Corner() startId = 0 selector.query("SELECT id, url FROM swayze where fake=0 AND id >= " + repr(startId)) for row in selector.cur: swayze_id = row[0] url = row[1] colors = swayze.getColorScheme(url) if colors is None: print("f**k that image") else: for color in colors: query = "INSERT INTO colors (swayze_id, color) VALUES (%s, %s)" insertor.cur.execute(query, (swayze_id, color)) print("Processed " + repr(x / 3) + " images. Last printed: " + repr(swayze_id)) x += 1
if __name__ == '__main__': img = cv.CreateImage((100, 100), 8, 1) a = (50, -10) b = (85, 50) c = (50, 90) d = (5, 50) cv.FillConvexPoly(img, [a, b, c, d], (255, 255, 255)) temp = 'temp' cv.NamedWindow(temp) oa, ob, oc, od = (48, -8), (80, 50), (48, 88), (0, 50) points = [oa, ob, oc, od] corners = [Corner(points, 0), Corner(points, 1), Corner(points, 2), Corner(points, 3)] CP = CornerPredictor(corners, 50, img) cv.PolyLine(img, [[oa, ob, oc, od]], 1, (150, 100, 100)) dimg = cv.CreateImage((200, 200), 8, 1) cv.PyrUp(img, dimg) cv.ShowImage(temp, dimg) cv.WaitKey(10000)