void colvardeps::init_cvb_requires() { int i; if (features().size() == 0) { for (i = 0; i < f_cvb_ntot; i++) { features().push_back(new feature); } } f_description(f_cvb_active, "active"); f_req_children(f_cvb_active, f_cv_active); f_description(f_cvb_apply_force, "apply force"); f_req_children(f_cvb_apply_force, f_cv_gradient); f_description(f_cvb_get_total_force, "obtain total force"); f_req_children(f_cvb_get_total_force, f_cv_total_force); f_description(f_cvb_history_dependent, "history-dependent"); // Initialize feature_states for each instance feature_states.reserve(f_cvb_ntot); for (i = 0; i < f_cvb_ntot; i++) { feature_states.push_back(new feature_state(true, false)); // Most features are available, so we set them so // and list exceptions below } // some biases are not history-dependent feature_states[f_cvb_history_dependent]->available = false; }
AutoShuntCalResult WirelessNode_Impl::autoShuntCal(const ChannelMask& mask, const ShuntCalCmdInfo& commandInfo) { //verify the node supports this operation if(!features().supportsAutoShuntCal()) { throw Error_NotSupported("AutoShuntCal is not supported by this Node."); } //verify the channel mask supports this operation if(!features().supportsChannelSetting(WirelessTypes::chSetting_autoShuntCal, mask)) { throw Error_NotSupported("AutoShuntCal is not supported by the provided channel(s)."); } uint8 channel = mask.lastChEnabled(); WirelessTypes::ChannelType chType = features().channelType(channel); AutoShuntCalResult result; bool success = m_baseStation.node_autoShuntCal(m_address, commandInfo, channel, model(), chType, result); if(!success) { throw Error_NodeCommunication(m_address, "AutoShuntCal has failed."); } return result; }
Symbol match(PcaContext& ctx, const TSomeView& imgv) const { boost::gil::gil_function_requires<boost::gil::ImageViewConcept<TSomeView> >(); boost::gil::gil_function_requires<boost::gil::ColorSpacesCompatibleConcept< typename boost::gil::color_space_type<TSomeView>::type, typename boost::gil::color_space_type<ConstViewT>::type> >(); boost::gil::gil_function_requires<boost::gil::ChannelsCompatibleConcept< typename boost::gil::channel_type<TSomeView>::type, typename boost::gil::channel_type<ConstViewT>::type> >(); assert(static_cast<size_t>(imgv.width()) <= cellWidth()); assert(static_cast<size_t>(imgv.height()) <= cellHeight()); typedef boost::gil::layout< typename boost::gil::color_space_type<ConstViewT>::type, typename boost::gil::channel_mapping_type<TSomeView>::type > LayoutT; typedef typename float_channel_type<typename boost::gil::channel_type<ConstViewT>::type>::type FloatChannelT; typedef typename boost::gil::pixel_value_type<FloatChannelT, LayoutT>::type FloatPixelT; typedef typename boost::gil::type_from_x_iterator<FloatPixelT*>::view_t FloatViewT; FloatViewT tmp_glyph_view = boost::gil::interleaved_view( cellWidth(), cellHeight(), reinterpret_cast<FloatPixelT*>(ctx.imageData_.data()), cellWidth() * sizeof(FloatPixelT)); boost::gil::fill_pixels(tmp_glyph_view, FloatPixelT()); boost::gil::copy_and_convert_pixels(imgv, subimage_view( tmp_glyph_view, 0, 0, imgv.width(), imgv.height())); features()->project(ctx.imageData_, ctx.components_); return font()->getSymbol(features()->findClosestGlyph(ctx.components_)); }
AutoCalResult_shmLink WirelessNode_Impl::autoCal_shmLink() { WirelessModels::NodeModel nodeModel = features().m_nodeInfo.model(); //verify the node supports autocal if(!features().supportsAutoCal()) { throw Error_NotSupported("AutoCal is not supported by this Node."); } //verify the node is the correct model if(nodeModel != WirelessModels::node_shmLink2 && nodeModel != WirelessModels::node_shmLink2_cust1) { throw Error_NotSupported("autoCal_shmLink is not supported by this Node's model."); } //perform the autocal command by the base station AutoCalResult_shmLink result; bool success = m_baseStation.node_autocal_shm(m_address, result); if(!success) { throw Error_NodeCommunication(m_address, "AutoCal has failed."); } return result; }
Containers::Array<char> AbstractFontConverter::exportGlyphCacheToSingleData(GlyphCache& cache) const { CORRADE_ASSERT(features() >= (Feature::ExportGlyphCache|Feature::ConvertData), "Text::AbstractFontConverter::exportGlyphCacheToSingleData(): feature not supported", nullptr); CORRADE_ASSERT(!(features() & Feature::MultiFile), "Text::AbstractFontConverter::exportGlyphCacheToSingleData(): the format is not single-file", nullptr); return doExportGlyphCacheToSingleData(cache); }
std::unique_ptr<GlyphCache> AbstractFontConverter::importGlyphCacheFromSingleData(Containers::ArrayView<const char> data) const { CORRADE_ASSERT(features() >= (Feature::ImportGlyphCache|Feature::ConvertData), "Text::AbstractFontConverter::importGlyphCacheFromSingleData(): feature not supported", nullptr); CORRADE_ASSERT(!(features() & Feature::MultiFile), "Text::AbstractFontConverter::importGlyphCacheFromSingleData(): the format is not single-file", nullptr); return doImportGlyphCacheFromSingleData(data); }
Containers::Array<char> AbstractFontConverter::exportFontToSingleData(AbstractFont& font, GlyphCache& cache, const std::string& characters) const { CORRADE_ASSERT(features() >= (Feature::ExportFont|Feature::ConvertData), "Text::AbstractFontConverter::exportFontToSingleData(): feature not supported", nullptr); CORRADE_ASSERT(!(features() & Feature::MultiFile), "Text::AbstractFontConverter::exportFontToSingleData(): the format is not single-file", nullptr); return doExportFontToSingleData(font, cache, uniqueUnicode(characters)); }
void colvardeps::init_cvc_requires() { size_t i; // Initialize static array once and for all if (features().size() == 0) { for (i = 0; i < colvardeps::f_cvc_ntot; i++) { features().push_back(new feature); } f_description(f_cvc_active, "active"); // The dependency below may become useful if we use dynamic atom groups // f_req_children(f_cvc_active, f_ag_active); f_description(f_cvc_scalar, "scalar"); f_description(f_cvc_gradient, "gradient"); f_description(f_cvc_inv_gradient, "inverse gradient"); f_req_self(f_cvc_inv_gradient, f_cvc_gradient); f_description(f_cvc_debug_gradient, "debug gradient"); f_req_self(f_cvc_debug_gradient, f_cvc_gradient); f_description(f_cvc_Jacobian, "Jacobian derivative"); f_req_self(f_cvc_Jacobian, f_cvc_inv_gradient); f_description(f_cvc_com_based, "depends on group centers of mass"); // Compute total force on first site only to avoid unwanted // coupling to other colvars (see e.g. Ciccotti et al., 2005) f_description(f_cvc_one_site_total_force, "compute total collective force only from one group center"); f_req_self(f_cvc_one_site_total_force, f_cvc_com_based); f_description(f_cvc_scalable, "scalable calculation"); f_req_self(f_cvc_scalable, f_cvc_scalable_com); f_description(f_cvc_scalable_com, "scalable calculation of centers of mass"); f_req_self(f_cvc_scalable_com, f_cvc_com_based); // TODO only enable this when f_ag_scalable can be turned on for a pre-initialized group // f_req_children(f_cvc_scalable, f_ag_scalable); // f_req_children(f_cvc_scalable_com, f_ag_scalable_com); } // Initialize feature_states for each instance // default as unavailable, not enabled feature_states.reserve(f_cvc_ntot); for (i = 0; i < colvardeps::f_cvc_ntot; i++) { feature_states.push_back(new feature_state(false, false)); } // Features that are implemented by all cvcs by default // Each cvc specifies what other features are available feature_states[f_cvc_active]->available = true; feature_states[f_cvc_gradient]->available = true; feature_states[f_cvc_scalable_com]->available = (cvm::proxy->scalable_group_coms() == COLVARS_OK); feature_states[f_cvc_scalable]->available = feature_states[f_cvc_scalable_com]->available; }
bool AbstractFont::openSingleData(const Containers::ArrayReference<const unsigned char> data, const Float size) { CORRADE_ASSERT(features() & Feature::OpenData, "Text::AbstractFont::openSingleData(): feature not supported", false); CORRADE_ASSERT(!(features() & Feature::MultiFile), "Text::AbstractFont::openSingleData(): the format is not single-file", false); close(); std::tie(_size, _lineHeight) = doOpenSingleData(data, size); CORRADE_INTERNAL_ASSERT(isOpened() || (_size == 0.0f && _lineHeight == 0.0f)); return isOpened(); }
std::unique_ptr<GlyphCache> AbstractFontConverter::doImportGlyphCacheFromFile(const std::string& filename) const { CORRADE_ASSERT(features() & Feature::ConvertData && !(features() & Feature::MultiFile), "Text::AbstractFontConverter::importGlyphCacheFromFile(): not implemented", nullptr); /* Open file */ if(!Utility::Directory::fileExists(filename)) { Error() << "Trade::AbstractFontConverter::importGlyphCacheFromFile(): cannot open file" << filename; return nullptr; } return doImportGlyphCacheFromSingleData(Utility::Directory::read(filename)); }
std::pair<Float, Float> AbstractFont::doOpenFile(const std::string& filename, const Float size) { CORRADE_ASSERT(features() & Feature::OpenData && !(features() & Feature::MultiFile), "Text::AbstractFont::openFile(): not implemented", {}); /* Open file */ if(!Utility::Directory::fileExists(filename)) { Error() << "Trade::AbstractFont::openFile(): cannot open file" << filename; return {}; } return doOpenSingleData(Utility::Directory::read(filename), size); }
void VigraRFclassifier::learn(std::vector< std::vector<double> >& pfeatures, std::vector<int>& plabels){ if (_rf) delete _rf; int rows = pfeatures.size(); int cols = pfeatures[0].size(); printf("Number of samples and dimensions: %d, %d\n",rows, cols); if ((rows<1)||(cols<1)){ return; } // clock_t start = clock(); std::time_t start, end; std::time(&start); MultiArray<2, float> features(Shape(rows,cols)); MultiArray<2, int> labels(Shape(rows,1)); int numzeros=0; for(int i=0; i < rows; i++){ labels(i,0) = plabels[i]; numzeros += (labels(i,0)==-1?1:0); for(int j=0; j < cols ; j++){ features(i,j) = (float)pfeatures[i][j]; } } printf("Number of merge: %d\n",numzeros); int tre_count = 255; printf("Number of trees: %d\n",tre_count); RandomForestOptions rfoptions = RandomForestOptions().tree_count(tre_count).use_stratification(RF_EQUAL); //RF_EQUAL, RF_PROPORTIONAL _rf= new RandomForest<>(rfoptions); // construct visitor to calculate out-of-bag error visitors::OOB_Error oob_v; visitors::VariableImportanceVisitor varimp_v; _rf->learn(features, labels); _nfeatures = _rf->column_count(); _nclass = _rf->class_count(); std::time(&end); printf("Time required to learn RF: %.2f sec\n", (difftime(end,start))*1.0); // printf("Time required to learn RF: %.2f\n", ((double)clock() - start) / CLOCKS_PER_SEC); printf("with oob :%f\n", oob_v.oob_breiman); }
bool AbstractFont::openSingleData(const Containers::ArrayView<const char> data, const Float size) { CORRADE_ASSERT(features() & Feature::OpenData, "Text::AbstractFont::openSingleData(): feature not supported", false); CORRADE_ASSERT(!(features() & Feature::MultiFile), "Text::AbstractFont::openSingleData(): the format is not single-file", false); close(); const Metrics metrics = doOpenSingleData(data, size); _size = metrics.size; _ascent = metrics.ascent; _descent = metrics.descent; _lineHeight = metrics.lineHeight; CORRADE_INTERNAL_ASSERT(isOpened() || (!_size && !_ascent && !_descent && !_lineHeight)); return isOpened(); }
void operator() (const cv::Mat & image) const { std::cout << "Extracted features " << features_collection_.size() << "..." << std::endl; Features features((features_collection_.size()==0? 0:features_collection_.front().size())); extract_interface_.compute(image, features); features_collection_.push_back(features); }
void CvSIFT::onNewImage() { LOG(LTRACE)<< "CvSIFT::onNewImage\n"; try { // Input: a grayscale image. cv::Mat input = in_img.read(); std::ofstream feature_calc_time; if(!string(prop_calc_path).empty()) { feature_calc_time.open((string(prop_calc_path)+string("czas_wyznaczenia_cech_sift.txt")).c_str(), ios::out|ios::app); } Common::Timer timer; timer.restart(); //-- Step 1: Detect the keypoints. cv::SiftFeatureDetector detector(0,4); std::vector<cv::KeyPoint> keypoints; detector.detect(input, keypoints); //-- Step 2: Calculate descriptors (feature vectors). cv::SiftDescriptorExtractor extractor; Mat descriptors; extractor.compute( input, keypoints, descriptors); if(!string(prop_calc_path).empty()) { feature_calc_time << timer.elapsed() << endl; } // Write results to outputs. Types::Features features(keypoints); features.type = "SIFT"; out_features.write(features); out_descriptors.write(descriptors); } catch (...) { LOG(LERROR) << "CvSIFT::onNewImage failed\n"; } }
/* * Signal whether the instruction is acceptable for this target. */ int acceptable(struct optab *op) { if ((op->visit & FEATURE_PIC) != 0) return (kflag != 0); return features(op->visit & 0xffff0000); }
vector<vector<DisambiguatedData> > Disambiguator::Disambiguate( const vector<Token>& tokens, double percentage, size_t maxNumberOfPaths , vector<double>* hypothesisDistribution) { vector<PredisambiguatedData> predisambiguated = featureCalculator->CalculateFeatures(tokens); // Create chain size_t size = predisambiguated.size(); vector<wstring> words(size); vector<vector<wstring> > features(size); vector<wstring> labels(size); for (size_t chainIndex = 0; chainIndex < size; ++chainIndex) { words[chainIndex] = predisambiguated[chainIndex].content; features[chainIndex] = predisambiguated[chainIndex].features; } LinearCRF::Chain chain( std::move(words) , std::move(features) , std::move(labels) , vector<vector<wstring> >()); vector<vector<wstring> > bestSequences; vector<vector<double> > bestSequenceWeights; this->Apply(chain , percentage , maxNumberOfPaths , &bestSequences , &bestSequenceWeights , hypothesisDistribution); vector<vector<DisambiguatedData> > topDisambiguatedSequences; for (size_t chainIndex = 0; chainIndex < bestSequences.size() ; ++chainIndex) { vector<DisambiguatedData> disambiguatedData; for (size_t tokenIndex = 0; tokenIndex < size; ++tokenIndex) { wstring& label = bestSequences[chainIndex][tokenIndex]; shared_ptr<Morphology> grammInfo = getBestGrammInfo( predisambiguated[tokenIndex], label); applyPostprocessRules(&label, grammInfo); const wstring& lemma = dictionary == 0 ? DICT_IS_NULL : *(grammInfo->lemma) == NOT_FOUND_LEMMA ? Tools::ToLower(predisambiguated[tokenIndex].content) : *(grammInfo->lemma); disambiguatedData.emplace_back( predisambiguated[tokenIndex].content , predisambiguated[tokenIndex].punctuation , predisambiguated[tokenIndex].source , predisambiguated[tokenIndex].isNextSpace , lemma , label , bestSequenceWeights[chainIndex][tokenIndex] , grammInfo->lemma_id); } topDisambiguatedSequences.push_back(std::move(disambiguatedData)); } return topDisambiguatedSequences; }
void test_lda() { printf("[test lda]\n"); double feats[3*10] = {1,2,3,4,5,6,7,8,9,3,5,7,5,3,7, 11,12,13,14,15,16,17,18,19, 13,15,17,15,13,17}; int lbls[10] = {-1, -1, 1, 1, -1, 1, 1, 1, -1, 1}; //HFMatrix<double> features(feats, 3, 10); Loader loader("data/hello_matrix"); HFMatrix<double> features(loader); //HFVector<int> labels(lbls, 10); Loader loader2("data/hello_label"); HFVector<int> labels(loader2); //Saver saver("data/hello_label"); //labels.save(saver); //Saver saver("data/hello_matrix"); //features.save(saver); LDA lda; lda.train(&features, &labels); }
void CvFAST::onNewImage() { CLOG(LTRACE) << "CvFAST::onNewImage\n"; try { // Input: a grayscale image. cv::Mat input = in_img.read(); std::vector<KeyPoint> keypoints; #if CV_VERSION_MAJOR==2 //-- Step 1: Detect the keypoints using FAST Detector. cv::FastFeatureDetector detector(m_threshold); detector.detect( input, keypoints ); #elif CV_VERSION_MAJOR==3 cv::Ptr<cv::FastFeatureDetector> fast = cv::FastFeatureDetector::create(10); fast->detect(input, keypoints); #endif // Write features to the output. Types::Features features(keypoints); out_features.write(features); } catch (...) { CLOG(LERROR) << "CvFAST::onNewImage failed\n"; } }
static void __classifier_update (std::unique_ptr<Onyx::LinearLaRank::Classifier> &classifier, const FeatureType *featuresPtr, const double *labelsPtr, const double *weightsPtr, unsigned int numSamples, unsigned int numFeatures) { for (unsigned int i = 0; i < numSamples; i++) { Eigen::Map< const Eigen::Matrix<FeatureType, Eigen::Dynamic, 1> > features(featuresPtr + i*numFeatures, numFeatures); classifier->update(features, static_cast<int>(labelsPtr[i]), weightsPtr ? static_cast<float>(weightsPtr[i]) : 1.0f); } }
// Generates random instances. // num: number of instances to be generated. // dataSize: number of features to be generated. // eSize: number of expected outputs. // strLen: length of random strings generated. // instances: input/output vector of instances void genRandInsts( const int& num, const int& dataSize, const int& eSize, const int& strLen, std::vector<Instance>& instances ){ std::shared_ptr<std::vector<std::string> > features(new std::vector<std::string>()); std::shared_ptr<std::vector<std::string> > classes(new std::vector<std::string>()); // Generate sudo names for features and classes for( int i = 0; i < dataSize; ++i){ features->push_back(randS(strLen)); } for( int i = 0; i < eSize; ++i){ classes->push_back(randS(strLen)); } // Generate instances for( int i = 0; i < num; ++i ){ // Generate sudo data for each instance std::vector<double>* data = new std::vector<double>(); std::vector<double>* expected = new std::vector<double>(); for( int j = 0; j < dataSize; ++j ){ data->push_back(randD()); } for( int j = 0; j < dataSize; ++j ){ expected->push_back(randD()); } instances.push_back( Instance( randS(strLen), data, expected, features, classes )); } }
CapsInfo CapsInfoGenerator::generateCapsInfo(const DiscoInfo& discoInfo) const { std::string serializedCaps; std::vector<DiscoInfo::Identity> identities(discoInfo.getIdentities()); std::sort(identities.begin(), identities.end()); for (const auto& identity : identities) { serializedCaps += identity.getCategory() + "/" + identity.getType() + "/" + identity.getLanguage() + "/" + identity.getName() + "<"; } std::vector<std::string> features(discoInfo.getFeatures()); std::sort(features.begin(), features.end()); for (const auto& feature : features) { serializedCaps += feature + "<"; } for (const auto& extension : discoInfo.getExtensions()) { serializedCaps += extension->getFormType() + "<"; std::vector<FormField::ref> fields(extension->getFields()); std::sort(fields.begin(), fields.end(), &compareFields); for (const auto& field : fields) { if (field->getName() == "FORM_TYPE") { continue; } serializedCaps += field->getName() + "<"; std::vector<std::string> values(field->getValues()); std::sort(values.begin(), values.end()); for (const auto& value : values) { serializedCaps += value + "<"; } } } std::string version(Base64::encode(crypto_->getSHA1Hash(createByteArray(serializedCaps)))); return CapsInfo(node_, version, "sha-1"); }
int main(int argc, char** argv){ //Reading parameters from file defined as input in the run command: Parameters param(argc, argv); srand(param.getSeed()); //Using Basic features: RedundantBPROFeatures features(¶m); //Reporting parameters read: printBasicInfo(param); ALEInterface ale(param.getDisplay()); ale.setFloat("repeat_action_probability", 0.00); ale.setInt("random_seed", param.getSeed()); ale.setFloat("frame_skip", param.getNumStepsPerAction()); ale.setInt("max_num_frames_per_episode", param.getEpisodeLength()); ale.loadROM(param.getRomPath().c_str()); //Instantiating the learning algorithm: SarsaLearner sarsaLearner(ale, &features, ¶m,param.getSeed()); //Learn a policy: sarsaLearner.learnPolicy(ale, &features); printf("\n\n== Evaluation without Learning == \n\n"); sarsaLearner.evaluatePolicy(ale, &features); return 0; }
std::vector< float > Saliency::distributionFilter( const std::vector< SuperpixelStatistic >& stat ) const { const int N = stat.size(); // Setup the data and features std::vector< Vec3f > features( stat.size() ); Mat_<float> data( stat.size(), 4 ); for( int i=0; i<N; i++ ) { //features[i] = stat[i].mean_color_ / settings_.sigma_c_; { Vec3f x = stat[i].mean_color_; x[0] = x[0]/settings_.sigma_c_; x[1] = x[1]/settings_.sigma_c_; x[2] = x[2]/settings_.sigma_c_; features[i] = x; } Vec2f p = stat[i].mean_position_; data(i,0) = 1; data(i,1) = p[0]; data(i,2) = p[1]; data(i,3) = p.dot(p); } // Filter Filter filter( (const float*)features.data(), N, 3 ); filter.filter( data.ptr<float>(), data.ptr<float>(), 4 ); // Compute the uniqueness std::vector< float > r( N ); for( int i=0; i<N; i++ ) r[i] = data(i,3) / data(i,0) - ( data(i,1) * data(i,1) + data(i,2) * data(i,2) ) / ( data(i,0) * data(i,0) ); normVec( r ); return r; }
void FAST::detect( FeatureSet& featureset, const ImagePyramid& imgpyr ) { if( imgpyr[ 0 ].format() != IFormat::GRAY_UINT8 ) throw CVTException( "Input Image format must be GRAY_UINT8" ); for( size_t coctave = 0; coctave < imgpyr.octaves(); coctave++ ) { float cscale = Math::pow( imgpyr.scaleFactor(), -( float )coctave ); FeatureSetWrapper features( featureset, cscale, coctave ); switch ( _fastSize ) { case SEGMENT_9: detect9( imgpyr[ coctave ], _threshold, features, _border ); break; case SEGMENT_10: detect10( imgpyr[ coctave ], _threshold, features, _border ); break; case SEGMENT_11: detect11( imgpyr[ coctave ], _threshold, features, _border ); break; case SEGMENT_12: detect12( imgpyr[ coctave ], _threshold, features, _border ); break; default: throw CVTException( "Unkown FAST size" ); break; } } }
WirelessTypes::StorageLimitMode WirelessNode_Impl::getStorageLimitMode() const { if(!features().supportsLoggedData()) { throw Error_NotSupported("Datalogging is not supported by this Node."); } if(!features().supportsStorageLimitModeConfig()) { //legacy nodes don't support this eeprom, but are //hard coded to stop when the storage limit is reached. return WirelessTypes::storageLimit_stop; } return m_eepromHelper->read_storageLimitMode(); }
BaseMatInstance* InstancingMaterialHook::getInstancingMat( BaseMatInstance *matInst ) { PROFILE_SCOPE( InstancingMaterialHook_GetInstancingMat ); if ( matInst == NULL ) return NULL; InstancingMaterialHook *hook = matInst->getHook<InstancingMaterialHook>(); if ( hook == NULL ) { hook = new InstancingMaterialHook(); matInst->addHook( hook ); BaseMatInstance *instMat = matInst->getMaterial()->createMatInstance(); FeatureSet features( matInst->getRequestedFeatures() ); features.addFeature( MFT_UseInstancing ); if ( !instMat->init( features, matInst->getVertexFormat() ) ) SAFE_DELETE( instMat ); hook->mMatInst = instMat; } return hook->mMatInst; }
void CvBRISK::onNewImage() { LOG(LTRACE) << "CvBRISK::onNewImage\n"; try { // objectImg: a grayscale image. cv::Mat objectImg = in_img.read(); //-- Step 1: Detect the keypoints using Brisk Detector. //cv::BriskFeatureDetector detector;//(thresh,3,1.0f); cv::FeatureDetector * detector = new cv::BRISK(thresh,3,1.0f); std::vector<cv::KeyPoint> keypoints; detector->detect( objectImg, keypoints ); //-- Step 2: Calculate descriptors (feature vectors). //cv::BriskDescriptorExtractor extractor; cv::DescriptorExtractor * extractor = new cv::BRISK(); cv::Mat descriptors; extractor->compute( objectImg, keypoints, descriptors); // Write features to the output. Types::Features features(keypoints); out_features.write(features); // Write descriptors to the output. out_descriptors.write(descriptors); } catch (...) { LOG(LERROR) << "CvBRISK::onNewImage failed\n"; } }
void readTokenMatrix(Dataset& data, const char* filename) { std::vector<string> lines; loadFile(lines, filename); assert(lines.size() > 1); std::vector<int> counts(2); tokenizeLineIntoIntVector(lines[1], counts); assert(counts.size() == 2); //cout << "Found: " << counts[0] << " and " << counts[1] << endl; data.numDocs = counts[0]; data.numTokens = counts[1]; vec trainClasses(data.numDocs); mat features(data.numDocs, data.numTokens); rowvec row(data.numTokens); for(uint i = 3; i < data.numDocs + 3; i++) { std::vector<double> tokens(getNumTokens(lines[i])); tokenizeLineIntoDoubleVector(lines[i], tokens); trainClasses(i-3) = tokens[0]; //cout << "class[" << tokens[0] << "]"; row.zeros(); int cumsum = 0; for(uint j = 1; j < tokens.size() - 1; j+=2) { cumsum += tokens[j]; //cout << "cumsum[" << cumsum << "]token[" << tokens[j+1] << "]" << flush ; row[cumsum] = tokens[j+1]; } Matrix::setMatrixRowToVector(features, i-3 ,row); } data.classifications = trainClasses; data.features = features; }
void FragSpectrumScanDatabase::printTabFss(std::auto_ptr< ::percolatorInNs::fragSpectrumScan> fss, ostream &tabOutputStream) { int label = 0; BOOST_FOREACH (const ::percolatorInNs::peptideSpectrumMatch &psm, fss->peptideSpectrumMatch()) { if (psm.isDecoy()) { label = -1; } else { label = 1; } tabOutputStream << psm.id() << '\t' << label << '\t' << fss->scanNumber(); tabOutputStream << '\t' << psm.experimentalMass() << '\t' << psm.calculatedMass(); if (psm.observedTime().present()) { tabOutputStream << '\t' << psm.observedTime() << '\t' << MassHandler::massDiff(psm.experimentalMass() ,psm.calculatedMass(),psm.chargeState()); } BOOST_FOREACH (const double feature, psm.features().feature()) { tabOutputStream << '\t' << feature; } bool isFirst = true; BOOST_FOREACH (const ::percolatorInNs::occurence & oc, psm.occurence() ) { // adding n-term and c-term residues to peptide //NOTE the residues for the peptide in the PSMs are always the same for every protein if (isFirst) { tabOutputStream << '\t' << oc.flankN() << "." << decoratePeptide(psm.peptide()) << "." << oc.flankC(); isFirst = false; } std::string proteinId = oc.proteinId(); std::replace(proteinId.begin(), proteinId.end(), ' ', '-'); tabOutputStream << '\t' << proteinId; } tabOutputStream << std::endl; } }