def __init__(self): self._windowManager = WindowManager.WindowManager( "Cameo", self.onKeyPress) self._captureManager = CaptureManager.CaptureManager( cv2.VideoCapture(0), self._windowManager, True) self._curveFilter = Filters.BGRCrossProcessCurveFilter() self._convultionFilter = Filters.BlurFilter()
def SincBandPassNonLinear(RBTW=0.05): """ Two sinthetic gaussian centered in 15/25 Hz example of sinc band pass-filtering Relative bandwidth transition desired of 20% more info on: dspguide.com or wikipedia """ s1 = Filters.SampleSignals.NonLinear(200, 0.01, 15, 500) # inventa um gauss. centrado em 15Hz s2 = Filters.SampleSignals.NonLinear(200, 0.01, 35, 500) # inventa um gauss. centrado em 35Hz s = 0.6 * s1 + 0.4 * s2 # monta um com 60% energia de s1 e 40% da energia de s2 N = numpy.size(s) print "Number of samples input %d" % N # use the upper limit of frequency to get the number of samples needed to a relative bandwidth transition desired Nf = Filters.FilterSize(25.0, 0.01, RBTW) fir = Filters.SincBandPass(Nf, 0.01, 5, 25) # filtro passa banda caixa frequencias de corte de passagem de 5Hz ah 25Hz res = Filters.ConvFft(s, fir) # mostra o resultado da conv. # older way # res = Filters.ConvEnd(s, fir, 0.01, plot=True); # mostra o resultado da conv. Filters.Dspplot.PlotFftCompare(s, res, 0.01) return res
def btn_filterHistogramGlobalEqualization_clicked(self): if self.rdio_filterHistogramLocal.isChecked(): Filters.filterAll(Filters.histogramLocalEqualize, self.processingImageList) self.sldr_images_valueChanged(self.sldr_images.value()) else: Filters.filterAll(Filters.histogramGlobalEqualize, self.processingImageList) self.sldr_images_valueChanged(self.sldr_images.value())
def run(self): res = Filters.thresholdSegmentation(self.dataIN, self.sigmaSmooth, self.thresMembra) res = Filters.invertVolume2D(res, self.sizeFilter) self.seg = res
def run(self): self._windowManager.createWindow() while self._windowManager.isWindowCreated: self._captureManager.enterFrame() frame = self._captureManager.frame # self._colorSpace.recolorRC(frame, frame) # self._blurFilter.apply(frame, frame) self._faceTracker.update(frame) faces = self._faceTracker.faces Rects.swapRects(frame, frame, [face.faceRect for face in faces]) Filters.strokeEdges(frame, frame) self._curveFilter.apply(frame, frame) self._faceTracker.drawDebugRects(frame) cv2.imshow('Cameo', frame) # cv2.imshow('frame', frame) # # # Filter the frame # self._captureManager.exitFrame() self._windowManager.processEvents()
def clean_text(self,minWordLen): dictionary = Dictionary.Dictionary2() for i in range(len(self.inputContent)): line = self.inputContent[i].rstrip('\n').split('\t') text = " ".join(line[self.columnStart:]).strip() text = Filters.filter_url( text ) text = Filters.filter_accents(text.decode('utf8', 'ignore')) text = Filters.filter_punct( text ) text = Filters.filter_charRepetition( text ).split() words = [ word for word in text if word.find('@') == -1 and not word.isdigit() \ and len(word) > minWordLen] newLine = "\t".join( line[:self.columnStart] ) + "\t" for word in words: if word[0].isupper(): newWord = word else: newWord = dictionary.getWord(word, False, False) if( word not in self.histogram ): self.histogram[word] = 0 self.histogram[word] += 1 newLine += newWord + " " self.inputContent[i] = newLine.strip()
def make_filter(dbstate, uistate, objclass, gramps_ids, title=None): """ Makes a Gramps Filter through dialog from a enumeration (list, set, etc.) of gramps_ids of type objclass. >>> make_filter(dbstate, uistate, 'Person', ['I0003', ...]) """ if objclass == "Media": objclass = "MediaObject" FilterClass = Filters.GenericFilterFactory(objclass) rule = getattr(getattr(Filters.Rules, objclass), 'RegExpIdOf') filter = FilterClass() if title is None: title = _("Filter %s from Clipboard") % objclass if callable(title): title = title() filter.set_name(title) struct_time = time.localtime() filter.set_comment( _("Created on %4d/%02d/%02d") % (struct_time.tm_year, struct_time.tm_mon, struct_time.tm_mday)) re = "|".join(["^%s$" % gid for gid in sorted(gramps_ids)]) filter.add_rule(rule([re])) filterdb = Filters.FilterList(const.CUSTOM_FILTERS) filterdb.load() EditFilter(objclass, dbstate, uistate, [], filter, filterdb, lambda: edit_filter_save(uistate, filterdb, objclass))
def applyFilters(image, sigma, win_size): ''' Apply Gaussian Blur and Sobel filter ''' blurred_im = Filters.gaussFilter(image, sigma, win_size) grad_x,grad_y = Filters.sobelFilter(blurred_im) return blurred_im, grad_x, grad_y
def main(argv=None): """main can also be called in the python interpreter, by supplying the command line as the argument.""" if argv is None: argv = sys.argv[1:] def destroy(*args): # call back for terminating the main eventloop gtk.main_quit() parser = OptionParser() (options, argv) = parser.parse_args(args = argv) config = Configuration.Config() db = None db = Database.Database() db.do_connect(config) qdict = SQL.SQL(db.get_backend_name()) i = Filters(db, config, qdict) main_window = gtk.Window() main_window.connect('destroy', destroy) main_window.add(i.get_vbox()) main_window.show() gtk.main()
def main(argv=None): """main can also be called in the python interpreter, by supplying the command line as the argument.""" if argv is None: argv = sys.argv[1:] def destroy(*args): # call back for terminating the main eventloop gtk.main_quit() parser = OptionParser() (options, argv) = parser.parse_args(args=argv) config = Configuration.Config() db = None db = Database.Database() db.do_connect(config) qdict = SQL.SQL(db.get_backend_name()) i = Filters(db, config, qdict) main_window = gtk.Window() main_window.connect('destroy', destroy) main_window.add(i.get_vbox()) main_window.show() gtk.main()
def write(): global image if request.method == "POST": route = 'static/' + image if request.form['submit'] == 'Write': filter.writeText(route, request.form["text"], request.form["x"], request.form["y"], 1) return render_template("write.html", image=image)
def crop(): global image if request.method == "POST": route = 'static/' + image if request.form['submit'] == 'Crop': filter.crop(route, request.form["lLeft"], request.form["uLeft"], request.form["uRight"], request.form["lRight"]) return render_template("crop.html", image=image)
def run(self): res = Filters.rayFeatures(self.dataIN, self.rayLength) res = Filters.multiHessian(res, self.scales) mem = vigra.gaussianSmoothing(self.dataIN, self.sigmaSmooth) res = Filters.waterSeg(mem, res, self.th1, self.th2) self.seg = res
def createDictionary(text): textList = text.split() lemList = filter.lemetizeWordList(textList) wordlist = removeStopwords(lemList, stopwords) # stemList = filter.stemetizWordList(textList) # wordlist = removeStopwords(stemList,stopwords) regList = filter.regexTextList(wordlist) dictionary = wordListToFreqDict(regList) # sorteddict = sortFreqDict(dictionary) # return sorteddict return dictionary
def __init__(self, parent=None): super(View, self).__init__(parent) self.figure = plt.figure() self.canvas = FigureCanvas(self.figure) self.canvas.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) toolbar = NavigationToolbar(self.canvas, self) self.navigationLayout = QHBoxLayout() layout = QHBoxLayout(self) self.navigations = [] self.addNavigation(True) self.filters = [ Filters.Lowpass(), Filters.Deconvolve(), Filters.Rotate() ] filterLayout = QVBoxLayout() for f in self.filters: filterLayout.addWidget(f) f.filterChanged.connect(self.plot) filterLayout.addStretch() addIcon = QIcon.fromTheme('list-add') addNaviButton = QPushButton(addIcon, 'Add navigation', self) addNaviButton.clicked.connect(self.addNavigation) self.maxFreq = QDoubleSpinBox(self) self.maxFreq.setValue(10.0) self.maxFreq.setVisible(False) spectrumIcon = QIcon.fromTheme('network-wireless') self.spectrum = QPushButton(spectrumIcon, 'Spectrum', self) self.spectrum.setCheckable(True) self.spectrum.clicked.connect(self.plot) self.spectrum.toggled.connect(self.maxFreq.setVisible) self.maxFreq.valueChanged.connect(self.plot) saveAll = QPushButton(QIcon.fromTheme('document-save'), '', self) saveAll.clicked.connect(self.savePlots) toolLayout = QHBoxLayout() toolLayout.addWidget(addNaviButton) toolLayout.addWidget(self.spectrum) toolLayout.addWidget(self.maxFreq) toolLayout.addWidget(saveAll) toolLayout.addWidget(toolbar) plotLayout = QVBoxLayout() plotLayout.addLayout(toolLayout) plotLayout.addWidget(self.canvas) layout.addLayout(self.navigationLayout) layout.addLayout(plotLayout) layout.addLayout(filterLayout)
def generate_species_list(c_all, c_some): """ Create a list of all species found in a user defined polygon.""" raw_species_list_plants, raw_species_list_animals, raw_species_list_fungi = QueryGBIF.qgd(c_all) # raw_species_list = QueryGBIF.qgd(c_all) # raw_species_list = QueryGBIF.qgd(c_all[0]) # Working species_list_plants = Filters.occurrence_nr(raw_species_list_plants) print species_list_plants # Devel. species_list_animals = Filters.occurrence_nr(raw_species_list_animals) species_list_fungi = Filters.occurrence_nr(raw_species_list_fungi) # species_list = Filters.occurrence_nr(raw_species_list) return species_list_plants, species_list_animals, species_list_fungi
def run(self): """ Run the main loop """ self._windowManager.createWindow() while self._windowManager.isWindowCreated: self._captureManager.enterFrame() frame = self._captureManager.frame Filters.strokeEdges(frame, frame) self._curveFilter.apply(frame, frame) self._convultionFilter.apply(frame, frame) self._captureManager.exitFrame() self._windowManager.processEvents()
def SincBoxNonStationary(): """ wrap around convolution from numerical recipes including the linear detrend for non stationay data the fft convolution also makes the things easier for working and also performance """ sig = rand(100) + 3 sig[0:25] = sig[0:25] + 1 sig[75:100] = sig[75:100] - 1 fr = Filters.SincLowPass(51, 1, 0.1) res = Filters.ConvFft(sig, fr) Filters.Dspplot.PlotFftCompare(sig, res, 0.1)
def computeDepthMapWithHOG( iminput, dataSetDir, depthMapDir, HOGdetector, k = 45 ): imNames = [ f for f in os.listdir( dataSetDir ) if f.endswith('.png') | f.endswith('.jpg')] imlist = [ os.path.join(dataSetDir,f) for f in imNames ] depthlist = [ os.path.join( depthMapDir, f.split('.')[0]+'_abs_smooth.png' ) for f in imNames ] if len(imlist) == 0 | len(depthlist) == 0 : return -1 if len( iminput.shape ) == 3: im = cv2.cvtColor( iminput, cv2.COLOR_RGB2HSV )[:,:,2] else: im = iminput.copy() #resize objective image to the size of train images imSize = np.array( Image.open(imlist[0]).convert('L')).shape im = misc.imresize( im, imSize ) #excute kNN search kIndices, distances, imlist, arrayOfDescriptors = kNNSearchWithHOG(im,imlist,HOGdetector,k) #read the k depthMap into 3-dimensional array kdepthMaps kdepthMaps = np.zeros( (imSize[0],imSize[1],len(kIndices) ) ) for i,k in enumerate(kIndices): kdepthMaps[:,:,i] = np.array( Image.open(depthlist[k]) ) #k depthMaps fused fusedDepthMap = fuseDepthMaps( kdepthMaps, distances ) #cross bilateral filtered finalDepthMap = Filters.cross_bilateral_filter( fusedDepthMap, iminput, 10, 20, 20 ) return finalDepthMap,kdepthMaps, fusedDepthMap, distances
def add_quest_filter(self, name, settings): if name in self._quest_filters: raise ValueError("Unable to add Quest Filter: Filter with the " "name {} already exists!".format(name)) f = Filters.QuestFilter(self, name, settings) self._quest_filters[name] = f self._log.debug("Quest filter '%s' set: %s", name, f)
def add_grunt_filter(self, name, settings): if name in self._grunt_filters: raise ValueError("Unable to add Invasion Filter: Filter with the " "name {} already exists!".format(name)) f = Filters.GruntFilter(self, name, settings) self._grunt_filters[name] = f self._log.debug("Invasion filter '%s' set: %s", name, f)
def __init__(self, querylist, config, parent, debug=True): """Constructor for GraphViewer""" self.sql = querylist self.conf = config self.debug = debug self.parent = parent #print "start of GraphViewer constructor" self.db = Database.Database(self.conf, sql=self.sql) filters_display = { "Heroes": True, "Sites": True, "Games": False, "Currencies": True, "Limits": False, "LimitSep": False, "LimitType": False, "Type": False, "UseType": 'tour', "Seats": False, "SeatSep": False, "Dates": True, "GraphOpsTour": True, "Groups": False, "Button1": True, "Button2": True } self.filters = Filters.Filters(self.db, self.conf, self.sql, display=filters_display) self.filters.registerButton1Name(_("Refresh _Graph")) self.filters.registerButton1Callback(self.generateGraph) self.filters.registerButton2Name(_("_Export to File")) self.filters.registerButton2Callback(self.exportGraph) self.mainHBox = gtk.HBox(False, 0) self.mainHBox.show() self.leftPanelBox = self.filters.get_vbox() self.hpane = gtk.HPaned() self.hpane.pack1(self.leftPanelBox) self.mainHBox.add(self.hpane) # hierarchy: self.mainHBox / self.hpane / self.graphBox / self.canvas / self.fig / self.ax self.graphBox = gtk.VBox(False, 0) self.graphBox.show() self.hpane.pack2(self.graphBox) self.hpane.show() self.fig = None #self.exportButton.set_sensitive(False) self.canvas = None self.db.rollback() #update the graph at entry (simulate a "Refresh Graph" click) gobject.GObject.emit(self.filters.Button1, "clicked")
def test_bug(self): nmoves = 200 bugPositions = np.zeros((nmoves, 2)) trackedPositins = np.zeros((nmoves, 2)) testBug = VirtualBug.VirtualBug() kf = None for i in range(nmoves): bugPositions[i, :] = np.array([testBug.x, testBug.y]) if i == 2: kf = Filters.Kalman(bugPositions[0, 0], bugPositions[0, 1], bugPositions[1, 0], bugPositions[1, 1]) if i > 2: trackedPositins[i, 0] = kf.X[0] trackedPositins[i, 1] = kf.X[1] kf.updatePredict(bugPositions[i, :]) testBug.move() plt.figure() plt.title("Bug position tracking test") plt.xlabel("x") plt.ylabel("y") plt.plot(bugPositions[:, 0], bugPositions[:, 1], 'b-', label="Bug") plt.plot(trackedPositins[:, 0], trackedPositins[:, 1], 'r--', label="Tracked") plt.legend() plt.savefig("test_bug_tracking.png", dpi=500) plt.close()
def add_weather_filter(self, name, settings): if name in self._weather_filters: raise ValueError("Unable to add Weather Filter: Filter with the " "name {} already exists!".format(name)) f = Filters.WeatherFilter(self, name, settings) self._weather_filters[name] = f self._log.debug("Weather filter '%s' set: %s", name, f)
def histogramButton(self): self.filter_button = tk.Button( self.histogramFrame, text='An Example for histogram matching', width=self.width, command=lambda: filter.histogram_matching()) self.filter_button.grid(column=2, row=2)
def tunnelLowFilter(self, mechanism, policy=0): if mechanism == 0: Filters.vguardStandard(self, policy) elif mechanism == 1: Filters.tokenBucketPolicer(self, self.tunnelLowCapacity) elif mechanism == 2: Filters.leakyBucketShapper(self, self.tunnelLowCapacity) else: Filters.leakyBucketPriorityShapper(self, self.tunnelLowCapacity, policy)
def SincTrapezoidalLowPassNoise(): """ a experiment with the trapezoidal low pass that's perfectly working, filter sampling is perfect and also the filtering process with the result using NR wrapped around convolution (use FftConv3 its simpler) """ s = Filters.SampleSignals.PeriodicNoise(200, 0.05) print " Input number of samples %d" % numpy.size(s) #filter depends on the sample rate and the transition bandwidth we want # we want 20% its a reasonable value Nf = Filters.FilterSize(3.0, 0.05) print " Filter number of samples %d" % Nf fr = Filters.SincTrapezoidalLowPass(Nf, 0.05, 0.5, 3) #res = Filters.ConvFft(s, filter, 0.05, plot=True); res = Filters.ConvFft(s, fr) Filters.Dspplot.PlotFftCompare(s, res, 0.05) return res
def _filter(self, img, filter_type, filter_paras): imgs = np.transpose(img, (2, 0, 1)) imgs = F.Filter_list(imgs, Ftype=filter_type, N=filter_paras["N"], K=filter_paras["K"], diffuse_function=filter_paras["diffuse_function"], gamma=filter_paras["gamma"]) imgs = np.array(imgs) imgs = np.transpose(imgs, (1, 2, 0)) return imgs
def _init_draw(self): for i in range(self.length): t = self.timef[i] self._updateCandle(self.candles[i], t, self.ohlc[i]) prices = Filters.peakPrices(list2array(self.ohlc), 0.0005, 20, np.min(self.ohlc), np.max(self.ohlc)) for i in range(len(prices)): price = prices[i] width = len(prices) - i self.hline([[price, 'green', width / 4]]) return
def __init__(self): self._windowManager = WindowManager('Cameo', self.onKeypress) self._captureManager = CaptureManager(cv2.VideoCapture(0), self._windowManager, True) # self._colorSpace = ColorSpace() self._curveFilter = Filters.BGRCrossProcessCurveFilter() # self._blurFilter = Filters.BlurFilter() self._faceTracker = FaceTracker() self._shouldDrawDebugRects = False
def __init__(self, querylist, config, parent, debug=True): QSplitter.__init__(self, parent) self.sql = querylist self.conf = config self.debug = debug self.parent = parent self.db = Database.Database(self.conf, sql=self.sql) filters_display = { "Heroes": True, "Sites": True, "Games": True, "Currencies": True, "Limits": True, "LimitSep": True, "LimitType": True, "Type": False, "UseType": 'ring', "Seats": False, "SeatSep": False, "Dates": True, "GraphOps": True, "Groups": False, "Button1": True, "Button2": True } self.filters = Filters.Filters(self.db, display=filters_display) self.filters.registerButton1Name(_("Refresh Graph")) self.filters.registerButton1Callback(self.generateGraph) self.filters.registerButton2Name(_("Export to File")) self.filters.registerButton2Callback(self.exportGraph) scroll = QScrollArea() scroll.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Expanding) scroll.setWidget(self.filters) self.addWidget(scroll) frame = QFrame() self.graphBox = QVBoxLayout() frame.setLayout(self.graphBox) self.addWidget(frame) self.setStretchFactor(0, 0) self.setStretchFactor(1, 1) self.fig = None #self.exportButton.set_sensitive(False) self.canvas = None self.exportFile = None self.db.rollback()
def Spike_Count(data_Frame,window = 5,win_step = 1, fps = 1.301,pass_band = (0.05,0.5)): ''' Count total dF/F in a time window, to evaluate cell activity. Parameters ---------- data_Frame : (pd Frame) Data frame of cell data. One row a cell. window : (int), optional Average window size. In seconds. The default is 5. win_step : (int), optional . The default is 20. fps : TYPE, optional DESCRIPTION. The default is 1.3. pass_band : TYPE, optional DESCRIPTION. The default is (0.05,0.5). Returns ------- activation_Diagram : TYPE DESCRIPTION. ''' acn = data_Frame._stat_axis.values.tolist()# get all cell name HP_Para = pass_band[0]*2/fps LP_Para = pass_band[1]*2/fps dF_F_Frame = data_Frame.copy()# deeph copy for i in range(len(acn)): c_train = data_Frame.loc[acn[i]] c_filted_train = Filters.Signal_Filter(c_train,filter_para = (HP_Para,LP_Para)) frame_num = len(c_filted_train) most_unactive = np.array(sorted(c_filted_train)[0:int(frame_num*0.1)])# Use least active 10% as base c_base = most_unactive.mean() c_dF_F_train = np.clip((c_filted_train-c_base)/c_base,0,None) dF_F_Frame.loc[acn[i]] = c_dF_F_train # After generating dF/F trains, we will calcuate window_length = int(window*fps) window_step = int(win_step*fps) win_num = 1+int((frame_num-window_length)/window_step)# Down stair round spike_counter = pd.DataFrame(index =acn) for i in range(win_num): c_win = dF_F_Frame.iloc[:,window_step*i:(window_step*i+window_length)] c_count = c_win.sum(1)# sum all dF/F values. spike_counter[i] = c_count # 加一个Z分数的功能 cell_avr = spike_counter.mean(1) cell_std = spike_counter.std(1) Z_counter = (spike_counter.sub(cell_avr,axis = 0)).div(cell_std,axis = 0) Z_counter = Z_counter.clip(-5,5,axis = 0) return spike_counter,Z_counter
def selectFilters(cfg, lexicon): filtersPresetName, filtersCfg = selectSubTreeWithBase(cfg, 'filters') filters = [] #OriginalOnlyFilter if filtersCfg.get('original') == True: filters.append(Filters.OriginalOnlyFilter(lexicon)) #NameLengthFilter minLength = filtersCfg.get('min-length', default=0) maxLength = filtersCfg.get('max-length', default=float("inf")) if minLength > 0 or maxLength < float("inf"): filters.append(Filters.NameLengthFilter(minLength, maxLength)) if filtersCfg.contains('regex'): pattern = filtersCfg.get('regex') filters.append(Filters.RegexFilter(pattern)) if cfg.get('verbose'): print('Choosing filters using settings %s' % (repr(filtersPresetName))) return Filters.AggregateFilter(filters)
def main(): # 创建处理文件和数据过滤器对象 fileOperator = DealFiles.DealFiles() filters = Filters.Filetrs() dataSet = fileOperator.loadData('/Users/YinongLong/dataSet/ml-100k/u.data') result = filters.filterInstances(dataSet, num=15) # fileOperator.outputFileWithDate(result, '/Users/YinongLong/dataSet/sortedData') # featureData = fileOperator.loadData('/Users/YinongLong/dataSet/sortedData') dictGraphData = filters.filterForGraph(result) # usersRecord = filters.generateUserWithMovie(result) graph = GenerateGraph.Graph() graph.showGraph(dictGraphData)
def calculateOrientation(self): self.image = self.image # smooth image with gaussian blur smoothed_im = Filters.gaussFilter(self.image, 0.5, 3) # calculate gradients with sobel filter dx,dy = Filters.sobelFilter(smoothed_im) # smooth gradients Gx = Filters.gaussFilter(dx,0.5,3) Gy = Filters.gaussFilter(dy,0.5,3) # compute gradient magnitude Gxx = Gx **2 Gyy = Gy **2 G = np.sqrt(Gxx + Gyy) # calculate theta theta = np.arctan2(Gy,Gx) # smooth theta smoothed_theta = Filters.gaussFilter(theta, 0.5, 3) # calculate double sine and cosine on theta --> increases precision Tx = (G**2 + 0.001) * (np.cos(smoothed_theta)**2 - np.sin(smoothed_theta)**2) Ty = (G**2 + 0.001) * (2 * np.sin(smoothed_theta) * np.cos(smoothed_theta)) denom = np.sqrt(Ty**2 + Tx**2) Tx = Tx / denom Ty = Ty / denom # smooth theta x and y smoothed_Tx = Filters.gaussFilter(Tx, 0.5, 3) smoothed_Ty = Filters.gaussFilter(Ty, 0.5, 3) # calculate new value for theta theta = np.pi + np.arctan2(smoothed_Ty,smoothed_Tx)/2 #draw lines final_im = self.decomposeImage(theta,5) return theta, final_im
def MovieMatchHandler(request): fmovie = {} fscore = {} context= {} prevvote = False if request.is_ajax(): if request.method == 'GET': params = request.GET template = "movievotingview.html" elif request.method == 'POST': params = request.POST winner = Movie.objects.get(mid=params['winner']) loser = Movie.objects.get(mid=params['loser']) if params['year']: year = params['year'] userprofile = request.user.get_profile() ranks = CalculateRating('movie',winner,loser,userprofile) prevvote = True template = "movievotingview.html" else: params = {} template = "indexmovie.html" results = Filters.setFromParams(request,params,'movie') request.session['filtdict'] = results['filtdict'] request.session['filtvalues'] = results['filtvalues'] results = Filters.getMovieAndScoreFilters(request) fmovie = results['fmovie'] fscore = results['fscore'] topfmovie = results['topfmovie'] if request.session.get('rematch') == 'Yes': rematch = True context['rematch'] = "Rematches Allowed" request.session['filtdict']['rematch'] = 'Rematches Allowed' else: rematch = False context['rematch'] = "No Rematches" if 'rematch' in request.session['filtdict']: del request.session['filtdict']['rematch'] print fscore print fmovie if 'gametype' in request.session['filtvalues'] and (request.session['filtvalues']['gametype']=='winner' or request.session['filtvalues']['gametype']=='loser') and request.method == 'POST': print "it was a post bitch" if request.session['filtvalues']['gametype'] == 'winner': movie1 = winner elif request.session['filtvalues']['gametype'] == 'loser': movie1 = loser movie1mat = UserMovieScore.objects.get(uid=request.user.get_profile(),mid= movie1) results = getOneMovie(fmovie, fscore, rematch, movie1,request.user.get_profile()) movie2 = results['Movie'] movie2mat = results['matchup'] elif request.session.get('m_lockedin') != None: movie1 = request.session['p_lockedin']#Movie.objects.get(mid= request.session['lockedin']) try: movie1mat = UserMovieScore.objects.get(uid = request.user.get_profile(),mid=movie1) except: movie1mat = UserMovieScore(uid = request.user.get_profile(), mid=movie1, elorating = 1000,numratings =0,wins=0,losses=0) movie1mat.save() if close_matchup: results = None#getCloseOneMovie(fmovie,fscore,rematch,movie1,movie1mat,request.user.get_profile()) else: results = getOneMovie(fmovie, fscore, rematch, movie1, request.user.get_profile()) movie2 = results['Movie'] movie2mat = results['matchup'] else: movies = getTwoMovies(fmovie,fscore,rematch,request.user.get_profile(),80) if movies == None: movie1 = None movie2 = None movie1mat = None movie2mat = None else: movie1 = movies['1'] movie2 = movies['2'] movie1mat = movies['1mat'] movie2mat = movies['2mat'] if movie1 == None or movie2 == None: movie1 = None movie2 = None movie1mat = None movie1mat = None #return HttpResponse("NO PEOPLE") top25 = UserMovieScore.objects.filter(uid=request.user.get_profile()).order_by('elorating').reverse() if (top25.count()>25): top25 = top25[:25] if prevvote: context['ranks'] = ranks t1 = time.time() #count = 0 #for i in range(1,1000): # testmovies = getTwoMovies(fmovie,fscore,rematch,request.user.get_profile(),25) # count += testmovies['count'] #t2 = time.time() #print "time was {} count was {}".format(t2-t1,count) context['moviebar']= True context['movie1'] = movie1 context['movie1mat'] = movie1mat context['movie2'] = movie2 context['movie2mat'] = movie2mat if movie1 != None and movie1.images>0: #print movie1.images context['movie1ran'] = random.randint(1,movie1.images) if movie2 != None and movie2.images>0: context['movie2ran'] = random.randint(1,movie2.images) context['top20'] = top25 context['top20'] = top25 context['filters'] = request.session.get('filtdict') #return_str = render_block_to_string('subtemplate.html', 'results', context) print context print movie1 print movie2 message = render_to_response(template, context,context_instance=RequestContext(request)) return HttpResponse(message)
def PersonMatchHandler(request): year = "" context = {} #fperson = {} #fscore = {'uid':request.user.get_profile(),'neveruse':False} fscore = {} prevvote = False if request.is_ajax(): if request.method == 'GET': params = request.GET template = 'personvotingview.html' print params elif request.method == 'POST': params = request.POST winner = Person.objects.get(pid=params['winner']) loser = Person.objects.get(pid=params['loser']) prevvote = True userprofile = request.user.get_profile() ranks = CalculateRating('person',winner,loser,userprofile) template = 'personvotingview.html' else: params = request.GET template = "indexperson.html" results = Filters.setFromParams(request,params,'person') request.session['filtdict'] = results['filtdict'] request.session['filtvalues'] = results['filtvalues'] results = Filters.getPersonAndScoreFilters(request) fperson = results['fperson'] fscore = results['fscore'] topfperson = results['topfperson'] if 'Food.objects.filter(tags__name__in=["delicious"])' in params: request.session['filtdict']['search'] = Person.objects.get(pid=params['search']).name request.session['search'] = params['search'] ########################################## #TEMPORARY UNTIL TAGGING GETS IMPLEMENTED # if 'cat' in params: # if params['cat'] == 'All Categories': # request.session['cat'] = None # else: # request.session['cat'] = params['cat'] # cat=None # if request.session.get('cat') != None: # cat = PersonCategory.objects.get(gid=request.session.get('cat')) # context['cat'] = PersonTag.objects.get(slug=request.session.get('cat')) # request.session['filtdict']['cat'] = context['cat'] # fperson['tags__slug'] = request.session.get('cat') # #fperson['cats__category']=cat.category # else: # context['cat'] = "All Categories" ############################################# rematch = request.session['filtvalues']['rematch'] if 'gametype' in request.session['filtdict'] and request.session['filtdict']['gametype'] == 'Close Matchup': close_matchup = True else: close_matchup = False if fscore != {}: fscore['uid'] = request.user.get_profile() fscore['neveruse'] = False print "fperson {} fscore {}".format(fperson, fscore) if 'gametype' in request.session['filtvalues'] and (request.session['filtvalues']['gametype']=='winner' or request.session['filtvalues']['gametype']=='loser') and request.method == 'POST': print "it was a post bitch" if request.session['filtvalues']['gametype'] == 'winner': person1 = winner elif request.session['filtvalues']['gametype'] == 'loser': person1 = loser person1mat = UserPersonScore.objects.get(uid=request.user.get_profile(),pid = person1) results = getOnePerson(fperson, fscore, rematch, person1,request.user.get_profile(),25) person2 = results['person'] person2mat = results['matchup'] elif 'p_lockedin' in request.session['filtvalues'] and request.session['filtvalues']['p_lockedin'] != None: print "lockedin" person1 = request.session['filtvalues']['p_lockedin']#Person.objects.get(pid = request.session['lockedin']) try: person1mat = UserPersonScore.objects.get(uid = request.user.get_profile(),pid=person1) except: person1mat = UserPersonScore(uid = request.user.get_profile(), pid=person1, elorating = 1000,numratings =0,wins=0,losses=0) person1mat.save() if close_matchup: results = getCloseOnePerson(fperson,fscore,rematch,person1,person1mat,request.user.get_profile()) else: results = getOnePerson(fperson, fscore, rematch, person1, request.user.get_profile(),25) person2 = results['person'] person2mat = results['matchup'] else: print request.session['filtvalues'] print "two people" people = getTwoPeople(fperson,fscore,rematch,request.user.get_profile(),25) if people == None: person1 = None person2 = None person1mat = None person2mat = None else: person1 = people['1'] person2 = people['2'] person1mat = people['1mat'] person2mat = people['2mat'] if person1 == None or person2 == None: person1 = None person2 = None person1mat = None person1mat = None #return HttpResponse("NO PEOPLE") topfperson={} if 'popularity_rating__gte' in fperson: del fperson['popularity_rating__gte'] for i in fperson: index = "pid__" + str(i) topfperson[index] = fperson[i] print topfperson top25 = UserPersonScore.objects.filter(uid=request.user.get_profile()).filter(**topfperson).order_by('elorating').reverse() if (top25.count()>25): top25 = top25[:25] if prevvote: context['ranks'] = ranks #t1 = time.time() #for i in range(1,1000): # testtvshows = getTwoPeople(fperson,fscore,rematch,request.user.get_profile(),25) #t2 = time.time() #print "1000 2 people was {}".format(t2-t1) context['filters'] = request.session.get('filtdict') context['person1'] = person1 context['person1mat'] = person1mat context['person2'] = person2 context['person2mat'] = person2mat context['p_tag'] = Person.tags.most_common() context['lists'] = PersonList.objects.all() context['peoplebar'] = True if person1 != None and person1.images>0: print person1.images context['person1ran'] = random.randint(1,person1.images) if person2 != None and person2.images>0: context['person2ran'] = random.randint(1,person2.images) context['top20'] = top25 message = render_to_response(template, context, context_instance=RequestContext(request)) return HttpResponse(message)
# getting input image_str = sys.argv[7] sigma = float(sys.argv[2]) win_size = int(sys.argv[4]) threshold = int(sys.argv[6]) length = len(image_str) - 4 file_extension = image_str[length:] if not file_extension == ".png": print "**Error: Invalid file type.\nThe software supports only .png files" sys.exit() image = cv2.imread(image_str, cv2.CV_LOAD_IMAGE_GRAYSCALE) blurred_im = Filters.gaussFilter(image, sigma, win_size) grad_x,grad_y = Filters.sobelFilter(blurred_im) # calculate grad grad = np.hypot(grad_y,grad_x) # calculate theta theta = np.arctan2(grad_y, grad_x) # binarize x0,y0 = np.where(grad > threshold) x1,y1 = np.where(grad < threshold) grad[x0,y0] = 1 grad[x1,y1] = 0 edge_im = grad # show results
def calculateOrientation(image): # smooth image with gaussian blur smoothed_im = Filters.gaussFilter(image, 0.5, 3) # calculate gradients with sobel filter dx,dy = Filters.sobelFilter(smoothed_im) # smooth gradients Gx = Filters.gaussFilter(dx,0.5,3) Gy = Filters.gaussFilter(dy,0.5,3) # compute gradient magnitude Gxx = Gx **2 Gyy = Gy **2 G = np.sqrt(Gxx + Gyy) # calculate theta theta = np.arctan2(Gy,Gx) # smooth theta smoothed_theta = Filters.gaussFilter(theta, 0.5, 3) # calculate double sine and cosine on theta --> increases precision Tx = (G**2 + 0.001) * (np.cos(smoothed_theta)**2 - np.sin(smoothed_theta)**2) Ty = (G**2 + 0.001) * (2 * np.sin(smoothed_theta) * np.cos(smoothed_theta)) denom = np.sqrt(Ty**2 + Tx**2) Tx = Tx / denom Ty = Ty / denom # smooth theta x and y smoothed_Tx = Filters.gaussFilter(Tx, 0.5, 3) smoothed_Ty = Filters.gaussFilter(Ty, 0.5, 3) # calculate new value for theta theta = np.pi + np.arctan2(smoothed_Ty,smoothed_Tx)/2 # The following code will calculate the average angle and draw lines --> it should be replaced # the reason is that this approximation is very inaccurate. # Note: this piece of code will not impact the precision of the Gabor filter. It is used # just to draw the lines on the orientation image. windows = {} orient = {} median = {} row_count = 0 window_height = 8 window_width = 8 currentx= 0 currenty = 0 # decomposing the window in 8 x 8 windows for y in range (0,2): currentx = 0 for x in range(0,2): windows[row_count]=image[currenty:currenty+window_height,currentx:currentx+window_width] orient[row_count]=theta[currenty:currenty+window_height,currentx:currentx+window_width] currentx += window_width row_count += 1 currenty += window_height # drawing lines on each 8 x 8 window for wins in range (0,4): sum = 0 for i in range (0,orient[wins].shape[0]): for j in range(0,orient[wins].shape[1]): sum += orient[wins][i][j] len = 1 if not orient[wins].shape[0] == 0: median[wins] = sum/orient[wins].shape[0]**2 x1 = 4 - len/2*math.cos(median[wins]) * 10 x1 = np.around(x1) x1 = x1.astype(int) y1 = 4 - len/2*math.sin(median[wins]) * 10 y1 = np.around(y1) y1 = y1.astype(int) x2 = 4 + math.cos(median[wins]) * 10 x2 = np.around(x2) x2 = x2.astype(int) y2 = 4 + math.sin(median[wins]) * 10 y2 = np.around(y2) y2 = y2.astype(int) point1 = (x1,y1) point2 = (x2,y2) x0,y0 = np.where(windows[wins]<=20) # values below or equal to 0 are darker regions, hence ridges windows[wins]*-100 if np.any(x0): cv2.line(windows[wins], point1, point2, cv2.cv.CV_RGB(1, 100, 255)) final_image = reconstructImage(image,windows) return final_image