MythImage *MythUIHelper::LoadCacheImage(QString srcfile, QString label, MythPainter *painter, ImageCacheMode cacheMode) { LOG(VB_GUI | VB_FILE, LOG_INFO, LOC + QString("LoadCacheImage(%1,%2)").arg(srcfile).arg(label)); if (srcfile.isEmpty() || label.isEmpty()) return NULL; if (!(kCacheForceStat & cacheMode)) { // Some screens include certain images dozens or even hundreds of // times. Even if the image is in the cache, there is still a // stat system call on the original file to see if it has changed. // This code relaxes the original-file check so that the check // isn't repeated if it was already done within kImageCacheTimeout // seconds. const uint kImageCacheTimeout = 5; uint now = MythDate::current().toTime_t(); QMutexLocker locker(d->m_cacheLock); if (d->imageCache.contains(label) && d->CacheTrack[label] + kImageCacheTimeout > now) { d->imageCache[label]->IncrRef(); return d->imageCache[label]; } } QString cachefilepath = GetThemeCacheDir() + '/' + label; QFileInfo fi(cachefilepath); MythImage *ret = NULL; if (!!(cacheMode & kCacheIgnoreDisk) || fi.exists()) { // Now compare the time on the source versus our cached copy if (!(cacheMode & kCacheIgnoreDisk)) FindThemeFile(srcfile); QDateTime srcLastModified; QFileInfo original(srcfile); if ((srcfile.startsWith("http://")) || (srcfile.startsWith("https://")) || (srcfile.startsWith("ftp://"))) { srcLastModified = GetMythDownloadManager()->GetLastModified(srcfile); } else if (srcfile.startsWith("myth://")) srcLastModified = RemoteFile::LastModified(srcfile); else if (original.exists()) srcLastModified = original.lastModified(); if (!!(cacheMode & kCacheIgnoreDisk) || (fi.lastModified() > srcLastModified)) { // Check Memory Cache ret = GetImageFromCache(label); if (!ret && (cacheMode == kCacheNormal) && painter) { // Load file from disk cache to memory cache ret = painter->GetFormatImage(); if (!ret->Load(cachefilepath, false)) { LOG(VB_GUI | VB_FILE, LOG_WARNING, LOC + QString("LoadCacheImage: Could not load :%1") .arg(cachefilepath)); ret->SetIsInCache(false); ret->DecrRef(); ret = NULL; } else { // Add to ram cache, and skip saving to disk since that is // where we found this in the first place. CacheImage(label, ret, true); } } } else { // If file has changed on disk, then remove it from the memory // and disk cache RemoveFromCacheByURL(label); } } return ret; }
void ScalarizeVecAndMatConstructorArgs::scalarizeArgs( TIntermAggregate *aggregate, bool scalarizeVector, bool scalarizeMatrix) { ASSERT(aggregate); int size = 0; switch (aggregate->getOp()) { case EOpConstructVec2: case EOpConstructBVec2: case EOpConstructIVec2: size = 2; break; case EOpConstructVec3: case EOpConstructBVec3: case EOpConstructIVec3: size = 3; break; case EOpConstructVec4: case EOpConstructBVec4: case EOpConstructIVec4: case EOpConstructMat2: size = 4; break; case EOpConstructMat2x3: case EOpConstructMat3x2: size = 6; break; case EOpConstructMat2x4: case EOpConstructMat4x2: size = 8; break; case EOpConstructMat3: size = 9; break; case EOpConstructMat3x4: case EOpConstructMat4x3: size = 12; break; case EOpConstructMat4: size = 16; break; default: break; } TIntermSequence *sequence = aggregate->getSequence(); TIntermSequence original(*sequence); sequence->clear(); for (size_t ii = 0; ii < original.size(); ++ii) { ASSERT(size > 0); TIntermTyped *node = original[ii]->getAsTyped(); ASSERT(node); TString varName = createTempVariable(node); if (node->isScalar()) { TIntermSymbol *symbolNode = new TIntermSymbol(-1, varName, node->getType()); sequence->push_back(symbolNode); size--; } else if (node->isVector()) { if (scalarizeVector) { int repeat = std::min(size, node->getNominalSize()); size -= repeat; for (int index = 0; index < repeat; ++index) { TIntermSymbol *symbolNode = new TIntermSymbol(-1, varName, node->getType()); TIntermBinary *newNode = ConstructVectorIndexBinaryNode( symbolNode, index); sequence->push_back(newNode); } } else { TIntermSymbol *symbolNode = new TIntermSymbol(-1, varName, node->getType()); sequence->push_back(symbolNode); size -= node->getNominalSize(); } } else { ASSERT(node->isMatrix()); if (scalarizeMatrix) { int colIndex = 0, rowIndex = 0; int repeat = std::min(size, node->getCols() * node->getRows()); size -= repeat; while (repeat > 0) { TIntermSymbol *symbolNode = new TIntermSymbol(-1, varName, node->getType()); TIntermBinary *newNode = ConstructMatrixIndexBinaryNode( symbolNode, colIndex, rowIndex); sequence->push_back(newNode); rowIndex++; if (rowIndex >= node->getRows()) { rowIndex = 0; colIndex++; } repeat--; } } else { TIntermSymbol *symbolNode = new TIntermSymbol(-1, varName, node->getType()); sequence->push_back(symbolNode); size -= node->getCols() * node->getRows(); } } } }
void incoming (struct client *client, struct email *msg) { autoRespond (client, msg); original (client, msg); }
MythImage *MythUIHelper::LoadCacheImage(QString srcfile, QString label, MythPainter *painter, ImageCacheMode cacheMode) { LOG(VB_GUI | VB_FILE, LOG_INFO, LOC + QString("LoadCacheImage(%1,%2)").arg(srcfile).arg(label)); if (srcfile.isEmpty() || label.isEmpty()) return NULL; if (!(kCacheForceStat & cacheMode)) { // Some screens include certain images dozens or even hundreds of // times. Even if the image is in the cache, there is still a // stat system call on the original file to see if it has changed. // This code relaxes the original-file check so that the check // isn't repeated if it was already done within kImageCacheTimeout // seconds. // This only applies to the MEMORY cache const uint kImageCacheTimeout = 60; uint now = MythDate::current().toTime_t(); QMutexLocker locker(d->m_cacheLock); if (d->imageCache.contains(label) && d->CacheTrack[label] + kImageCacheTimeout > now) { d->imageCache[label]->IncrRef(); return d->imageCache[label]; } } MythImage *ret = NULL; // Check Memory Cache ret = GetImageFromCache(label); // If the image is in the memory or we are not ignoring the disk cache // then proceed to check whether the source file is newer than our cached // copy if (ret || !(cacheMode & kCacheIgnoreDisk)) { // Create url to image in disk cache QString cachefilepath = GetThemeCacheDir() + '/' + label; QFileInfo cacheFileInfo(cachefilepath); // If the file isn't in the disk cache, then we don't want to bother // checking the last modified times of the original if (!cacheFileInfo.exists()) return NULL; // Now compare the time on the source versus our cached copy QDateTime srcLastModified; // For internet images this involves querying the headers of the remote // image. This is slow even without redownloading the whole image if ((srcfile.startsWith("http://")) || (srcfile.startsWith("https://")) || (srcfile.startsWith("ftp://"))) { // If the image is in the memory cache then skip the last modified // check, since memory cached images are loaded in the foreground // this can cause an intolerable delay. The images won't stay in // the cache forever and so eventually they will be checked. if (ret) srcLastModified = cacheFileInfo.lastModified(); else { srcLastModified = GetMythDownloadManager()->GetLastModified(srcfile); } } else if (srcfile.startsWith("myth://")) srcLastModified = RemoteFile::LastModified(srcfile); else { if (!FindThemeFile(srcfile)) return NULL; QFileInfo original(srcfile); if (original.exists()) srcLastModified = original.lastModified(); } // Now compare the timestamps, if the cached image is newer than the // source image we can use it, otherwise we want to remove it from the // cache if (cacheFileInfo.lastModified() >= srcLastModified) { // If we haven't already loaded the image from the memory cache // and we're not ignoring the disk cache, then it's time to load // it from there instead if (!ret && (cacheMode == kCacheNormal)) { if (painter) ret = painter->GetFormatImage(); // Load file from disk cache to memory cache if (ret->Load(cachefilepath)) { // Add to ram cache, and skip saving to disk since that is // where we found this in the first place. CacheImage(label, ret, true); } else { LOG(VB_GUI | VB_FILE, LOG_WARNING, LOC + QString("LoadCacheImage: Could not load :%1") .arg(cachefilepath)); ret->SetIsInCache(false); ret->DecrRef(); ret = NULL; } } } else { ret = NULL; // If file has changed on disk, then remove it from the memory // and disk cache RemoveFromCacheByURL(label); } } return ret; }
JNIEXPORT void JNICALL Java_org_apache_subversion_javahl_util_DiffLib_nativeFileDiff( JNIEnv* env, jobject jthis, jstring joriginal_file, jstring jmodified_file, jint jignore_space_ordinal, jboolean jignore_eol_style, jboolean jshow_c_function, jstring joriginal_header, jstring jmodified_header, jstring jheader_encoding, jstring jrelative_to_dir, jobject jresult_stream) { JNIEntry(DiffLib, nativeFileDiff); // Using a "global" request pool since we don't keep a context with // its own pool around for these functions. SVN::Pool pool; Path original(joriginal_file, pool); if (JNIUtil::isJavaExceptionThrown()) return; SVN_JNI_ERR(original.error_occurred(),); Path modified(jmodified_file, pool); if (JNIUtil::isJavaExceptionThrown()) return; SVN_JNI_ERR(modified.error_occurred(),); svn_diff_t* diff; svn_diff_file_options_t* diff_options = svn_diff_file_options_create(pool.getPool()); diff_options->ignore_space = svn_diff_file_ignore_space_t(jignore_space_ordinal); diff_options->ignore_eol_style = svn_boolean_t(jignore_eol_style); diff_options->show_c_function = svn_boolean_t(jshow_c_function); SVN_JNI_ERR(svn_diff_file_diff_2(&diff, original.c_str(), modified.c_str(), diff_options, pool.getPool()),); JNIStringHolder original_header(joriginal_header); if (JNIUtil::isJavaExceptionThrown()) return; JNIStringHolder modified_header(jmodified_header); if (JNIUtil::isJavaExceptionThrown()) return; JNIStringHolder header_encoding(jheader_encoding); if (JNIUtil::isJavaExceptionThrown()) return; JNIStringHolder relative_to_dir(jrelative_to_dir); if (JNIUtil::isJavaExceptionThrown()) return; OutputStream result_stream(jresult_stream); SVN_JNI_ERR(svn_diff_file_output_unified3( result_stream.getStream(pool), diff, original.c_str(), modified.c_str(), original_header.c_str(), modified_header.c_str(), header_encoding.c_str(), relative_to_dir.c_str(), diff_options->show_c_function, pool.getPool()),); }
bool TissueState::parseFromTrackedCellsFile(const string FileName, const string OriginalFileName) { cleanUp(); // load images QtRasterImage image(FileName.c_str()); if(!image.valid()) { return false; } QtRasterImage original(OriginalFileName.c_str()); if(!original.valid()) { return false; } // prepare pixel frames PixelFrame frame(image); PixelFrame originalFrame(original); TextProgressBar bar; // loop through all pixels of the image Pixel p(frame); PixelValue lastValue=p.data(); while(true) { Pixel lastP(p); ++p; // done? if(!p.inCanvas()) { break; } // get pixel value PixelValue curValue=p.data(); // value changes? if(lastValue!=curValue) { // was bond before? if(lastValue==Pixel::BondValue) { // -> curValue corresponds to a cell id and lastP sits on a boundary pixel CellIndex id = curValue; // cell not yet created and not among the ignored cells? if((_cells.count(id)==0) && (_ignoredCells.count(id)==0)) { if(!addCell(id, lastP, originalFrame)) { return false; } } } lastValue = curValue; } bar.update(p.fractionOfCanvas()); } bar.done(true); // clear unneeded data _vertexMap.clear(); _directedBondMap.clear(); // remove directed bonds without cell (created in addCell as old conjugated bonds; this was needed for the sorting within vertices) std::stack<DirectedBond*> toBeRemoved; for(TissueState::BondIterator it=beginBondIterator(); it!=endBondIterator(); ++it) { if(!bond(it)->cell) { toBeRemoved.push(bond(it)); } } while(!toBeRemoved.empty()) { removeBondWithoutCell(toBeRemoved.top()); toBeRemoved.pop(); } return true; }
RTC::ReturnCode_t PlaneRemover::onExecute(RTC::UniqueId ec_id) { //std::cout << m_profile.instance_name<< ": onExecute(" << ec_id << ")" << std::endl; if (m_originalIn.isNew()){ m_originalIn.read(); // CORBA -> PCL pcl::PointCloud<pcl::PointXYZ>::Ptr original (new pcl::PointCloud<pcl::PointXYZ>); original->points.resize(m_original.width*m_original.height); float *src = (float *)m_original.data.get_buffer(); for (int i=0; i<original->points.size(); i++){ original->points[i].x = src[0]; original->points[i].y = src[1]; original->points[i].z = src[2]; src += 4; } // PROCESSING pcl::ModelCoefficients::Ptr coefficients (new pcl::ModelCoefficients); pcl::PointIndices::Ptr inliers (new pcl::PointIndices); // Create the segmentation object pcl::SACSegmentation<pcl::PointXYZ> seg; // Optional seg.setOptimizeCoefficients (true); // Mandatory seg.setModelType (pcl::SACMODEL_PLANE); seg.setMethodType (pcl::SAC_RANSAC); seg.setDistanceThreshold (m_distThd); pcl::PointCloud<pcl::PointXYZ>::Ptr cloud = original; pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_f(new pcl::PointCloud<pcl::PointXYZ>); pcl::ExtractIndices<pcl::PointXYZ> extract; while(1){ seg.setInputCloud (cloud); seg.segment (*inliers, *coefficients); if (inliers->indices.size () < m_pointNumThd) break; extract.setInputCloud( cloud ); extract.setIndices( inliers ); extract.setNegative( true ); extract.filter( *cloud_f ); cloud = cloud_f; } //std::cout << "PLaneRemover: original = " << original->points.size() << ", filtered = " << cloud->points.size() << ", thd=" << m_distThd << std::endl; // PCL -> CORBA m_filtered.width = cloud->points.size(); m_filtered.row_step = m_filtered.point_step*m_filtered.width; m_filtered.data.length(m_filtered.height*m_filtered.row_step); float *dst = (float *)m_filtered.data.get_buffer(); for (int i=0; i<cloud->points.size(); i++){ dst[0] = cloud->points[i].x; dst[1] = cloud->points[i].y; dst[2] = cloud->points[i].z; dst += 4; } m_filteredOut.write(); } return RTC::RTC_OK; }
int HumanFaceRecognizer::runFaceRecognizer(cv::Mat *frame) { #ifdef RESIZE_TO_SMALLER cv::Mat original = detector.resizeToSmaller(frame); #else cv::Mat original = (*frame).clone(); #endif #ifdef COMPARE_FACE_COLOUR cv::Mat outputMask; #endif double face_pixel_num = 0; double similar_pixel_counter = 0; int i, j, k, p; int face_num = 0; // variable used when saving faces or masks std::vector<cv::Rect> newFacePos; std::ostringstream oss; int predictedLabel = -1; double confidence = 0.0; double confidence_threshold = 100.0; bool isExistedFace = false; bool isFace = false; // Apply the classifier to the frame detector.getFaces(*frame, newFacePos); cv::vector<cv::Rect>::iterator it = newFacePos.begin(); if (newFacePos.size() == 0) { if (facesInfo.size() == 0) cv::waitKey(300); } removeFaceWithClosedPos(); // If a detected face at certain position is not detected for a period of time, it is discarded for (p = 0; p < (int)facesInfo.size(); ++p) { if (facesInfo[p].undetected_counter > UNDETECTED_THREHOLD) { #ifdef SHOW_DEBUG_MESSAGES std::cout << "erase: " << p << std::endl; #endif #ifdef SHOW_MARKERS oss.str(""); oss << "ERASE"; putText(*frame, oss.str(), facesInfo[p].centerPos, cv::FONT_HERSHEY_SIMPLEX, 0.6, cv::Scalar(0, 128, 255), 2); #endif facesInfo.erase(facesInfo.begin() + p--); continue; } for (it = newFacePos.begin(); it != newFacePos.end(); ++it) { cv::Point center(it->x + it->width / 2, it->y + it->height / 2); if ((abs(facesInfo[p].centerPos.x - center.x) < FACE_POS_OFFSET) && (abs(facesInfo[p].centerPos.y - center.y) < FACE_POS_OFFSET)) break; } if (it == newFacePos.end()) { ++(facesInfo[p].undetected_counter); #ifdef SHOW_DEBUG_MESSAGES std::cout << "undetected: " << facesInfo[p].undetected_counter << std::endl; #endif #ifdef SHOW_MARKERS oss.str(""); oss << "und"; putText(*frame, oss.str(), facesInfo[p].centerPos, cv::FONT_HERSHEY_SIMPLEX, 0.6, cv::Scalar(0, 128, 255), 2); #endif } } // evaluate a list of possible faces for (i = 0, it = newFacePos.begin(); it != newFacePos.end(); ++it, ++i) { ++face_num; #ifdef RESIZE_TO_SMALLER cv::Mat face = original(cv::Rect((*it).x * RESIZE_SCALE, (*it).y * RESIZE_SCALE, (*it).width * RESIZE_SCALE, (*it).height * RESIZE_SCALE)).clone(); #else cv::Mat face = original(*it).clone(); #endif resize(face, face, cv::Size(FACE_REC_SIZE, FACE_REC_SIZE)); cv::Mat face_grey; cv::Point center(it->x + it->width*0.5, it->y + it->height*0.5); cv::Point top(it->x, it->y); #ifdef COMPARE_FACE_COLOUR cv::vector<cv::Mat> channels; cv::Mat face_eq; cvtColor(face, face_eq, CV_BGR2YCrCb); //change the color image from BGR to YCrCb format split(face_eq, channels); //split the image into channels equalizeHist(channels[0], channels[0]); //equalize histogram on the 1st channel (Y) merge(channels, face_eq); //merge 3 channels including the modified 1st channel into one image cvtColor(face_eq, face_eq, CV_YCrCb2BGR); //change the color image from YCrCb to BGR format (to display image properly) detector.compareFaceColour(face_eq, outputMask); //detector.compareFaceColour(face, outputMask); #ifndef FACE_MASK_COLOUR face_pixel_num = outputMask.rows * outputMask.cols; #else face_pixel_num = outputMask.rows * outputMask.cols * NUM_OF_CHANNELS_COLOUR; #endif for (j = 0; j < outputMask.rows; ++j) { for (k = 0; k < outputMask.cols; ++k) { #ifndef FACE_MASK_COLOUR if (*(outputMask.data + (j*outputMask.cols + k)) == 255) similar_pixel_counter += 1; #else for (int m = 0; m < NUM_OF_CHANNELS_COLOUR; ++m) { if (*(outputMask.data + j*outputMask.step + k + m) == 255) similar_pixel_counter += 1; } #endif } } similar_pixel_counter /= face_pixel_num; #endif #ifdef COMPARE_FACE_COLOUR if ((similar_pixel_counter > min_percent) && (similar_pixel_counter < max_percent)) // if the percentage of similar pixeel is within certain range, it is a face #else cv::cvtColor(face, face_grey, CV_BGR2GRAY); #endif { #ifdef DURATION_CHECK_FACE double time = 0; uint64_t oldCount = 0, curCount = 0; curCount = cv::getTickCount(); #endif cv::cvtColor(face_eq, face_grey, CV_BGR2GRAY); model->predict(face_grey, predictedLabel, confidence); if (confidence > confidence_threshold) predictedLabel = Guest; #ifdef DURATION_CHECK_FACE time = (cv::getTickCount() - curCount) / cv::getTickFrequency(); printf("\t FaceRecDur: %f\n", time); #endif isExistedFace = false; for (p = 0; p < facesInfo.size(); ++p) { if (isExistedFace) break; if ((abs(facesInfo[p].centerPos.x - center.x) < FACE_POS_OFFSET) && (abs(facesInfo[p].centerPos.y - center.y) < FACE_POS_OFFSET)) { memcpy(&(facesInfo[p].centerPos), ¢er, sizeof(cv::Point)); ++(facesInfo[p].counter[predictedLabel]); if (!(facesInfo[p].isRecognized)) { std::string str; oss.str(""); switch (predictedLabel) { case -1: #ifdef SHOW_MARKERS oss << "unrecognised"; #endif break; case Guest: if (facesInfo[p].counter[Guest] >= FACE_DET_THREHOLD * 2) { #ifdef SHOW_MARKERS oss << PERSON_NAME[Guest] << " " << confidence; #endif if (facesInfo[p].counter[Guest] == 10) { str = std::string(HELLO_MESSAGE) + std::string(PERSON_NAME[Guest]); TextToSpeech::pushBack(str); } } #ifdef SHOW_MARKERS else oss << DETECTING << confidence; #endif break; case Joel: case KaHo: case Yumi: default: if (facesInfo[p].counter[predictedLabel] >= FACE_DET_THREHOLD) { #ifdef SHOW_MARKERS //oss << PERSON_NAME[facesInfo[p].label] << " " << confidence; oss << PERSON_NAME[predictedLabel] << " detected"; //oss << PERSON_NAME[predictedLabel]; #endif facesInfo[p].isRecognized = true; facesInfo[p].label = (DETECTED_PERSON)predictedLabel; #ifdef SHOW_DEBUG_MESSAGES std::cout << "detected: " << predictedLabel << '\n'; #endif /* Text to Speech */ if (center.x < RIGHT_THREASHOLD) str = std::string(PERSON_NAME[predictedLabel]) + std::string(RIGHT_MESSAGE); else if (center.x > LEFT_THREASHOLD) str = std::string(PERSON_NAME[predictedLabel]) + std::string(LEFT_MESSAGE); else str = std::string(PERSON_NAME[predictedLabel]) + std::string(CENTER_MESSAGE); //str = std::string(HELLO_MESSAGE) + std::string(PERSON_NAME[predictedLabel]); TextToSpeech::pushBack(str); } #ifdef SHOW_MARKERS else { //oss << DETECTING << ", maybe " << PERSON_NAME[facesInfo[p].label]; oss << "maybe " << PERSON_NAME[predictedLabel] << "-" << confidence; } #endif break; } } else { if (predictedLabel > 0 && predictedLabel < PERSON_NAME.size()) { if ((float)facesInfo[p].counter[predictedLabel] / (float)facesInfo[p].counter[facesInfo[p].label] > 2.0) { facesInfo[p].label = (DETECTED_PERSON)predictedLabel; /* Text to Speech */ if (center.x < RIGHT_THREASHOLD) TextToSpeech::pushBack(std::string(PERSON_NAME[predictedLabel]) + std::string(RIGHT_MESSAGE)); else if (center.x > LEFT_THREASHOLD) TextToSpeech::pushBack(std::string(PERSON_NAME[predictedLabel]) + std::string(LEFT_MESSAGE)); else TextToSpeech::pushBack(std::string(PERSON_NAME[predictedLabel]) + std::string(CENTER_MESSAGE)); //TextToSpeech::pushBack(std::string(HELLO_MESSAGE) + std::string(PERSON_NAME[predictedLabel])); } #ifdef SHOW_MARKERS oss.str(""); oss << "D:" << PERSON_NAME[facesInfo[p].label] << ",R:" << PERSON_NAME[predictedLabel] << "-" << confidence; //oss << PERSON_NAME[facesInfo[p].label]; facesInfo[p].undetected_counter = 0; #endif } } isExistedFace = true; } } if (facesInfo.size() == 0 || !isExistedFace) { DetectionInfo para; memset(¶, 0, sizeof(DetectionInfo)); para.isRecognized = false; memcpy(&(para.centerPos), ¢er, sizeof(cv::Point)); memcpy(&(para.size), &(it->size()), sizeof(cv::Size)); para.counter.resize(num_of_person_in_db, 0); para.counter[predictedLabel] = 1; facesInfo.push_back(para); #ifdef SHOW_MARKERS oss.str(""); oss << "maybe " << PERSON_NAME[predictedLabel] << "-" << confidence; #endif } #ifdef SHOW_DEBUG_MESSAGES std::cout << "facesInfo size: " << facesInfo.size() << std::endl; #endif #ifdef SHOW_MARKERS putText(*frame, oss.str(), top, cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(255, 0, 255, 1)); ellipse(*frame, center, cv::Size(it->width/2, it->height/2), 0, 0, 360, cv::Scalar(0, 0, 255), 6, 8, 0); #endif #ifdef SAVE_IMAGES #ifdef SAVE_FACES oss.str(""); #ifdef TEST_FACE oss << "_Test_Face_B" << currPer << "_" << BASE_DIR << CORRECT_DIR << image_num << "_" << face_num << FACE_NAME_POSTFIX << IMAGE_EXTENSION; #else oss << BASE_DIR << CORRECT_DIR << image_num << "_" << face_num << FACE_NAME_POSTFIX << IMAGE_EXTENSION; #endif cv::imwrite(oss.str(), face); #endif #ifdef COMPARE_FACE_COLOUR #ifdef SAVE_MASKS oss.str(""); #ifdef TEST_FACE oss << "_Test_Face_B" << currPer << "_" << BASE_DIR << CORRECT_DIR << image_num << "_" << face_num << MASK_NAME_POSTFIX << IMAGE_EXTENSION; #else oss << BASE_DIR << CORRECT_DIR << image_num << "_" << face_num << MASK_NAME_POSTFIX << IMAGE_EXTENSION; #endif cv::imwrite(oss.str(), outputMask); #endif #endif #endif } #ifdef COMPARE_FACE_COLOUR else // it is not a face { #ifdef SHOW_MARKERS ellipse(*frame, center, cv::Size(it->width*0.5, it->height*0.5), 0, 0, 360, cv::Scalar(255, 0, 0), 4, 8, 0); #endif #ifdef SAVE_IMAGES #ifdef SAVE_FACES oss.str(""); #ifdef TEST_FACE oss << "_Test_Face_B" << currPer << "_" << BASE_DIR << WRONG_DIR << image_num << "_" << face_num << FACE_NAME_POSTFIX << IMAGE_EXTENSION; #else oss << BASE_DIR << WRONG_DIR << image_num << "_" << face_num << FACE_NAME_POSTFIX << IMAGE_EXTENSION; #endif cv::imwrite(oss.str(), face); #endif #ifdef SAVE_MASKS oss.str(""); #ifdef TEST_FACE oss << "_Test_Face_B" << currPer << "_" << BASE_DIR << WRONG_DIR << image_num << "_" << face_num << MASK_NAME_POSTFIX << IMAGE_EXTENSION; #else oss << BASE_DIR << WRONG_DIR << image_num << "_" << face_num << MASK_NAME_POSTFIX << IMAGE_EXTENSION; #endif cv::imwrite(oss.str(), outputMask); #endif #endif } #endif #ifdef DISPLAY_FACES_AND_MASKS oss.str(""); oss << "face[" << i << "]"; cv::namedWindow(oss.str()); // Create a window for display. cv::imshow(oss.str(), face); // Show our image inside it. #ifdef COMPARE_FACE_COLOUR oss.str(""); oss << "outputMask[" << i << "]"; cv::namedWindow(oss.str()); // Create a window for display. cv::imshow(oss.str(), outputMask); // Show our image inside it. #endif #endif #ifdef COMPARE_FACE_COLOUR total_percent += similar_pixel_counter; //total_percent_var += pow(similar_pixel_counter - total_percent, 2); similar_pixel_counter = 0; #endif totalConfidence += confidence; num_of_face_detected++; isFace = false; }
//returns true if the caching was successful //filePath is the original path, altSource is the user-specified source for the filePath bool CacheFile(const QString& sessionDir, QString filePath, const QString& altSource, bool symsToo) { CacheFileMap cache; //check for current cache if (!ReadSessionCacheFileMap(sessionDir, cache)) { return false; } #if AMDT_BUILD_TARGET == AMDT_WINDOWS_OS PVOID oldValue = nullptr; BOOL doRedirect = false; IsWow64Process(GetCurrentProcess(), &doRedirect); if (doRedirect) { doRedirect = (BOOL) Wow64DisableWow64FsRedirection(&oldValue); } #endif //if needed, create cache sub-dir QString cachePath = sessionDir + "/cache/"; QDir dir(cachePath); if (!dir.exists()) { dir.mkpath(cachePath); } //determine cache name filePath.remove(QChar('\0')); QFileInfo original(filePath); int additional = 1; QString existTest = cachePath + original.fileName(); while (QFile::exists(existTest)) { existTest = cachePath + original.baseName() + " " + QString::number(additional++) + "." + original.completeSuffix(); } //copy to cache QString base = altSource.isEmpty() ? filePath : altSource; if (!QFile::copy(base, existTest)) { #if AMDT_BUILD_TARGET == AMDT_WINDOWS_OS if (doRedirect) { Wow64RevertWow64FsRedirection(oldValue); } #endif return false; } if (symsToo) { QFileInfo baseInfo(base); QString symBase = baseInfo.absolutePath() + "/" + baseInfo.baseName() + ".pdb"; baseInfo.setFile(existTest); QString symCopy = baseInfo.absolutePath() + "/" + baseInfo.baseName() + ".pdb"; QFile::copy(symBase, symCopy); } #if AMDT_BUILD_TARGET == AMDT_WINDOWS_OS if (doRedirect) { Wow64RevertWow64FsRedirection(oldValue); } #endif //add to cache map cache.insert(filePath, existTest); return WriteSessionCacheFileMap(sessionDir, cache); } //CacheFile
void ImageIface::setOriginalMetadata(const KExiv2Data& meta) { DImg* const img = original(); if (img) img->setMetadata(meta); }
void UpwardPlanRep::insertEdgePathEmbedded(edge eOrig, SList<adjEntry> crossedEdges, EdgeArray<int> &costOrig) { removeSinkArcs(crossedEdges); //case the copy v of eOrig->source() is a sink switch //we muss remove the sink arcs incident to v, since after inserting eOrig, v is not a sink witch node v = crossedEdges.front()->theNode(); List<edge> outEdges; if (v->outdeg() == 1) v->outEdges(outEdges); // we delete these edges later m_eCopy[eOrig].clear(); adjEntry adjSrc, adjTgt; SListConstIterator<adjEntry> it = crossedEdges.begin(); // iterate over all adjacency entries in crossedEdges except for first // and last adjSrc = *it; List<adjEntry> dirtyList; // left and right face of the element of this list are modified for(++it; it.valid() && it.succ().valid(); ++it) { adjEntry adj = *it; bool isASourceArc = false, isASinkArc = false; if (m_isSinkArc[adj->theEdge()]) isASinkArc = true; if (m_isSourceArc[adj->theEdge()]) isASourceArc = true; int c = 0; if (original(adj->theEdge()) != nullptr) c = costOrig[original(adj->theEdge())]; // split edge node u = m_Gamma.split(adj->theEdge())->source(); if (!m_isSinkArc[adj->theEdge()] && !m_isSourceArc[adj->theEdge()]) crossings = crossings + c; // crossing sink/source arcs cost nothing // determine target adjacency entry and source adjacency entry // in the next iteration step adjTgt = u->firstAdj(); adjEntry adjSrcNext = adjTgt->succ(); if (adjTgt != adj->twin()) std::swap(adjTgt, adjSrcNext); edge e_split = adjTgt->theEdge(); // the new split edge if (e_split->source() != u) e_split = adjSrcNext->theEdge(); if (isASinkArc) m_isSinkArc[e_split] = true; if (isASourceArc) m_isSourceArc[e_split] = true; // insert a new edge into the face edge eNew = m_Gamma.splitFace(adjSrc,adjTgt); m_eIterator[eNew] = GraphCopy::m_eCopy[eOrig].pushBack(eNew); m_eOrig[eNew] = eOrig; dirtyList.pushBack(eNew->adjSource()); adjSrc = adjSrcNext; } // insert last edge edge eNew = m_Gamma.splitFace(adjSrc,*it); m_eIterator[eNew] = m_eCopy[eOrig].pushBack(eNew); m_eOrig[eNew] = eOrig; dirtyList.pushBack(eNew->adjSource()); // remove the sink arc incident to v if(!outEdges.empty()) { edge e = outEdges.popFrontRet(); if (m_isSinkArc[e]) m_Gamma.joinFaces(e); } m_Gamma.setExternalFace(m_Gamma.rightFace(extFaceHandle)); //computeSinkSwitches(); FaceSinkGraph fsg(m_Gamma, s_hat); List<adjEntry> dummyList; FaceArray< List<adjEntry> > sinkSwitches(m_Gamma, dummyList); fsg.sinkSwitches(sinkSwitches); //construct sinkArc for the dirty faces for(adjEntry adj : dirtyList) { face fLeft = m_Gamma.leftFace(adj); face fRight = m_Gamma.rightFace(adj); List<adjEntry> switches = sinkSwitches[fLeft]; OGDF_ASSERT(!switches.empty()); constructSinkArcs(fLeft, switches.front()->theNode()); OGDF_ASSERT(!switches.empty()); switches = sinkSwitches[fRight]; constructSinkArcs(fRight, switches.front()->theNode()); } m_Gamma.setExternalFace(m_Gamma.rightFace(extFaceHandle)); computeSinkSwitches(); }
// Restores the previous call before the hook happened static void restore() { MakeCALL(addr, raw_ptr(original())); }
// Constructs passing information to the static variables function_hooker(hook_type hooker) { hook() = hooker; original() = MakeCALL(addr, raw_ptr(call)).get(); }
// The hook caller static Ret call(Args... a) { return hook()(original(), a...); }
TEST(StatusOr, TestPointerCopyCtorStatusNotOkConverting) { StatusOr<Derived*> original(Status::CANCELLED); StatusOr<Base2*> copy(original); // NOLINT EXPECT_EQ(original.status(), copy.status()); }
//activates a cc, if minnode==true, at least one node is inserted node PlanRepInc::initActiveCCGen(int i, bool minNode) { //node to be returned node minActive = nullptr; //list to be filled wih activated nodes List<node> activeOrigCCNodes; // a) delete copy / chain fields for originals of nodes in current cc, // since we change the CC number... // (since we remove all these copies in initByNodes(...) // b) create list of currently active original nodes for(int j = m_ccInfo.startNode(i); j < m_ccInfo.stopNode(i); ++j) { node vG = m_ccInfo.v(j); if (m_activeNodes[vG]) activeOrigCCNodes.pushBack(vG); if (m_currentCC >= 0) { m_vCopy[vG] = nullptr; for(adjEntry adj : vG->adjEdges) { if ((adj->index() & 1) == 0) continue; edge eG = adj->theEdge(); m_eCopy[eG].clear(); } } }//for originals //}//if non-empty //now we check if we have to activate a single node if (minNode) { if (activeOrigCCNodes.size() == 0) { //Simple strategy: take the first node minActive = m_ccInfo.v(m_ccInfo.startNode(i)); if (minActive != nullptr) { m_activeNodes[minActive] = true; activeOrigCCNodes.pushFront(minActive); } } }//minNode m_currentCC = i; //double feature: liste und nodearray, besser GraphCopy::initByActiveNodes(activeOrigCCNodes, m_activeNodes, m_eAuxCopy); // set type of edges (gen. or assoc.) in the current CC if (m_pGraphAttributes->attributes() & GraphAttributes::edgeType) for(edge e : edges) { m_eType[e] = m_pGraphAttributes->type(original(e)); if (original(e)) { switch (m_pGraphAttributes->type(original(e))) { case Graph::generalization: setGeneralization(e); break; case Graph::association: setAssociation(e); break; OGDF_NODEFAULT }//switch }//if original } if (m_pGraphAttributes->attributes() & GraphAttributes::nodeType) for(node v : nodes) m_vType[v] = m_pGraphAttributes->type(original(v)); //TODO:check only in CCs or global? m_treeInit = false; return minActive; }//initActiveCC
//-------------------------------------------------------------- void ofApp::draw(){ // Clear with alpha, so we can capture via syphon and composite elsewhere should we want. glClearColor(0.0, 0.0, 0.0, 0.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); ofFbo fbo; fbo.allocate(45, 45, GL_RGB); fbo.begin(); ofClear(0,0,0); fbo.end(); ofPixels pixels; ofImage feedImg; fbo.begin(); mClient.draw(0, 0); fbo.end(); fbo.readToPixels(pixels); fbo.draw(0, 0); ofBuffer imgAsBuffer; imgAsBuffer.clear(); imgAsBuffer.append((const char*)pixels.getData(),pixels.size()-5109); ofxOscMessage m; m.setAddress("/led"); m.addBlobArg(imgAsBuffer); // sender.sendMessage(m); // this code come from ofxOscSender::sendMessage in ofxOscSender.cpp static const int OUTPUT_BUFFER_SIZE = 327680; char buffer[OUTPUT_BUFFER_SIZE]; osc::OutboundPacketStream p( buffer, OUTPUT_BUFFER_SIZE ); // serialise the message bool wrapInBundle = true; // TODO turn this into a parameter if(wrapInBundle) p << osc::BeginBundleImmediate; appendMessage( m, p ); if(wrapInBundle) p << osc::EndBundle; ofx::IO::SLIPEncoding slip; ofx::IO::ByteBuffer original(p.Data(),p.Size()); device.send(original); // a priori ce truc encode en SLIP et transmet au Teensy ˆ tester ofx::IO::ByteBuffer encoded; slip.encode(original, encoded); ofxOscMessage s; ofBuffer slipBuffer; ofLogNotice("slip") << "original size : " << original.size(); ofLogNotice("slip") << "encoded size : " << encoded.size(); slipBuffer.append(reinterpret_cast<const char*>( encoded.getPtr()), encoded.size()); // getPtr() returns the const char* of the underlying buffer s.setAddress("/led"); s.addBlobArg(slipBuffer); sender.sendMessage(s); // feedImg.setFromPixels(feedPxl); // mClient.bind(); //ofTexture tex = mClient.getTexture(); //ofPixels & pixels = tex.readToPixels(); //ofPixels & pixels = mClient.getTextureReference().readToPixels(pixels); // ofTexture Nebula = mClient.getTexture()(); }
/** * Check to see if we have a local database already. * If it is, then check if it is up to date. * If local database is missing or obsolete then recreate it. * Return true if application has a local items database to run with, false otherwise. */ bool DBManager::syncLocalItemsDB(std::tstring const& localfile, std::tstring const& aofolder) { bool hasLocalDB = false; std::time_t lastUpdateTime; bfs::path local(to_ascii_copy (localfile)); bfs::path original(to_ascii_copy (aofolder)); original = original / "cd_image/data/db/ResourceDatabase.dat"; if (bfs::exists(local) && bfs::is_regular(local)) { hasLocalDB = true; lastUpdateTime = bfs::last_write_time(local); } if (!exists(original)) { Logger::instance().log(_T("Could not locate the original AO database.")); return hasLocalDB; } if (hasLocalDB && getAODBSchemeVersion(localfile) == CURRENT_AODB_VERSION) { std::time_t lastOriginalUpdateTime = bfs::last_write_time(original); if (lastOriginalUpdateTime <= lastUpdateTime) { return true; } // Ask user if he wants to continue using the old (but compatible) DB or update it now. int answer = ::MessageBox(NULL, _T("You items database is out of date. Do you wish to update it now?\r\nAnswering 'NO' will continue using the old one."), _T("Question - AO Item Assistant++"), MB_ICONQUESTION | MB_YESNOCANCEL); if (answer == IDCANCEL) { exit(0); } else if (answer == IDNO) { return true; } } // If we come this far we need to update the DB. bfs::path tmpfile("tmp_" + local.string()); bfs::remove(tmpfile); try { std::set<ResourceType> resource_types = boost::assign::list_of(AODB_TYP_ITEM)(AODB_TYP_NANO); AODatabaseIndex indexer(to_ascii_copy(aofolder) + "/cd_image/data/db/ResourceDatabase.idx", resource_types); std::vector<unsigned int> item_offsets = indexer.GetOffsets(AODB_TYP_ITEM); std::vector<unsigned int> nano_offsets = indexer.GetOffsets(AODB_TYP_NANO); unsigned int itemCount = item_offsets.size(); unsigned int nanoCount = nano_offsets.size(); std::vector<std::string> original_files = boost::assign::list_of(original.string())(original.string()+".001")(original.string()+".002"); AODatabaseParser aodb(original_files); AODatabaseWriter writer(tmpfile.string(), Logger::instance().stream()); CProgressDialog dlg(itemCount + nanoCount, itemCount); dlg.SetWindowText(_T("Progress Dialog - Item Assistant")); dlg.setText(0, _T("Extracting data from the AO DB...")); dlg.setText(1, STREAM2STR("Finished " << 0 << " out of " << itemCount << " items.")); dlg.setText(2, _T("Overall progress: 0%")); // Extract items boost::shared_ptr<ao_item> item; unsigned int count = 0; writer.BeginWrite(); for (std::vector<unsigned int>::iterator item_it = item_offsets.begin(); item_it != item_offsets.end(); ++item_it) { item = aodb.GetItem(*item_it); count++; if (!item) { LOG(_T("Parsing item ") << count << _T(" at offset ") << *item_it << _T(" failed!")); continue; } writer.WriteItem(item); if (count % 1000 == 0) { if (dlg.userCanceled()) { return false; } dlg.setTaskProgress(count, itemCount); dlg.setText(1, STREAM2STR("Finished " << count << " out of " << itemCount << " items.")); dlg.setOverallProgress(count, itemCount + nanoCount); dlg.setText(2, STREAM2STR("Overall progress: " << (count * 100) / max(1, itemCount + nanoCount) << "%")); } if (count % 10000 == 0) { writer.CommitItems(); writer.BeginWrite(); } } item.reset(); dlg.setTaskProgress(count, itemCount); dlg.setText(1, STREAM2STR("Finished " << count << " out of " << itemCount << " items.")); dlg.setOverallProgress(count, itemCount + nanoCount); dlg.setText(2, STREAM2STR("Overall progress: " << (count * 100) / max(1, itemCount + nanoCount) << "%")); writer.CommitItems(); if (dlg.userCanceled()) { return false; } // Extract nano programs boost::shared_ptr<ao_item> nano; count = 0; writer.BeginWrite(); for (std::vector<unsigned int>::iterator nano_it = nano_offsets.begin(); nano_it != nano_offsets.end(); ++nano_it) { nano = aodb.GetItem(*nano_it); count++; if (!nano) { LOG(_T("Parsing nano ") << count << _T(" at offset ") << *nano_it << _T(" failed!")); continue; } writer.WriteItem(nano); if (count % 1000 == 0) { if (dlg.userCanceled()) { return false; } dlg.setTaskProgress(count, nanoCount); dlg.setText(1, STREAM2STR("Finished " << count << " out of " << nanoCount << " nanos.")); dlg.setOverallProgress(itemCount + count, itemCount + nanoCount); dlg.setText(2, STREAM2STR("Overall progress: " << ((itemCount + count) * 100) / max(1, itemCount + nanoCount) << "%")); } if (count % 10000 == 0) { writer.CommitItems(); writer.BeginWrite(); } } nano.reset(); dlg.setTaskProgress(count, nanoCount); dlg.setText(1, STREAM2STR("Finished " << count << " out of " << nanoCount << " nanos.")); dlg.setOverallProgress(itemCount + count, itemCount + nanoCount); dlg.setText(2, STREAM2STR("Overall progress: " << ((itemCount + count) * 100) / max(1, itemCount + nanoCount) << "%")); writer.CommitItems(); if (dlg.userCanceled()) { return false; } writer.PostProcessData(); } catch (std::bad_alloc& e) { assert(false); LOG(_T("Error creating item database. ") << e.what()); MessageBox(NULL, _T("Unable to parse the AO database.\n\rMore details might be found in the log-file (if enabled)."), _T("Error - AO Item Assistant++"), MB_OK | MB_ICONERROR); return false; } catch (AODatabaseParser::Exception& e) { assert(false); LOG(_T("Error creating item database. ") << e.what()); MessageBox(NULL, _T("Unable to parse the AO database.\n\rMore details might be found in the log-file (if enabled)."), _T("Error - AO Item Assistant++"), MB_OK | MB_ICONERROR); return false; } catch (std::exception& e) { assert(false); LOG(_T("Error creating item database. ") << e.what()); MessageBox(NULL, _T("Unable to parse the AO database.\n\rMore details might be found in the log-file (if enabled)."), _T("Error - AO Item Assistant++"), MB_OK | MB_ICONERROR); return false; } remove(local); rename(tmpfile, local); return true; }
void RideImportWizard::abortClicked() { // if done when labelled abort we kill off this dialog QString label = abortButton->text(); if (label == "Abort") { aborted=true; // terminated. I'll be back. return; } if (label == "Finish") { // phew. our work is done. done(0); return; } int needdates=0; for (int i=0; i<filenames.count(); i++) { QTableWidgetItem *t = tableWidget->item(i,5); if (t->text().startsWith(tr("Error"))) continue; // date needed? t = tableWidget->item(i,1); if (t->text() == "") { needdates++; } t->setFlags(t->flags() | (Qt::ItemIsEditable)); // time needed? t = tableWidget->item(i,2); if (t->text() == "") { needdates++; } t->setFlags(t->flags() | (Qt::ItemIsEditable)); } if (needdates) return; // no dice dude, we need those dates filled in! // if done when labelled save we copy the files and run the cpi calculator phaseLabel->setText(tr("Step 4 of 4: Save to Library")); abortButton->setText(tr("Abort")); aborted = false; cancelButton->setHidden(true); todayButton->setHidden(true); overFiles->setHidden(true); // now set this fields uneditable again ... yeesh. for (int i=0; i <filenames.count(); i++) { QTableWidgetItem *t = tableWidget->item(i,1); t->setFlags(t->flags() & (~Qt::ItemIsEditable)); t = tableWidget->item(i,2); t->setFlags(t->flags() & (~Qt::ItemIsEditable)); } QChar zero = QLatin1Char ( '0' ); for (int i=0; i< filenames.count(); i++) { if (tableWidget->item(i,5)->text().startsWith(tr("Error"))) continue; // skip error tableWidget->item(i,5)->setText(tr("Saving...")); tableWidget->setCurrentCell(i,5); QApplication::processEvents(); if (aborted) { done(0); } this->repaint(); // Setup the ridetime as a QDateTime QDateTime ridedatetime = QDateTime(QDate().fromString(tableWidget->item(i,1)->text(), tr("dd MMM yyyy")), QTime().fromString(tableWidget->item(i,2)->text(), tr("hh:mm:ss a"))); QString suffix = QFileInfo(filenames[i]).suffix(); QString targetnosuffix = QString ( "%1_%2_%3_%4_%5_%6" ) .arg ( ridedatetime.date().year(), 4, 10, zero ) .arg ( ridedatetime.date().month(), 2, 10, zero ) .arg ( ridedatetime.date().day(), 2, 10, zero ) .arg ( ridedatetime.time().hour(), 2, 10, zero ) .arg ( ridedatetime.time().minute(), 2, 10, zero ) .arg ( ridedatetime.time().second(), 2, 10, zero ); QString target = QString ("%1.%2" ) .arg ( targetnosuffix ) .arg ( suffix ); QString fulltarget = home.absolutePath() + "/" + target; // so now we have sourcefile in 'filenames[i]' and target file name in 'target' if (!fulltarget.compare(filenames[i])) { // they are the same file! so skip copy tableWidget->item(i,5)->setText(tr("Error - Source is Target")); } else if (QFileInfo(fulltarget).exists()) { if (overwriteFiles) { tableWidget->item(i,5)->setText(tr("Overwriting file...")); QFile source(filenames[i]); QString fulltargettmp(home.absolutePath() + tr("/") + targetnosuffix + tr(".tmp")); if (source.copy(fulltargettmp)) { // tmp version saved now zap original QFile original(fulltarget); original.remove(); // zap! // mv tmp to target QFile temp(fulltargettmp); if (temp.rename(fulltarget)) { tableWidget->item(i,5)->setText(tr("File Overwritten")); //no need to add since its already there! //mainwindow->addRide(QFileInfo(fulltarget).fileName(), true); // add to tree view } else tableWidget->item(i,5)->setText(tr("Error - overwrite failed")); } else { tableWidget->item(i,5)->setText(tr("Error - overwrite failed")); } } else { tableWidget->item(i,5)->setText(tr("Error - File exists")); } } else { tableWidget->item(i,5)->setText(tr("Saving file...")); QFile source(filenames[i]); if (source.copy(fulltarget)) { tableWidget->item(i,5)->setText(tr("File Saved")); mainwindow->addRide(QFileInfo(fulltarget).fileName(), true); // add to tree view } else tableWidget->item(i,5)->setText(tr("Error - copy failed")); } QApplication::processEvents(); if (aborted) { done(0); } progressBar->setValue(progressBar->value()+1); this->repaint(); } #if 0 // NOT UNTIL CPINTPLOT.CPP IS REFACTORED TO SEPERATE CPI FILES MAINTENANCE FROM CP PLOT CODE // if done when labelled save we copy the files and run the cpi calculator phaseLabel->setText(tr("Step 5 of 5: Calculating Critical Powers")); abortButton->setText(tr("Abort")); aborted = false; for (int i=0; i< filenames.count(); i++) { if (!tableWidget->item(i,5)->text().startsWith(tr("Error"))) { tableWidget->item(i,5)->setText(tr("Calculating...")); tableWidget->setCurrentCell(i,5); QApplication::processEvents(); if (aborted) { done(0); } this->repaint(); // calculated // change status tableWidget->item(i,5)->setText(tr("Completed.")); } QApplication::processEvents(); if (aborted) { done(0); } progressBar->setValue(progressBar->value()+1); this->repaint(); } #endif // not until CPINTPLOT IS REFACTORED // how did we get on in the end then ... int completed = 0; for (int i=0; i< filenames.count(); i++) if (!tableWidget->item(i,5)->text().startsWith(tr("Error"))) { completed++; } tableWidget->setSortingEnabled(true); // so you can browse through errors etc QString donemessage = QString("Import Complete. %1 of %2 successful.") .arg(completed, 1, 10, zero) .arg(filenames.count(), 1, 10, zero); progressBar->setValue(progressBar->maximum()); phaseLabel->setText(donemessage); abortButton->setText(tr("Finish")); aborted = false; }
void TestApp::test_matrix_mat4() { Console::write_line(" Class: Mat4"); Console::write_line(" Function: inverse()"); { Mat4f test_src = Mat4f::rotate((Angle(30, angle_degrees)), 1.0, 0.0, 0.0, true); Mat4f test_inv; Mat4f test_dest; Mat4f test_ident = Mat4f::identity(); test_dest = test_src; test_dest.inverse(); test_dest = test_dest * test_src; if (test_ident != test_dest) fail(); } static int test_a_values[] = {3, 1, 2, 4, 5 ,6, 4, 2, 1, 4, 6, 7, 6, 3, 7, 2}; static int test_b_values[] = {4, 7, 2, 5, 3, 5, 2, 9, 3, 3, 6, 9, 2, 4, 6, 2}; Mat4i test_a(test_a_values); Mat4i test_b(test_b_values); Mat4f test_c(test_a); Mat4f test_c_scaled(test_c); { float x = 2.0f; float y = 3.0f; float z = 4.0f; test_c_scaled[0 + 4 * 0] *= x; test_c_scaled[0 + 4 * 1] *= y; test_c_scaled[0 + 4 * 2] *= z; test_c_scaled[1 + 4 * 0] *= x; test_c_scaled[1 + 4 * 1] *= y; test_c_scaled[1 + 4 * 2] *= z; test_c_scaled[2 + 4 * 0] *= x; test_c_scaled[2 + 4 * 1] *= y; test_c_scaled[2 + 4 * 2] *= z; test_c_scaled[3 + 4 * 0] *= x; test_c_scaled[3 + 4 * 1] *= y; test_c_scaled[3 + 4 * 2] *= z; } Console::write_line(" Function: add() and operator"); { int answer_values[] = {7, 8, 4, 9, 8, 11, 6, 11, 4, 7, 12, 16, 8, 7, 13, 4}; Mat4i answer(answer_values); Mat4i result = test_a + test_b; if (result != answer) fail(); result = Mat4i::add(test_a, test_b); if (result != answer) fail(); } Console::write_line(" Function: subtract() and operator"); { int answer_values[] = {-1, -6, 0, -1, 2, 1, 2, -7, -2, 1, 0, -2, 4, -1, 1, 0}; Mat4i answer(answer_values); Mat4i result = test_a - test_b; if (result != answer) fail(); result = Mat4i::subtract(test_a, test_b); if (result != answer) fail(); } Console::write_line(" Function: translate()"); { int answer_values[] = {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 2, 3, 4, 1}; Mat4i answer(answer_values); Mat4i result = Mat4i::translate(2, 3, 4); if (result != answer) fail(); } Console::write_line(" Function: translate_self() (int)"); { Mat4i answer(test_a); Mat4i result = test_a; result = result * Mat4i::translate(2, 3, 4); Mat4i result2 = test_a; result2.translate_self(2,3,4); if (result != result2) fail(); } Console::write_line(" Function: translate_self() (float)"); { Mat4f answer(test_a); Mat4f result(test_a); result = result * Mat4f::translate(2, 3, 4); Mat4f result2(test_a); result2.translate_self(2, 3, 4); if (!result.is_equal(result2, 0.00001f)) fail(); } Console::write_line(" Function: scale_self()"); { Mat4i answer(test_a); Mat4i result = test_a; result = result * Mat4i::scale(2, 3, 4); Mat4i result2 = test_a; result2.scale_self(2,3,4); if (result != result2) fail(); Mat4f test = test_c; test.scale_self(2.0f, 3.0f, 4.0f); if (!test.is_equal(test_c_scaled, 0.00001f)) fail(); } Console::write_line(" Function: rotate (using euler angles)"); { Mat4f mv = Mat4f::identity(); mv = mv * Mat4f::rotate(Angle(30.0f, angle_degrees), 0.0f, 0.0f, 1.0f, false); mv = mv * Mat4f::rotate(Angle(10.0f, angle_degrees), 1.0f, 0.0f, 0.0f, false); mv = mv * Mat4f::rotate(Angle(20.0f, angle_degrees), 0.0f, 1.0f, 0.0f, false); Mat4f test_matrix; test_matrix = Mat4f::rotate(Angle(10.0f, angle_degrees), Angle(20.0f, angle_degrees), Angle(30.0f, angle_degrees), order_YXZ); if (!test_matrix.is_equal(mv, 0.00001f)) fail(); } Console::write_line(" Function: rotate (using euler angles) and get_euler"); { test_rotate_and_get_euler(order_XYZ); test_rotate_and_get_euler(order_XZY); test_rotate_and_get_euler(order_YZX); test_rotate_and_get_euler(order_YXZ); test_rotate_and_get_euler(order_ZXY); test_rotate_and_get_euler(order_ZYX); } Console::write_line(" Function: transpose() (float)"); { Mat4f original(test_a); Mat4f transposed_matrix; transposed_matrix[0] = original[0]; transposed_matrix[1] = original[4]; transposed_matrix[2] = original[8]; transposed_matrix[3] = original[12]; transposed_matrix[4] = original[1]; transposed_matrix[5] = original[5]; transposed_matrix[6] = original[9]; transposed_matrix[7] = original[13]; transposed_matrix[8] = original[2]; transposed_matrix[9] = original[6]; transposed_matrix[10] = original[10]; transposed_matrix[11] = original[14]; transposed_matrix[12] = original[3]; transposed_matrix[13] = original[7]; transposed_matrix[14] = original[11]; transposed_matrix[15] = original[15]; Mat4f test = original; test.transpose(); if (!test.is_equal(transposed_matrix, 0.00001f)) fail(); } }
void incoming (struct client *client, struct email *msg) { verify (client, msg); original (client, msg); }
DeviceDenicer::DeviceDenicer(const std::string& device) { DeviceName original(device); setup(original); }
JNIEXPORT void JNICALL Java_org_apache_subversion_javahl_util_DiffLib_nativeFileMerge( JNIEnv* env, jobject jthis, jstring joriginal_file, jstring jmodified_file, jstring jlatest_file, jint jignore_space_ordinal, jboolean jignore_eol_style, jboolean jshow_c_function, jstring jconflict_original, jstring jconflict_modified, jstring jconflict_latest, jstring jconflict_separator, jint jconflict_style_ordinal, jobject jresult_stream) { JNIEntry(DiffLib, nativeFileMerge); // Using a "global" request pool since we don't keep a context with // its own pool around for these functions. SVN::Pool pool; Path original(joriginal_file, pool); if (JNIUtil::isJavaExceptionThrown()) return; SVN_JNI_ERR(original.error_occurred(),); Path modified(jmodified_file, pool); if (JNIUtil::isJavaExceptionThrown()) return; SVN_JNI_ERR(modified.error_occurred(),); Path latest(jlatest_file, pool); if (JNIUtil::isJavaExceptionThrown()) return; SVN_JNI_ERR(latest.error_occurred(),); svn_diff_t* diff; svn_diff_file_options_t* diff_options = svn_diff_file_options_create(pool.getPool()); diff_options->ignore_space = svn_diff_file_ignore_space_t(jignore_space_ordinal); diff_options->ignore_eol_style = svn_boolean_t(jignore_eol_style); diff_options->show_c_function = svn_boolean_t(jshow_c_function); SVN_JNI_ERR(svn_diff_file_diff3_2(&diff, original.c_str(), modified.c_str(), latest.c_str(), diff_options, pool.getPool()),); JNIStringHolder conflict_original(jconflict_original); if (JNIUtil::isJavaExceptionThrown()) return; JNIStringHolder conflict_modified(jconflict_modified); if (JNIUtil::isJavaExceptionThrown()) return; JNIStringHolder conflict_latest(jconflict_latest); if (JNIUtil::isJavaExceptionThrown()) return; JNIStringHolder conflict_separator(jconflict_separator); if (JNIUtil::isJavaExceptionThrown()) return; OutputStream result_stream(jresult_stream); SVN_JNI_ERR(svn_diff_file_output_merge2( result_stream.getStream(pool), diff, original.c_str(), modified.c_str(), latest.c_str(), conflict_original.c_str(), conflict_modified.c_str(), conflict_latest.c_str(), conflict_separator.c_str(), svn_diff_conflict_display_style_t(jconflict_style_ordinal), pool.getPool()),); }
extern "C" LEVMARDLL_API void StochFit(BoxReflSettings* InitStruct, double parameters[], double covararray[], int paramsize, double info[], double ParamArray[], double chisquarearray[], int* paramarraysize) { FastReflcalc Refl; Refl.init(InitStruct); double* Reflectivity = InitStruct->Refl; int QSize = InitStruct->QPoints; double* parampercs = InitStruct->ParamPercs; //Setup the fit double opts[LM_OPTS_SZ]; opts[0]=LM_INIT_MU; opts[1]=1E-15; opts[2]=1E-15; opts[3]=1E-20; opts[4]=-LM_DIFF_DELTA; // relevant only if the finite difference jacobian version is used //Allocate a dummy array - Our real calculation is done in Refl.objective double* xvec = new double[InitStruct->QPoints] ; for(int i = 0; i < InitStruct->QPoints; i++) { xvec[i] = 0; } //Copy starting solution double* origguess = new double[paramsize]; memcpy(origguess, parameters, sizeof(double)*paramsize); if(InitStruct->OneSigma) Refl.mkdensityonesigma(parameters, paramsize); else Refl.mkdensity(parameters, paramsize); Refl.myrfdispatch(); double bestchisquare = 0; for(int i = 0; i < InitStruct->QPoints; i++) { bestchisquare += (log(Refl.reflpt[i])-log(Reflectivity[i]))*(log(Refl.reflpt[i])-log(Reflectivity[i])); } double tempinfoarray[9]; tempinfoarray[1] = bestchisquare; double* tempcovararray = new double[paramsize*paramsize]; memset(tempcovararray,0.0, sizeof(double)*paramsize*paramsize); ParameterContainer original(parameters, tempcovararray, paramsize,InitStruct->OneSigma, tempinfoarray, parampercs[6]); delete[] tempcovararray; vector<ParameterContainer> temp; temp.reserve(6000); omp_set_num_threads(omp_get_num_procs()); #pragma omp parallel { FastReflcalc locRefl; locRefl.init(InitStruct); //Initialize random number generator int seed = time_seed(); CRandomMersenne randgen(time_seed()+omp_get_thread_num()); ParameterContainer localanswer; double locparameters[20]; double locbestchisquare = bestchisquare; double bestparam[20]; int vecsize = 1000; int veccount = 0; ParameterContainer* vec = (ParameterContainer*)malloc(vecsize*sizeof(ParameterContainer)); double locinfo[9]; //Allocate workspace - these will be private to each thread double* work, *covar; work=(double*)malloc((LM_DIF_WORKSZ(paramsize, QSize)+paramsize*QSize)*sizeof(double)); covar=work+LM_DIF_WORKSZ(paramsize, QSize); #pragma omp for schedule(runtime) for(int i = 0; i < InitStruct->Iterations;i++) { locparameters[0] = randgen.IRandom(origguess[0]*parampercs[4], origguess[0]*parampercs[5]); for(int k = 0; k< InitStruct->Boxes; k++) { if(InitStruct->OneSigma) { locparameters[2*k+1] = randgen.IRandom(origguess[2*k+1]*parampercs[0], origguess[2*k+1]*parampercs[1]); locparameters[2*k+2] = randgen.IRandom(origguess[2*k+2]*parampercs[2], origguess[2*k+2]*parampercs[3]); } else { locparameters[3*k+1] = randgen.IRandom(origguess[3*k+1]*parampercs[0], origguess[3*k+1]*parampercs[1]); locparameters[3*k+2] = randgen.IRandom(origguess[3*k+2]*parampercs[2], origguess[3*k+2]*parampercs[3]); locparameters[3*k+3] = randgen.IRandom(origguess[3*k+3]*parampercs[4], origguess[3*k+3]*parampercs[5]); } } locparameters[paramsize-1] = origguess[paramsize-1]; if(InitStruct->UL == NULL) dlevmar_dif(locRefl.objective, locparameters, xvec, paramsize, InitStruct->QPoints, 500, opts, locinfo, work,covar,(void*)(&locRefl)); else dlevmar_bc_dif(locRefl.objective, locparameters, xvec, paramsize, InitStruct->QPoints, InitStruct->LL, InitStruct->UL, 500, opts, locinfo, work,covar,(void*)(&locRefl)); localanswer.SetContainer(locparameters,covar,paramsize,InitStruct->OneSigma,locinfo, parampercs[6]); if(locinfo[1] < bestchisquare && localanswer.IsReasonable()) { //Resize the private arrays if we need the space if(veccount+2 == vecsize) { vecsize += 1000; vec = (ParameterContainer*)realloc(vec,vecsize*sizeof(ParameterContainer)); } bool unique = true; int arraysize = veccount; //Check if the answer already exists for(int i = 0; i < arraysize; i++) { if(localanswer == vec[i]) { unique = false; i = arraysize; } } //If the answer is unique add it to our set of answers if(unique) { vec[veccount] = localanswer; veccount++; } } } #pragma omp critical (AddVecs) { for(int i = 0; i < veccount; i++) { temp.push_back(vec[i]); } } free(vec); free(work); } // delete[] xvec; delete[] origguess; //Sort the answers //Get the total number of answers temp.push_back(original); vector<ParameterContainer> allsolutions; allsolutions.reserve(6000); int tempsize = temp.size(); allsolutions.push_back(temp[0]); for(int i = 1; i < tempsize; i++) { int allsolutionssize = allsolutions.size(); for(int j = 0; j < allsolutionssize;j++) { if(temp[i] == allsolutions[j]) { break; } if(j == allsolutionssize-1) { allsolutions.push_back(temp[i]); } } } if(allsolutions.size() > 0) { sort(allsolutions.begin(), allsolutions.end()); } for(int i = 0; i < allsolutions.size() && i < 1000 && allsolutions.size() > 0; i++) { for(int j = 0; j < paramsize; j++) { ParamArray[(i)*paramsize+j] = (allsolutions.at(i).GetParamArray())[j]; covararray[(i)*paramsize+j] = (allsolutions.at(i).GetCovarArray())[j]; } memcpy(info, allsolutions.at(i).GetInfoArray(), 9* sizeof(double)); info += 9; chisquarearray[i] = (allsolutions.at(i).GetScore()); } *paramarraysize = min(allsolutions.size(),999); }
void CBaseRenderer::CalcNormalDisplayRect(float offsetX, float offsetY, float screenWidth, float screenHeight, float inputFrameRatio, float zoomAmount, float verticalShift) { // if view window is empty, set empty destination if(screenHeight == 0 || screenWidth == 0) { m_destRect.SetRect(0.0f, 0.0f, 0.0f, 0.0f); return; } // scale up image as much as possible // and keep the aspect ratio (introduces with black bars) // calculate the correct output frame ratio (using the users pixel ratio setting // and the output pixel ratio setting) float outputFrameRatio = inputFrameRatio / g_graphicsContext.GetResInfo().fPixelRatio; // allow a certain error to maximize screen size float fCorrection = screenWidth / screenHeight / outputFrameRatio - 1.0f; float fAllowed = CSettings::GetInstance().GetInt(CSettings::SETTING_VIDEOPLAYER_ERRORINASPECT) * 0.01f; if(fCorrection > fAllowed) fCorrection = fAllowed; if(fCorrection < - fAllowed) fCorrection = - fAllowed; outputFrameRatio *= 1.0f + fCorrection; // maximize the movie width float newWidth = screenWidth; float newHeight = newWidth / outputFrameRatio; if (newHeight > screenHeight) { newHeight = screenHeight; newWidth = newHeight * outputFrameRatio; } // Scale the movie up by set zoom amount newWidth *= zoomAmount; newHeight *= zoomAmount; // if we are less than one pixel off use the complete screen instead if (std::abs(newWidth - screenWidth) < 1.0f) newWidth = screenWidth; if (std::abs(newHeight - screenHeight) < 1.0f) newHeight = screenHeight; // Centre the movie float posY = (screenHeight - newHeight) / 2; float posX = (screenWidth - newWidth) / 2; // vertical shift range -1 to 1 shifts within the top and bottom black bars // if there are no top and bottom black bars, this range does nothing float blackBarSize = std::max((screenHeight - newHeight) / 2.0f, 0.0f); posY += blackBarSize * std::max(std::min(verticalShift, 1.0f), -1.0f); // vertical shift ranges -2 to -1 and 1 to 2 will shift the image out of the screen // if vertical shift is -2 it will be completely shifted out the top, // if it's 2 it will be completely shifted out the bottom float shiftRange = std::min(newHeight, newHeight - (newHeight - screenHeight) / 2.0f); if (verticalShift > 1.0f) posY += shiftRange * (verticalShift - 1.0f); else if (verticalShift < -1.0f) posY += shiftRange * (verticalShift + 1.0f); m_destRect.x1 = (float)MathUtils::round_int(posX + offsetX); m_destRect.x2 = m_destRect.x1 + MathUtils::round_int(newWidth); m_destRect.y1 = (float)MathUtils::round_int(posY + offsetY); m_destRect.y2 = m_destRect.y1 + MathUtils::round_int(newHeight); // clip as needed if (!(g_graphicsContext.IsFullScreenVideo() || g_graphicsContext.IsCalibrating())) { CRect original(m_destRect); m_destRect.Intersect(CRect(offsetX, offsetY, offsetX + screenWidth, offsetY + screenHeight)); if (m_destRect != original) { float scaleX = m_sourceRect.Width() / original.Width(); float scaleY = m_sourceRect.Height() / original.Height(); m_sourceRect.x1 += (m_destRect.x1 - original.x1) * scaleX; m_sourceRect.y1 += (m_destRect.y1 - original.y1) * scaleY; m_sourceRect.x2 += (m_destRect.x2 - original.x2) * scaleX; m_sourceRect.y2 += (m_destRect.y2 - original.y2) * scaleY; } } if (m_oldDestRect != m_destRect || m_oldRenderOrientation != m_renderOrientation) { // adapt the drawing rect points if we have to rotate // and either destrect or orientation changed ReorderDrawPoints(); m_oldDestRect = m_destRect; m_oldRenderOrientation = m_renderOrientation; } }
TEST(StatusOr, TestCopyCtorStatusNotOkConverting) { StatusOr<int> original(Status::CANCELLED); StatusOr<double> copy(original); EXPECT_EQ(original.status(), copy.status()); }
void tst_QMediaResource::assign() { const QUrl url(QString::fromLatin1("http://test.com/test.mp4")); const QString mimeType(QLatin1String("video/mp4")); const QString amrCodec(QLatin1String("amr")); const QString mp3Codec(QLatin1String("mp3")); const QString aacCodec(QLatin1String("aac")); const QString h264Codec(QLatin1String("h264")); QNetworkRequest request(QUrl(QString::fromLatin1("http://test.com/test.mp4"))); const qint64 dataSize(23600); int audioBitRate = 1, sampleRate = 2, channelCount = 3, videoBitRate = 4; QSize resolution(QSize(640, 480)); QString language("eng"); QMediaResource copy(QUrl(QString::fromLatin1("file:///thumbs/test.jpg"))); QMediaResource original(url, mimeType); original.setAudioCodec(amrCodec); copy = original; QCOMPARE(copy.url(), url); QCOMPARE(copy.mimeType(), mimeType); QCOMPARE(copy.audioCodec(), amrCodec); QCOMPARE(original == copy, true); QCOMPARE(original != copy, false); original.setAudioCodec(mp3Codec); QCOMPARE(copy.audioCodec(), amrCodec); QCOMPARE(original == copy, false); QCOMPARE(original != copy, true); copy.setAudioCodec(aacCodec); copy.setVideoCodec(h264Codec); QCOMPARE(copy.url(), url); QCOMPARE(copy.mimeType(), mimeType); QCOMPARE(original.audioCodec(), mp3Codec); /* for constructor of QMediaresource(QNetworkrequest,mimeType)*/ QMediaResource copy1(QNetworkRequest(QUrl(QString::fromLatin1("file:///thumbs/test.jpg")))); QMediaResource original1(request, mimeType); original1.setAudioCodec(amrCodec); original1.setLanguage(QString("eng")); original1.setVideoCodec(h264Codec); original1.setDataSize(dataSize); original1.setAudioBitRate(audioBitRate); original1.setSampleRate(sampleRate); original1.setChannelCount(channelCount); original1.setVideoBitRate(videoBitRate); original1.setResolution(resolution); copy1 = original1; QCOMPARE(original1 == copy1, true); }
TEST(StatusOr, TestPointerCopyCtorStatusNotOk) { StatusOr<int*> original(Status::CANCELLED); StatusOr<int*> copy(original); EXPECT_EQ(original.status(), copy.status()); }
/** * Runs a debug version of perty for visualizing the results. Not necessary for normal testing. */ void runDebugTest() { shared_ptr<OsmMap> map(new OsmMap()); OGREnvelope env; env.MinX = 0; env.MinY = 0; env.MaxX = 1; env.MaxY = 1; map->setProjection(MapProjector::createAeacProjection(env)); //OsmReader reader; //reader.read("test-files/ToyTestA.osm", map); // force the map bounds. NodePtr n1(new Node(Status::Unknown1, map->createNextNodeId(), 0, 0, 10)); NodePtr n2(new Node(Status::Unknown1, map->createNextNodeId(), 100, 100, 10)); map->addNode(n1); map->addNode(n2); double gridSpacing = 2.5; for (double x = 0.0; x < 200.0; x += gridSpacing / 4) { for (double y = 0.0; y < 100.0; y += gridSpacing / 4) { NodePtr n(new Node(Status::Unknown1, map->createNextNodeId(), x, y, 10)); //n->setTag("note", QString::number(n->getId())); map->addNode(n); } } OsmWriter writer; QDir().mkpath("test-output/perty"); shared_ptr<OsmMap> original(new OsmMap(map)); MapProjector::projectToWgs84(original); writer.write(original, "test-output/perty/Original.osm"); PertyOp uut; uut.setGridSpacing(gridSpacing); uut.setRandomError(0.0, 0.0); uut.setSeed(1); uut.setSystematicError(10.0, 10.0); uut.setCsmParameters(9, 10); //uut.apply(map); // for (int i = 0; i < 100; i++) // { // shared_ptr<OsmMap> tmp(new OsmMap(map)); // uut.permute(tmp); // } //tbs::SampleStats ss(uut._x); //LOG_INFO("sd: " << ss.calculateUnbiasedStandardDeviation()); shared_ptr<OsmMap> debug = uut.generateDebugMap(map); // for (int i = 0; i < 100; i++) // { // shared_ptr<OsmMap> tmp(new OsmMap(map)); // uut.permute(tmp); // } //tbs::SampleStats ss(uut._x); //LOG_INFO("sd: " << ss.calculateUnbiasedStandardDeviation MapProjector::projectToWgs84(debug); writer.write(debug, "test-output/perty/Debug.osm"); MapProjector::projectToWgs84(map); writer.write(map, "test-output/perty/Permuted.osm"); }
int main(int argc, char** argv) { std::cout << "make the image denoising alchemy problem" << std::endl; std::string model_filename = "image"; std::string drawing = "sunset"; std::string corruption = "gaussian"; std::string smoothing = "square"; double lambda = 3; double sigma = 1; size_t rows = 200; size_t rings = 7; // Command line parsing graphlab::command_line_options clopts("Make the alchemy image", true); clopts.attach_option("model", &model_filename, model_filename, "Alchemy formatted model file"); clopts.attach_option("drawing", &drawing, drawing, "drawing type"); clopts.attach_option("corruption", &corruption, corruption, "corruption type"); clopts.attach_option("smoothing", &smoothing, smoothing, "smoothing type"); clopts.attach_option("lambda", &lambda, lambda, "edge parameter"); clopts.attach_option("sigma", &sigma, sigma, "noise parameter"); clopts.attach_option("rows", &rows, rows, "number of rows and cols"); clopts.attach_option("rings", &rings, rings, "number of rings"); if( !clopts.parse(argc, argv) ) { std::cout << "Error parsing command line arguments!" << std::endl; return EXIT_FAILURE; } std::cout << "Creating a synethic image." << std::endl; image original(rows, rows); if(drawing == "sunset") original.paint_sunset(rings); else if(drawing == "checkerboard") original.paint_checkerboard(rings); else { std::cout << "Invalid drawing type!" << std::endl; exit(1); } std::cout << "Saving original image. " << std::endl; original.save("original.pgm"); std::cout << "Corrupting Image. " << std::endl; image noisy = original; if(corruption == "gaussian") noisy.gaussian_corrupt(sigma); else if(corruption == "flip") noisy.flip_corrupt(rings, 0.75); else if(corruption == "ising") noisy = image(rows, rows); else { std::cout << "Invalid corruption type!" << std::endl; exit(1); } std::cout << "Saving corrupted image. " << std::endl; noisy.save("corrupted.pgm"); // dummy variables 0 and 1 and num_rings by num_rings std::cout << "Creating edge factor" << std::endl; factor_t edge_factor(domain_t(variable_t(0, rings), variable_t(1, rings))); // Set the smoothing type if(smoothing == "square") { edge_factor.set_as_agreement(lambda); } else if (smoothing == "laplace") { edge_factor.set_as_laplace(lambda); } else { std::cout << "Invalid smoothing stype!" << std::endl; assert(false); } std::cout << edge_factor << std::endl; std::cout << "Constructing factor graph." << std::endl; factorized_model model; // Add all the node factors double sigmaSq = sigma*sigma; for(size_t i = 0; i < noisy.rows(); ++i) { for(size_t j = 0; j < noisy.cols(); ++j) { // initialize the potential and belief uint32_t pixel_id = noisy.vertid(i, j); variable_t var(pixel_id, rings); factor_t factor(var); // Set the node potential double obs = noisy.pixel(i, j); if(corruption == "gaussian") { for(size_t pred = 0; pred < rings; ++pred) { factor.logP(pred) = -(obs - pred)*(obs - pred) / (2.0 * sigmaSq); } } else if(corruption == "flip") { for(size_t pred = 0; pred < rings; ++pred) { factor.logP(pred) = obs == pred? 0 : -sigma; } } else if(corruption == "ising") { // Do nothing since we want a uniform node potential factor.uniform(); } else { std::cout << "Invalid corruption!" << std::endl; exit(1); } factor.normalize(); model.add_factor(factor); } // end of for j in cols } // end of for i in rows // Construct edge_factors for(size_t i = 0; i < noisy.rows(); ++i) { for(size_t j = 0; j < noisy.cols(); ++j) { size_t source = noisy.vertid(i,j); variable_t source_var(source, rings); if(i+1 < noisy.rows()) { vertex_id_t target = noisy.vertid(i+1, j); variable_t target_var(target, rings); domain_t dom(source_var, target_var); edge_factor.set_args(dom); model.add_factor(edge_factor); } if(j+1 < noisy.cols()) { vertex_id_t target = noisy.vertid(i, j+1); variable_t target_var(target, rings); domain_t dom(source_var, target_var); edge_factor.set_args(dom); model.add_factor(edge_factor); } } // end of for j in cols } // end of for i in rows std::cout << "Saving model in alchemy format" << std::endl; model.save_alchemy(model_filename + ".alchemy"); return EXIT_SUCCESS; } // end of main