int main(){ int N,i,M,j,k; long long sum; N=fast(); while(N--){ sum=0; M=fast(); for(i=0;i<M;i++) arr[i]=fast(); k=M-1; for(j=M-1;j>=0;j--,k-=2)sum+=k*arr[j]; printf("%lld\n",sum); }return 0; }
TreeNode *sortedListToBST(ListNode *head) { if (NULL == head) { return NULL; } // special case for a single node if (NULL == head->next) { return new TreeNode(head->val); } ListNode *fast(head), *slow(head); while (slow && fast && fast->next && fast->next->next && fast->next->next->next) { fast = fast->next->next; slow = slow->next; } TreeNode *root(new TreeNode(0)); if (slow && slow->next) { root->val = slow->next->val; if (slow->next) { root->right = sortedListToBST(slow->next->next); } slow->next = NULL; root->left = sortedListToBST(head); } else { return NULL; } return root; }
typename std::enable_if<is_numexpr_arg<F>::value, numpy_fexpr<numpy_iexpr<Arg>, F>>::type numpy_iexpr<Arg>:: operator[](F const &filter) const { return fast(filter); }
char &sliced_str<S>::operator[](long i) { if (i < 0) { i += size(); } return fast(i); }
int main() { str[0]='$'; int id = 0; while (scanf("%s", str + 1) != EOF) { if(strcmp(str, "$END") == 0) break; printf("Case %d: %d\n", ++id, fast(str)); } return 0; }
int main() { // 在最低位放一个特殊字符 str[0]='$'; int n; scanf("%d", &n); while (n --) { scanf("%s", str + 1); printf("%d\n", fast(str)); } return 0; }
void fast(int array[], int size) { int i=0; int j=size; int p=array[size/2]; int temp; while(i<=j) { while(array[i]<p) i++; while(array[j]>p) j--; if(i<=j) { temp=array[i]; array[i]=array[j]; array[j]=temp; i++; j--; } } if(j>0) fast(array, j); if(i<size) fast(array+i,size-i); }
/* ------------------------------------------------------------------------------------------- * * ------------------------------------------------------------------------------------------- */ void FastFeaturesModule::OnFrame(mtv::Module *module, const QString name, cv::Mat &matrix) { cv::Mat frame; std::vector<cv::KeyPoint> keypoints; cv::FastFeatureDetector fast(10); fast.detect(matrix,keypoints); matrix.copyTo(frame); cv::drawKeypoints(matrix,keypoints,frame, cv::Scalar(255,255,255), cv::DrawMatchesFlags::DRAW_OVER_OUTIMG); //TODO emit List of PointList emit frameReady(this,"OUTPUT",frame); }
ListNode *detectCycle(ListNode *head) { if(!head) return nullptr; ListNode *slow(head), *fast(head); while(fast && fast->next) { slow = slow->next; fast = fast->next->next; if(slow == fast) break; } if(!fast || !fast->next) return nullptr; slow = head; while(slow != fast) { slow = slow->next; fast = fast->next; } return slow; }
bool hasCycle(ListNode *head) { if (NULL == head) { return false; } ListNode *slow(head), *fast(head->next); bool has_cycle = false; while (NULL != slow && NULL != fast) { if (slow == fast) { has_cycle = true; break; } slow = slow->next; fast = fast->next; if (NULL == fast) { break; } fast = fast->next; } return has_cycle; }
/* - matcher - the actual matching engine == static int matcher(struct re_guts *g, const char *string, \ == size_t nmatch, regmatch_t pmatch[], int eflags); */ static int /* 0 success, REG_NOMATCH failure */ matcher(struct re_guts *g, const char *string, size_t nmatch, regmatch_t pmatch[], int eflags) { const char *endp; int i; struct match mv; struct match *m = &mv; const char *dp; const sopno gf = g->firststate+1; /* +1 for OEND */ const sopno gl = g->laststate; const char *start; const char *stop; /* Boyer-Moore algorithms variables */ const char *pp; int cj, mj; const char *mustfirst; const char *mustlast; int *matchjump; int *charjump; /* simplify the situation where possible */ if (g->cflags®_NOSUB) nmatch = 0; if (eflags®_STARTEND) { start = string + pmatch[0].rm_so; stop = string + pmatch[0].rm_eo; } else { start = string; stop = start + strlen(start); } if (stop < start) return(REG_INVARG); /* prescreening; this does wonders for this rather slow code */ if (g->must != NULL) { if (g->charjump != NULL && g->matchjump != NULL) { mustfirst = g->must; mustlast = g->must + g->mlen - 1; charjump = g->charjump; matchjump = g->matchjump; pp = mustlast; for (dp = start+g->mlen-1; dp < stop;) { /* Fast skip non-matches */ while (dp < stop && charjump[(int)*dp]) dp += charjump[(int)*dp]; if (dp >= stop) break; /* Greedy matcher */ /* We depend on not being used for * for strings of length 1 */ while (*--dp == *--pp && pp != mustfirst); if (*dp == *pp) break; /* Jump to next possible match */ mj = matchjump[pp - mustfirst]; cj = charjump[(int)*dp]; dp += (cj < mj ? mj : cj); pp = mustlast; } if (pp != mustfirst) return(REG_NOMATCH); } else { for (dp = start; dp < stop; dp++) if (*dp == g->must[0] && stop - dp >= g->mlen && memcmp(dp, g->must, (size_t)g->mlen) == 0) break; if (dp == stop) /* we didn't find g->must */ return(REG_NOMATCH); } } /* match struct setup */ m->g = g; m->eflags = eflags; m->pmatch = NULL; m->lastpos = NULL; m->offp = string; m->beginp = start; m->endp = stop; STATESETUP(m, 4); SETUP(m->st); SETUP(m->fresh); SETUP(m->tmp); SETUP(m->empty); CLEAR(m->empty); ZAPSTATE(&m->mbs); /* Adjust start according to moffset, to speed things up */ if (g->moffset > -1) start = ((dp - g->moffset) < start) ? start : dp - g->moffset; /* this loop does only one repetition except for backrefs */ for (;;) { endp = fast(m, start, stop, gf, gl); if (endp == NULL) { /* a miss */ if (m->pmatch != NULL) free((char *)m->pmatch); if (m->lastpos != NULL) free((char *)m->lastpos); STATETEARDOWN(m); return(REG_NOMATCH); } if (nmatch == 0 && !g->backrefs) break; /* no further info needed */ /* where? */ assert(m->coldp != NULL); for (;;) { NOTE("finding start"); endp = slow(m, m->coldp, stop, gf, gl); if (endp != NULL) break; assert(m->coldp < m->endp); m->coldp += XMBRTOWC(NULL, m->coldp, m->endp - m->coldp, &m->mbs, 0); } if (nmatch == 1 && !g->backrefs) break; /* no further info needed */ /* oh my, he wants the subexpressions... */ if (m->pmatch == NULL) m->pmatch = (regmatch_t *)malloc((m->g->nsub + 1) * sizeof(regmatch_t)); if (m->pmatch == NULL) { STATETEARDOWN(m); return(REG_ESPACE); } for (i = 1; i <= m->g->nsub; i++) m->pmatch[i].rm_so = m->pmatch[i].rm_eo = -1; if (!g->backrefs && !(m->eflags®_BACKR)) { NOTE("dissecting"); dp = dissect(m, m->coldp, endp, gf, gl); } else { if (g->nplus > 0 && m->lastpos == NULL) m->lastpos = malloc((g->nplus+1) * sizeof(const char *)); if (g->nplus > 0 && m->lastpos == NULL) { free(m->pmatch); STATETEARDOWN(m); return(REG_ESPACE); } NOTE("backref dissect"); dp = backref(m, m->coldp, endp, gf, gl, (sopno)0, 0); } if (dp != NULL) break; /* uh-oh... we couldn't find a subexpression-level match */ assert(g->backrefs); /* must be back references doing it */ assert(g->nplus == 0 || m->lastpos != NULL); for (;;) { if (dp != NULL || endp <= m->coldp) break; /* defeat */ NOTE("backoff"); endp = slow(m, m->coldp, endp-1, gf, gl); if (endp == NULL) break; /* defeat */ /* try it on a shorter possibility */ #ifndef NDEBUG for (i = 1; i <= m->g->nsub; i++) { assert(m->pmatch[i].rm_so == -1); assert(m->pmatch[i].rm_eo == -1); } #endif NOTE("backoff dissect"); dp = backref(m, m->coldp, endp, gf, gl, (sopno)0, 0); } assert(dp == NULL || dp == endp); if (dp != NULL) /* found a shorter one */ break; /* despite initial appearances, there is no match here */ NOTE("false alarm"); /* recycle starting later */ start = m->coldp + XMBRTOWC(NULL, m->coldp, stop - m->coldp, &m->mbs, 0); assert(start <= stop); } /* fill in the details if requested */ if (nmatch > 0) { pmatch[0].rm_so = m->coldp - m->offp; pmatch[0].rm_eo = endp - m->offp; } if (nmatch > 1) { assert(m->pmatch != NULL); for (i = 1; i < nmatch; i++) if (i <= m->g->nsub) pmatch[i] = m->pmatch[i]; else { pmatch[i].rm_so = -1; pmatch[i].rm_eo = -1; } } if (m->pmatch != NULL) free((char *)m->pmatch); if (m->lastpos != NULL) free((char *)m->lastpos); STATETEARDOWN(m); return(0); }
/* * Runs benchmark. */ int main(int argc, char **argv) { int i; /* Loop index. */ int *mask; /* Mask. */ uint64_t end; /* End time. */ uint64_t start; /* Start time. */ char *img; /* Image. */ int numcorners=0; /* Total corners detected */ #ifdef _XEON_PHI_ double power; #endif readargs(argc, argv); timer_init(); srandnum(seed); omp_set_num_threads(nthreads); /* Benchmark initialization. */ if (verbose) printf("initializing...\n"); start = timer_get(); img = smalloc(p->imgsize*p->imgsize*sizeof(char)); for (i = 0; i < p->imgsize*p->imgsize; i++){ char val = randnum() & 0xff; img[i] = (val>0) ? val : val*(-1); } mask = smalloc(p->maskrows*p->maskcolumns*sizeof(int)); generate_mask(mask); end = timer_get(); if (verbose) printf(" time spent: %f\n", timer_diff(start, end)*MICROSEC); #ifdef _XEON_PHI_ power_init(); #endif /* Detect corners. */ if (verbose) printf("detecting corners...\n"); start = timer_get(); numcorners = fast(img, p->imgsize, mask); end = timer_get(); #ifdef _XEON_PHI_ power = power_end(); #endif printf("timing statistics:\n"); printf(" total time: %f\n", timer_diff(start, end)*MICROSEC); #ifdef _XEON_PHI_ printf(" average power: %f\n", power*0.000001); #endif printf(" corners detected: %d\n", numcorners); /* House keeping. */ free(mask); free(img); return (0); }
void fast_pyramid(std::vector<unsigned>& feat_pyr, std::vector<float*>& d_x_pyr, std::vector<float*>& d_y_pyr, std::vector<unsigned>& lvl_best, std::vector<float>& lvl_scl, std::vector<CParam<T> >& img_pyr, CParam<T> in, const float fast_thr, const unsigned max_feat, const float scl_fctr, const unsigned levels, const unsigned patch_size) { unsigned min_side = std::min(in.dims[0], in.dims[1]); unsigned max_levels = 0; float scl_sum = 0.f; for (unsigned i = 0; i < levels; i++) { min_side /= scl_fctr; // Minimum image side for a descriptor to be computed if (min_side < patch_size || max_levels == levels) break; max_levels++; scl_sum += 1.f / (float)std::pow(scl_fctr,(float)i); } // Compute number of features to keep for each level lvl_best.resize(max_levels); lvl_scl.resize(max_levels); unsigned feat_sum = 0; for (unsigned i = 0; i < max_levels-1; i++) { float scl = (float)std::pow(scl_fctr,(float)i); lvl_scl[i] = scl; lvl_best[i] = ceil((max_feat / scl_sum) / lvl_scl[i]); feat_sum += lvl_best[i]; } lvl_scl[max_levels-1] = (float)std::pow(scl_fctr,(float)max_levels-1); lvl_best[max_levels-1] = max_feat - feat_sum; // Hold multi-scale image pyramids static const dim4 dims0; static const CParam<T> emptyCParam(NULL, dims0.get(), dims0.get()); // Need to do this as CParam does not have a default constructor // And resize needs a default constructor or default value prior to C++11 img_pyr.resize(max_levels, emptyCParam); // Create multi-scale image pyramid for (unsigned i = 0; i < max_levels; i++) { if (i == 0) { // First level is used in its original size img_pyr[i].ptr = in.ptr; for (int k = 0; k < 4; k++) { img_pyr[i].dims[k] = in.dims[k]; img_pyr[i].strides[k] = in.strides[k]; } } else { // Resize previous level image to current level dimensions Param<T> lvl_img; lvl_img.dims[0] = round(in.dims[0] / lvl_scl[i]); lvl_img.dims[1] = round(in.dims[1] / lvl_scl[i]); lvl_img.strides[0] = 1; lvl_img.strides[1] = lvl_img.dims[0] * lvl_img.strides[0]; for (int k = 2; k < 4; k++) { lvl_img.dims[k] = 1; lvl_img.strides[k] = lvl_img.dims[k - 1] * lvl_img.strides[k - 1]; } int lvl_elem = lvl_img.strides[3] * lvl_img.dims[3]; lvl_img.ptr = memAlloc<T>(lvl_elem); resize<T, AF_INTERP_BILINEAR>(lvl_img, img_pyr[i-1]); img_pyr[i].ptr = lvl_img.ptr; for (int k = 0; k < 4; k++) { img_pyr[i].dims[k] = lvl_img.dims[k]; img_pyr[i].strides[k] = lvl_img.strides[k]; } } } feat_pyr.resize(max_levels); d_x_pyr.resize(max_levels); d_y_pyr.resize(max_levels); for (unsigned i = 0; i < max_levels; i++) { unsigned lvl_feat = 0; float* d_x_feat = NULL; float* d_y_feat = NULL; float* d_score_feat = NULL; // Round feature size to nearest odd integer float size = 2.f * floor(patch_size / 2.f) + 1.f; // Avoid keeping features that are too wide and might not fit the image, // sqrt(2.f) is the radius when angle is 45 degrees and represents // widest case possible unsigned edge = ceil(size * sqrt(2.f) / 2.f); // Detects FAST features fast(&lvl_feat, &d_x_feat, &d_y_feat, &d_score_feat, img_pyr[i], fast_thr, 9, 1, 0.15f, edge); // FAST score is not used memFree(d_score_feat); if (lvl_feat == 0) { feat_pyr[i] = 0; d_x_pyr[i] = NULL; d_x_pyr[i] = NULL; } else { feat_pyr[i] = lvl_feat; d_x_pyr[i] = d_x_feat; d_y_pyr[i] = d_y_feat; } } }
void ProcessingThread::run() { while(1) { // Check if paused pauseMutex.lock(); if (paused) { pauseMutex.unlock(); sleep(3); continue; } pauseMutex.unlock(); ///////////////////////////////// // Stop thread if stopped=TRUE // ///////////////////////////////// stoppedMutex.lock(); if (stopped) { stopped = false; stoppedMutex.unlock(); break; } stoppedMutex.unlock(); ///////////////////////////////// ///////////////////////////////// inputMutex.lock(); if (inputMode != INPUT_IMAGE) { inputMutex.unlock(); currentFrame = outputBuffer->getFrame(); } else { inputMutex.unlock(); if (outputBuffer->getSizeOfImageBuffer() > 0) { currentFrame = outputBuffer->getFrame(); } msleep(50); } inputMutex.unlock(); updM.lock(); //////////////////////////////////// // PERFORM IMAGE PROCESSING BELOW // //////////////////////////////////// cv::Mat outputIm = currentFrame.clone(); if (filters.flags[ImageProcessingFlags::ConvertColorspace]) { switch (settings.colorSpace) { case 0: { // Gray cv::cvtColor(currentFrame,outputIm, CV_RGB2GRAY); } break; case 1: { // HSV cv::cvtColor(currentFrame,outputIm, CV_RGB2HSV); } break; case 3: { // Lba cv::cvtColor(currentFrame,outputIm, CV_RGB2Lab); } break; } } if (filters.flags[ImageProcessingFlags::SaltPepperNoise]) { for (int i=0; i<settings.saltPepperNoiseDensity; i+=1) { // adding noise // generate randomly the col and row int m = qrand() % outputIm.rows; int n = qrand() % outputIm.cols; // generate randomly the value {black, white} int color_ = ((qrand() % 100) > 50) ? 255 : 0; if (outputIm.channels() == 1) { // gray-level image outputIm.at<uchar>(m, n)= color_; } else if (outputIm.channels() == 3) { // color image outputIm.at<cv::Vec3b>(m, n)[0]= color_; outputIm.at<cv::Vec3b>(m, n)[1]= color_; outputIm.at<cv::Vec3b>(m, n)[2]= color_; } } } if (filters.flags[ImageProcessingFlags::Dilate]) { cv::dilate(outputIm, outputIm, cv::Mat(), cv::Point(-1, -1), settings.dilateIterations); } if (filters.flags[ImageProcessingFlags::Erode]) { cv::erode(outputIm, outputIm, cv::Mat(), cv::Point(-1, -1), settings.erodeIterations); } if (filters.flags[ImageProcessingFlags::Open]) { cv::morphologyEx(outputIm, outputIm, cv::MORPH_OPEN, cv::Mat(), cv::Point(-1, -1), settings.openIterations); } if (filters.flags[ImageProcessingFlags::Close]) { cv::morphologyEx(outputIm, outputIm, cv::MORPH_CLOSE, cv::Mat(), cv::Point(-1, -1), settings.openIterations); } if (filters.flags[ImageProcessingFlags::Blur]) { cv::GaussianBlur(outputIm, outputIm, cv::Size(settings.blurSize, settings.blurSize), settings.blurSigma); } if (filters.flags[ImageProcessingFlags::Sobel]) { int scale = 1; int delta = 0; int ddepth = CV_16S; // check the direction switch (settings.sobelDirection) { case 0: { // horizontal cv::Mat grad_x; cv::Sobel( outputIm, grad_x, ddepth, 1, 0, settings.sobelKernelSize, scale, delta, BORDER_DEFAULT ); cv::convertScaleAbs( grad_x, outputIm ); } break; case 1: { // vertical cv::Mat grad_y; cv::Sobel( outputIm, grad_y, ddepth, 0, 1, settings.sobelKernelSize, scale, delta, BORDER_DEFAULT ); cv::convertScaleAbs( grad_y, outputIm ); } break; case 2: { // both directions cv::Mat grad_x; cv::Mat grad_y; cv::Mat abs_grad_x; cv::Mat abs_grad_y; cv::Sobel( outputIm, grad_x, ddepth, 1, 0, settings.sobelKernelSize, scale, delta, BORDER_DEFAULT ); cv::Sobel( outputIm, grad_y, ddepth, 0, 1, settings.sobelKernelSize, scale, delta, BORDER_DEFAULT ); cv::convertScaleAbs( grad_x, abs_grad_x ); cv::convertScaleAbs( grad_y, abs_grad_y ); cv::addWeighted( abs_grad_x, 0.5, abs_grad_y, 0.5, 0, outputIm ); } break; } } if (filters.flags[ImageProcessingFlags::Laplacian]) { int scale = 1; int delta = 0; int ddepth = CV_16S; cv::Laplacian( outputIm, outputIm, ddepth, settings.laplacianKernelSize, scale, delta, BORDER_DEFAULT ); cv::convertScaleAbs( outputIm, outputIm ); } if (filters.flags[ImageProcessingFlags::SharpByKernel]) { cv::Mat kernel(3,3,CV_32F,cv::Scalar(0));// init the kernel with zeros // assigns kernel values kernel.at<float>(1,1)= settings.sharpKernelCenter; kernel.at<float>(0,1)= -1.0; kernel.at<float>(2,1)= -1.0; kernel.at<float>(1,0)= -1.0; kernel.at<float>(1,2)= -1.0; //filter the image cv::filter2D(outputIm,outputIm,outputIm.depth(),kernel); } if (filters.flags[ImageProcessingFlags::EdgeDetection]) { // with canny cv::Canny(outputIm, outputIm, settings.cannyLowThres, settings.cannyHighThres); } if (filters.flags[ImageProcessingFlags::LinesHough]) { // Apply Canny algorithm cv::Mat contours; cv::Canny(outputIm,contours,125,350); // Hough tranform for line detection vector<cv::Vec2f> lines; cv::HoughLines(contours,lines, 1, PI/180, settings.linesHoughVotes); vector<cv::Vec2f>::const_iterator it= lines.begin(); while (it!=lines.end()) { float rho = (*it)[0]; // first element is distance rho float theta = (*it)[1]; // second element is angle theta if (theta < PI/4. || theta > 3.*PI/4.) {// ~vertical line // point of intersection of the line with first row cv::Point pt1(rho/cos(theta),0); // point of intersection of the line with last row cv::Point pt2((rho-contours.rows*sin(theta))/cos(theta),contours.rows); // draw a white line cv::line( outputIm, pt1, pt2, cv::Scalar(255), 1); } else { // ~horizontal line // point of intersection of the line with first column cv::Point pt1(0,rho/sin(theta)); // point of intersection of the line with last column cv::Point pt2(contours.cols, (rho-contours.cols*cos(theta))/sin(theta)); // draw a white line cv::line(outputIm, pt1, pt2, cv::Scalar(255), 1); } ++it; } } if (filters.flags[ImageProcessingFlags::CirclesHough]) { cv::Mat temp; if (outputIm.channels() > 1) { cv::cvtColor(outputIm, temp, CV_RGB2GRAY); } else { temp = outputIm; } cv::GaussianBlur(temp, temp, cv::Size(5,5), 1.5); vector<cv::Vec3f> circles; cv::HoughCircles(temp, circles, CV_HOUGH_GRADIENT, 2, // accumulator resolution (size of the image / 2) 50, // minimum distance between two circles 200, // Canny high threshold 60, // minimum number of votes settings.circlesHoughMin, settings.circlesHoughMax); std::vector<cv::Vec3f>::const_iterator itc= circles.begin(); while (itc!=circles.end()) { cv::circle(outputIm, cv::Point((*itc)[0], (*itc)[1]), // circle centre (*itc)[2], // circle radius cv::Scalar(255), // color 2); // thickness ++itc; } } if (filters.flags[ImageProcessingFlags::Countours]) { cv::Mat temp; if (outputIm.channels() > 1) { cv::cvtColor(outputIm, temp, CV_RGB2GRAY); } else { temp = outputIm; } cv::blur(temp, temp, Size(3,3)); cv::Canny(temp, temp, settings.contoursThres, settings.contoursThres+30); vector< vector<cv::Point> > contours; cv::findContours(temp, contours, // a vector of contours CV_RETR_TREE, // retrieve all contours, reconstructs a full hierarchy CV_CHAIN_APPROX_NONE); // all pixels of each contours cv::drawContours(outputIm,contours, -1, // draw all contours cv::Scalar(255, 255, 255), // in white 1); // with a thickness of 1 } if (filters.flags[ImageProcessingFlags::BoundingBox]) { cv::Mat temp; if (outputIm.channels() > 1) { cv::cvtColor(outputIm, temp, CV_RGB2GRAY); } else { temp = outputIm; } cv::blur(temp, temp, Size(3,3)); cv::Canny(temp, temp, settings.boundingBoxThres, settings.boundingBoxThres*2); vector< vector<cv::Point> > contours; cv::findContours(temp, contours, // a vector of contours CV_RETR_TREE, // retrieve all contours, reconstructs a full hierarchy CV_CHAIN_APPROX_NONE); // all pixels of each contours vector< vector<cv::Point> >::iterator itc = contours.begin(); while (itc != contours.end()) { cv::Rect r0 = cv::boundingRect(cv::Mat(*itc)); cv::rectangle(outputIm,r0,cv::Scalar(255, 0, 0), 2); ++itc; } } if (filters.flags[ImageProcessingFlags::enclosingCircle]) { cv::Mat temp; if (outputIm.channels() > 1) { cv::cvtColor(outputIm, temp, CV_RGB2GRAY); } else { temp = outputIm; } cv::blur(temp, temp, Size(3,3)); cv::Canny(temp, temp, settings.enclosingCircleThres, settings.enclosingCircleThres*2); vector< vector<cv::Point> > contours; cv::findContours(temp, contours, // a vector of contours CV_RETR_TREE, // retrieve all contours, reconstructs a full hierarchy CV_CHAIN_APPROX_NONE); // all pixels of each contours vector< vector<cv::Point> >::iterator itc = contours.begin(); while (itc != contours.end()) { float radius; cv::Point2f center; cv::minEnclosingCircle(cv::Mat(*itc),center,radius); cv::circle(outputIm, center, static_cast<int>(radius), cv::Scalar(0, 255, 0), 2); ++itc; } } if (filters.flags[ImageProcessingFlags::harris]) { cv::Mat temp; if (outputIm.channels() > 1) { cv::cvtColor(outputIm, temp, CV_RGB2GRAY); } else { temp = outputIm; } // Detector parameters int blockSize = 2; int apertureSize = 3; double k = 0.04; // Detecting corners cv::cornerHarris(temp, temp, blockSize, apertureSize, k, BORDER_DEFAULT); // Normalizing normalize(temp,temp, 0, 255, NORM_MINMAX, CV_32FC1, Mat()); // Drawing a circle around corners for( int j = 0; j < temp.rows ; j++ ) { for( int i = 0; i < temp.cols; i++ ) { if( (int) temp.at<float>(j,i) > settings.harrisCornerThres) { circle(outputIm, Point( i, j ), 5, Scalar(0, 0 , 255), 2, 8, 0); } } } } if (filters.flags[ImageProcessingFlags::FAST]) { // vector of keypoints vector<cv::KeyPoint> keypoints; // Construction of the Fast feature detector object cv::FastFeatureDetector fast(settings.fastThreshold); // threshold for detection // feature point detection fast.detect(outputIm,keypoints); cv::drawKeypoints(outputIm, keypoints, outputIm, cv::Scalar(255,255,255), cv::DrawMatchesFlags::DRAW_OVER_OUTIMG); } if (filters.flags[ImageProcessingFlags::SURF]) { // vector of keypoints vector<cv::KeyPoint> keypoints; // Construct the SURF feature detector object cv::SurfFeatureDetector surf((double) settings.surfThreshold); // threshold // Detect the SURF features surf.detect(outputIm,keypoints); // Draw the keypoints with scale and orientation information cv::drawKeypoints(outputIm, keypoints, outputIm, cv::Scalar(255,255,255),cv::DrawMatchesFlags::DRAW_RICH_KEYPOINTS); } if (filters.flags[ImageProcessingFlags::SIFT]) { vector<cv::KeyPoint> keypoints; // Construct the SURF feature detector object cv::SiftFeatureDetector sift( settings.siftContrastThres, // feature threshold (double) settings.siftEdgeThres); // threshold to reduce sens. to lines sift.detect(outputIm,keypoints); // Draw the keypoints with scale and orientation information cv::drawKeypoints(outputIm, keypoints, outputIm, cv::Scalar(255,255,255),cv::DrawMatchesFlags::DRAW_RICH_KEYPOINTS); } if (filters.flags[ImageProcessingFlags::EqualizeHistogram]) { // converting the image to gray if (outputIm.channels() == 3) { vector<Mat> bgr_planes; split( outputIm, bgr_planes ); equalizeHist( bgr_planes[0], bgr_planes[0] ); equalizeHist( bgr_planes[1], bgr_planes[1] ); equalizeHist( bgr_planes[2], bgr_planes[2] ); merge( bgr_planes, outputIm ); } else { equalizeHist( outputIm, outputIm ); } } // Computing histogram if (filters.flags[ImageProcessingFlags::ComputeHistogram]) { cv::Mat grayIm; cv::Mat hist; // converting the image to gray if (outputIm.channels() == 3) { cv::cvtColor(outputIm,grayIm, CV_RGB2GRAY); } else { grayIm = outputIm; } int histSize = 256; // number of bins float range [] = {0, 256}; // ranges const float* histRange = { range }; bool uniform = true, accumulate = false; // compute histogram cv::calcHist(&grayIm, 1, // using just one image 0, // using just one layer cv::Mat(), hist, 1, &histSize, &histRange, uniform, accumulate); int hist_w = 691; int hist_h =161; Mat result( hist_h, hist_w, CV_8UC3, Scalar( 255,255,255) ); int bin_w = cvRound( (double) hist_w/histSize ); normalize(hist, hist, 0, result.rows, NORM_MINMAX, -1, Mat()); /// Draw for each channel for( int i = 1; i < histSize; i++ ) { line(result, Point( bin_w*(i-1), hist_h - cvRound(hist.at<float>(i-1)) ), Point( bin_w*(i), hist_h - cvRound(hist.at<float>(i)) ), Scalar( 0, 0, 0), 2, 8, 0 ); } // emit signal emit newProcessedHistogram(MatToQImage(result)); } updM.unlock(); processedFrame = outputIm; // Inform GUI thread of new frame (QImage) emit newProcessedFrame(MatToQImage(outputIm)); } }
/* - matcher - the actual matching engine */ static int /* 0 success, R_REGEX_NOMATCH failure */ matcher(struct re_guts *g, char *string, size_t nmatch, RRegexMatch pmatch[], int eflags) { char *endp; int i; struct match mv; struct match *m = &mv; char *dp; const sopno gf = g->firststate+1; /* +1 for OEND */ const sopno gl = g->laststate; char *start; char *stop; /* simplify the situation where possible */ if (g->cflags&R_REGEX_NOSUB) nmatch = 0; if (eflags&R_REGEX_STARTEND) { start = string + pmatch[0].rm_so; stop = string + pmatch[0].rm_eo; } else { start = string; stop = start + strlen(start); } if (stop < start) return(R_REGEX_INVARG); /* prescreening; this does wonders for this rather slow code */ if (g->must != NULL) { for (dp = start; dp < stop; dp++) if (*dp == g->must[0] && stop - dp >= g->mlen && memcmp(dp, g->must, (size_t)g->mlen) == 0) break; if (dp == stop) /* we didn't find g->must */ return(R_REGEX_NOMATCH); } /* match struct setup */ m->g = g; m->eflags = eflags; m->pmatch = NULL; m->lastpos = NULL; m->offp = string; m->beginp = start; m->endp = stop; STATESETUP(m, 4); SETUP(m->st); SETUP(m->fresh); SETUP(m->tmp); SETUP(m->empty); CLEAR(m->empty); /* this loop does only one repetition except for backrefs */ for (;;) { endp = fast(m, start, stop, gf, gl); if (endp == NULL) { /* a miss */ free(m->pmatch); free(m->lastpos); STATETEARDOWN(m); return(R_REGEX_NOMATCH); } if (nmatch == 0 && !g->backrefs) break; /* no further info needed */ /* where? */ assert(m->coldp != NULL); for (;;) { NOTE("finding start"); endp = slow(m, m->coldp, stop, gf, gl); if (endp != NULL) break; assert(m->coldp < m->endp); m->coldp++; } if (nmatch == 1 && !g->backrefs) break; /* no further info needed */ /* oh my, he wants the subexpressions... */ if (m->pmatch == NULL) m->pmatch = (RRegexMatch *)malloc((m->g->nsub + 1) * sizeof(RRegexMatch)); if (m->pmatch == NULL) { STATETEARDOWN(m); return(R_REGEX_ESPACE); } for (i = 1; i <= m->g->nsub; i++) m->pmatch[i].rm_so = m->pmatch[i].rm_eo = -1; if (!g->backrefs && !(m->eflags&R_REGEX_BACKR)) { NOTE("dissecting"); dp = dissect(m, m->coldp, endp, gf, gl); } else { if (g->nplus > 0 && m->lastpos == NULL) m->lastpos = (char **)malloc((g->nplus+1) * sizeof(char *)); if (g->nplus > 0 && m->lastpos == NULL) { free(m->pmatch); STATETEARDOWN(m); return(R_REGEX_ESPACE); } NOTE("backref dissect"); dp = backref(m, m->coldp, endp, gf, gl, (sopno)0, 0); } if (dp != NULL) break; /* uh-oh... we couldn't find a subexpression-level match */ assert(g->backrefs); /* must be back references doing it */ assert(g->nplus == 0 || m->lastpos != NULL); for (;;) { if (dp != NULL || endp <= m->coldp) break; /* defeat */ NOTE("backoff"); endp = slow(m, m->coldp, endp-1, gf, gl); if (endp == NULL) break; /* defeat */ /* try it on a shorter possibility */ #ifndef NDEBUG for (i = 1; i <= m->g->nsub; i++) { assert(m->pmatch[i].rm_so == -1); assert(m->pmatch[i].rm_eo == -1); } #endif NOTE("backoff dissect"); dp = backref(m, m->coldp, endp, gf, gl, (sopno)0, 0); } assert(dp == NULL || dp == endp); if (dp != NULL) /* found a shorter one */ break; /* despite initial appearances, there is no match here */ NOTE("false alarm"); if (m->coldp == stop) break; start = m->coldp + 1; /* recycle starting later */ } /* fill in the details if requested */ if (nmatch > 0) { pmatch[0].rm_so = m->coldp - m->offp; pmatch[0].rm_eo = endp - m->offp; } if (nmatch > 1) { assert(m->pmatch != NULL); for (i = 1; i < nmatch; i++) if (i <= m->g->nsub) pmatch[i] = m->pmatch[i]; else { pmatch[i].rm_so = -1; pmatch[i].rm_eo = -1; } } if (m->pmatch != NULL) free((char *)m->pmatch); if (m->lastpos != NULL) free((char *)m->lastpos); STATETEARDOWN(m); return(0); }
static int dnoise(CSOUND *csound, int argc, char **argv) { OPARMS O; csound->GetOParms(csound, &O); MYFLT beg = -FL(1.0), end = -FL(1.0); long Beg = 0, End = 99999999; MYFLT *ibuf1, /* pointer to start of input buffer */ *ibuf2, /* pointer to start of input buffer */ *obuf1, /* pointer to start of output buffer */ *obuf2, /* pointer to start of output buffer */ *fbuf, /* pointer to start of FFT buffer */ *aWin, /* pointer to center of analysis window */ *sWin, /* pointer to center of synthesis window */ *i0, /* pointer to real channels */ *i1, /* pointer to imaginary channels */ *j0, /* pointer to real channels */ *j1, /* pointer to imaginary channels */ *f, /* pointer to FFT buffer */ *f0, /* pointer to real channels */ *f1, /* pointer to imaginary channels */ *w, /* pointer to window */ *mbuf, /* m most recent frames of FFT */ *nbuf, /* m most recent frames of FFT */ *nref, /* noise reference buffer */ *rsum, /* running sum of magnitude-squared spectrum */ *ssum, /* running sum of magnitude-squared spectrum */ *ibp, /* pointer to next input to be read */ *ib0, /* pointer to output buffer */ *ib1, /* pointer to output buffer */ *ib2, /* pointer to output buffer */ *obp, /* pointer to next output to be read */ *ob0, /* pointer to output buffer */ *ob1, /* pointer to output buffer */ *ob2; /* pointer to output buffer */ int N = 0, /* number of phase vocoder channels (bands) */ Np2, /* N+2 */ M = 0, /* length of aWin impulse response */ L = 0, /* length of sWin impulse response */ D = 0, /* decimation factor (default will be M/8) */ I = 0, /* interpolation factor (default will be I=D)*/ W = -1, /* filter overlap factor (determines M, L) */ ibuflen, /* size of ibuf */ obuflen, /* size of obuf */ aLen, /* half-length of analysis window */ sLen; /* half-length of synthesis window */ long oCnt = 0L, /* number of samples written to output */ nI, /* current input (analysis) sample */ nO, /* current output (synthesis) sample */ nImodR, /* current input sample mod R */ nMaxOut, /* last output (synthesis) sample */ nMin, /* first input (analysis) sample */ nMax, /* last input sample (unless EOF) */ lnread, /* total input samples read */ lj, /* to satisfy lame Microsoft compiler */ lk; /* to satisfy lame Microsoft compiler */ SNDFILE *fp = NULL; /* noise reference file */ MYFLT Ninv, /* 1. / N */ //RoverTwoPi, /* R/D divided by 2*Pi */ //TwoPioverR, /* 2*Pi divided by R/I */ sum, /* scale factor for renormalizing windows */ //rIn, /* decimated sampling rate */ //rOut, /* pre-interpolated sampling rate */ invR, /* 1. / srate */ time, /* nI / srate */ gain, /* gain of noise gate */ g0 = -FL(40.0),/* minimum gain for noise gate */ g0m, /* 1. - g0 */ th = FL(30.0), /* threshold above noise reference (dB) */ avg, /* average square energy */ fac, /* factor in gain computation */ minv, /* 1 / m */ R = -FL(1.0); /* input sampling rate */ int i,j,k, /* index variables */ ibs, /* current starting location in input buffer */ ibc, /* current location in input buffer */ obs, /* current starting location in output buffer */ obc, /* current location in output buffer */ m = 5, /* number of frames to save in mbuf */ mi = 0, /* frame offset index in mbuf */ mj, /* delayed offset index in mbuf */ md, /* number of frames of delay in mbuf (m/2) */ mp, /* mi * Np2 */ sh = 1, /* sharpness control for noise gate gain */ nread, /* number of bytes read */ N2, /* N/2 */ Meven = 0, /* flag for even M */ Leven = 0, /* flag for even L */ Verbose = 0,/* flag for verbose output to stderr */ Chans = -1, /* number of audio input channels (stereo = 2) */ chan, /* channel counter */ flag = 1, /* end-of-input flag */ first = 0; /* first-time-thru flag */ SOUNDIN *p, *pn; char *infile = NULL, *nfile = NULL; SNDFILE *inf = NULL, *outfd = NULL; char c, *s; int channel = ALLCHNLS; MYFLT beg_time = FL(0.0), input_dur = FL(0.0), sr = FL(0.0); MYFLT beg_ntime = FL(0.0), input_ndur = FL(0.0), srn = FL(0.0); const char *envoutyp = NULL; unsigned int outbufsiz = 0U; int nrecs = 0; /* audio is now normalised after call to getsndin */ /* csound->e0dbfs = csound->dbfs_to_float = FL(1.0); */ if ((envoutyp = csound->GetEnv(csound, "SFOUTYP")) != NULL) { if (strcmp(envoutyp, "AIFF") == 0) O.filetyp = TYP_AIFF; else if (strcmp(envoutyp, "WAV") == 0) O.filetyp = TYP_WAV; else if (strcmp(envoutyp, "IRCAM") == 0) O.filetyp = TYP_IRCAM; else { csound->Message(csound, Str("%s not a recognised SFOUTYP env setting"), envoutyp); return -1; } } { ++argv; while (--argc>0) { s = *argv++; if (*s++ == '-') { /* read all flags: */ while ((c = *s++) != '\0') { switch (c) { case 'o': FIND("no outfilename"); O.outfilename = s; /* soundout name */ for ( ; *s != '\0'; s++) ; if (strcmp(O.outfilename, "stdin") == 0) { csound->Message(csound, Str("-o cannot be stdin\n")); return -1; } break; case 'i': FIND("no noisefilename"); nfile = s; for ( ; *s != '\0'; s++) ; break; case 'A': if (O.filetyp == TYP_WAV) csound->Warning(csound, Str("-A overriding local default WAV out")); O.filetyp = TYP_AIFF; /* AIFF output request*/ break; case 'J': if (O.filetyp == TYP_AIFF || O.filetyp == TYP_WAV) csound->Warning(csound, Str("-J overriding local default " "AIFF/WAV out")); O.filetyp = TYP_IRCAM; /* IRCAM output request */ break; case 'W': if (O.filetyp == TYP_AIFF) csound->Warning(csound, Str("-W overriding local default AIFF out")); O.filetyp = TYP_WAV; /* WAV output request */ break; case 'h': O.filetyp = TYP_RAW; O.sfheader = 0; /* skip sfheader */ break; case 'c': O.outformat = AE_CHAR; /* 8-bit char soundfile */ break; case '8': O.outformat = AE_UNCH; /* 8-bit unsigned char file */ break; case 'a': O.outformat = AE_ALAW; /* a-law soundfile */ break; case 'u': O.outformat = AE_ULAW; /* mu-law soundfile */ break; case 's': O.outformat = AE_SHORT; /* short_int soundfile */ break; case 'l': O.outformat = AE_LONG; /* long_int soundfile */ break; case 'f': O.outformat = AE_FLOAT; /* float soundfile */ break; case 'R': O.rewrt_hdr = 1; break; case 'H': if (isdigit(*s)) { int n; sscanf(s, "%d%n", &O.heartbeat, &n); s += n; } else O.heartbeat = 1; break; case 't': FIND(Str("no t argument")); #if defined(USE_DOUBLE) csound->sscanf(s,"%lf",&th); #else csound->sscanf(s,"%f",&th); #endif while (*++s); break; case 'S': FIND("no s arg"); sscanf(s,"%d", &sh); while (*++s); break; case 'm': FIND("no m arg"); #if defined(USE_DOUBLE) csound->sscanf(s,"%lf",&g0); #else csound->sscanf(s,"%f",&g0); #endif while (*++s); break; case 'n': FIND(Str("no n argument")); sscanf(s,"%d", &m); while (*++s); break; case 'b': FIND(Str("no b argument")); #if defined(USE_DOUBLE) csound->sscanf(s,"%lf",&beg); #else csound->sscanf(s,"%f",&beg); #endif while (*++s); break; case 'B': FIND(Str("no B argument")); sscanf(s,"%ld", &Beg); while (*++s); break; case 'e': FIND("no e arg"); #if defined(USE_DOUBLE) csound->sscanf(s,"%lf",&end); #else csound->sscanf(s,"%f",&end); #endif while (*++s); break; case 'E': FIND(Str("no E argument")); sscanf(s,"%ld", &End); while (*++s); break; case 'N': FIND(Str("no N argument")); sscanf(s,"%d", &N); while (*++s); break; case 'M': FIND(Str("no M argument")); sscanf(s,"%d", &M); while (*++s); break; case 'L': FIND(Str("no L argument")); sscanf(s,"%d", &L); while (*++s); break; case 'w': FIND(Str("no w argument")); sscanf(s,"%d", &W); while (*++s); break; case 'D': FIND(Str("no D argument")); sscanf(s,"%d", &D); while (*++s); break; case 'V': Verbose = 1; break; default: csound->Message(csound, Str("Looking at %c\n"), c); return dnoise_usage(csound, -1); /* this exits with error */ } } } else if (infile==NULL) { infile = --s; csound->Message(csound, Str("Infile set to %s\n"), infile); } else { csound->Message(csound, Str("End with %s\n"), s); return dnoise_usage(csound, -1); } } } if (infile == NULL) { csound->Message(csound, Str("dnoise: no input file\n")); return dnoise_usage(csound, -1); } if (nfile == NULL) { csound->Message(csound, Str("Must have an example noise file (-i name)\n")); return -1; } if ((inf = csound->SAsndgetset(csound, infile, &p, &beg_time, &input_dur, &sr, channel)) == NULL) { csound->Message(csound, Str("error while opening %s"), infile); return -1; } if (O.outformat == 0) O.outformat = p->format; O.sfsampsize = csound->sfsampsize(FORMAT2SF(O.outformat)); if (O.filetyp == TYP_RAW) { O.sfheader = 0; O.rewrt_hdr = 0; } else O.sfheader = 1; if (O.outfilename == NULL) O.outfilename = "test"; { SF_INFO sfinfo; char *name; memset(&sfinfo, 0, sizeof(SF_INFO)); sfinfo.samplerate = (int) p->sr; sfinfo.channels = (int) p->nchanls; sfinfo.format = TYPE2SF(O.filetyp) | FORMAT2SF(O.outformat); if (strcmp(O.outfilename, "stdout") != 0) { name = csound->FindOutputFile(csound, O.outfilename, "SFDIR"); if (name == NULL) { csound->Message(csound, Str("cannot open %s.\n"), O.outfilename); return -1; } outfd = sf_open(name, SFM_WRITE, &sfinfo); if (outfd != NULL) csound->NotifyFileOpened(csound, name, csound->type2csfiletype(O.filetyp, O.outformat), 1, 0); csound->Free(csound, name); } else outfd = sf_open_fd(1, SFM_WRITE, &sfinfo, 1); if (outfd == NULL) { csound->Message(csound, Str("cannot open %s."), O.outfilename); return -1; } /* register file to be closed by csoundReset() */ (void)csound->CreateFileHandle(csound, &outfd, CSFILE_SND_W, O.outfilename); sf_command(outfd, SFC_SET_CLIPPING, NULL, SF_TRUE); } csound->SetUtilSr(csound, (MYFLT)p->sr); csound->SetUtilNchnls(csound, Chans = p->nchanls); /* read header info */ if (R < FL(0.0)) R = (MYFLT)p->sr; if (Chans < 0) Chans = (int) p->nchanls; p->nchanls = Chans; if (Chans > 2) { csound->Message(csound, Str("dnoise: input MUST be mono or stereo\n")); return -1; } /* read noise reference file */ if ((fp = csound->SAsndgetset(csound, nfile, &pn, &beg_ntime, &input_ndur, &srn, channel)) == NULL) { csound->Message(csound, Str("dnoise: cannot open noise reference file\n")); return -1; } if (sr != srn) { csound->Message(csound, Str("Incompatible sample rates\n")); return -1; } /* calculate begin and end times in NOISE file */ if (beg >= FL(0.0)) Beg = (long) (beg * R); if (end >= FL(0.0)) End = (long) (end * R); else if (End == 99999999) End = (long) (input_ndur * R); nMin = Beg * Chans; /* total number of samples to skip */ nMax = End - Beg; /* number of samples per channel to process */ /* largest valid FFT size is 8192 */ if (N == 0) N = 1024; for (i = 1; i < 4096; i *= 2) if (i >= N) break; if (i != N) csound->Message(csound, Str("dnoise: warning - N not a valid power of two; " "revised N = %d\n"),i); N = i; N2 = N / 2; Np2 = N + 2; Ninv = FL(1.0) / N; if (W != -1) { if (M != 0) csound->Message(csound, Str("dnoise: warning - do not specify both M and W\n")); else if (W == 0) M = 4*N; else if (W == 1) M = 2*N; else if (W == 2) M = N; else if (W == 3) M = N2; else csound->Message(csound, Str("dnoise: warning - invalid W ignored\n")); } if (M == 0) M = N; if ((M%2) == 0) Meven = 1; if (L == 0) L = M; if ((L%2) == 0) Leven = 1; if (M < 7) { csound->Message(csound, Str("dnoise: warning - M is too small\n")); exit(~1); } if (D == 0) D = M / 8; I = D; lj = (long) M + 3 * (long) D; lj *= (long) Chans; if (lj > 32767) { csound->Message(csound, Str("dnoise: M too large\n")); return -1; } lj = (long) L + 3 * (long) I; lj *= (long) Chans; if (lj > 32767) { csound->Message(csound, Str("dnoise: L too large\n")); return -1; } ibuflen = Chans * (M + 3 * D); obuflen = Chans * (L + 3 * I); outbufsiz = obuflen * sizeof(MYFLT); /* calc outbuf size */ #if 0 outbuf = csound->Malloc(csound, (size_t) outbufsiz); /* & alloc bufspace */ #endif csound->Message(csound, Str("writing %u-byte blks of %s to %s"), outbufsiz, csound->getstrformat(O.outformat), O.outfilename); csound->Message(csound, " (%s)\n", csound->type2string(O.filetyp)); /* spoutran = spoutsf; */ minv = FL(1.0) / (MYFLT)m; md = m / 2; g0 = (MYFLT) pow(10.0,(double)(0.05*(double)g0)); g0m = FL(1.0) - g0; th = (MYFLT) pow(10.0,(double)(0.05*(double)th)); /* set up analysis window: The window is assumed to be symmetric with M total points. After the initial memory allocation, aWin always points to the midpoint of the window (or one half sample to the right, if M is even); aLen is half the true window length (rounded down). If the window duration is longer than the transform (M > N), then the window is multiplied by a sin(x)/x function to meet the condition: aWin[Ni] = 0 for i != 0. In either case, the window is renormalized so that the phase vocoder amplitude estimates are properly scaled. */ if ((aWin = (MYFLT*) csound->Calloc(csound, (M+Meven) * sizeof(MYFLT))) == NULL) { ERR(Str("dnoise: insufficient memory\n")); } aLen = M/2; aWin += aLen; hamming(aWin, aLen, Meven); for (i = 1; i <= aLen; i++) { aWin[-i] = aWin[i-1]; } if (M > N) { if (Meven) *aWin *= (MYFLT)N * (MYFLT) sin(PI*0.5/(double)N) /( PI_F*FL(0.5)); for (i = 1; i <= aLen; i++) aWin[i] *= (MYFLT) (N * sin(PI * ((double) i + 0.5 * (double) Meven) / (double) N) / (PI * (i + 0.5 * (double) Meven))); for (i = 1; i <= aLen; i++) aWin[-i] = aWin[i - Meven]; } sum = FL(0.0); for (i = -aLen; i <= aLen; i++) sum += aWin[i]; sum = FL(2.0) / sum; /* factor of 2 comes in later in trig identity */ for (i = -aLen; i <= aLen; i++) aWin[i] *= sum; /* set up synthesis window: For the minimal mean-square-error formulation (valid for N >= M), the synthesis window is identical to the analysis window (except for a scale factor), and both are even in length. If N < M, then an interpolating synthesis window is used. */ if ((sWin = (MYFLT*) csound->Calloc(csound, (L+Leven) * sizeof(MYFLT))) == NULL) { ERR(Str("dnoise: insufficient memory\n")); } sLen = L/2; sWin += sLen; if (M <= N) { hamming(sWin, sLen, Leven); for (i = 1; i <= sLen; i++) sWin[-i] = sWin[i - Leven]; for (i = -sLen; i <= sLen; i++) sWin[i] *= sum; sum = FL(0.0); for (i = -sLen; i <= sLen; i+=I) sum += sWin[i] * sWin[i]; sum = FL(1.0) / sum; for (i = -sLen; i <= sLen; i++) sWin[i] *= sum; } else { hamming(sWin, sLen, Leven); for (i = 1; i <= sLen; i++) sWin[-i] = sWin[i - Leven]; if (Leven) *sWin *= (MYFLT) (I * sin(PI*0.5/(double) I) / (PI*0.5)); for (i = 1; i <= sLen; i++) sWin[i] *= (MYFLT)(I * sin(PI * ((double) i + 0.5 * (double) Leven) / (double) I) / (PI * ((double) i + 0.5 * (double) Leven))); for (i = 1; i <= sLen; i++) sWin[i] = sWin[i - Leven]; sum = FL(1.0) / sum; for (i = -sLen; i <= sLen; i++) sWin[i] *= sum; } /* set up input buffer: nextIn always points to the next empty word in the input buffer (i.e., the sample following sample number (n + aLen)). If the buffer is full, then nextIn jumps back to the beginning, and the old values are written over. */ if ((ibuf1 = (MYFLT *) csound->Calloc(csound, ibuflen * sizeof(MYFLT))) == NULL) { ERR("dnoise: insufficient memory\n"); } if ((ibuf2 = (MYFLT *) csound->Calloc(csound, ibuflen * sizeof(MYFLT))) == NULL) { ERR(Str("dnoise: insufficient memory\n")); } /* set up output buffer: nextOut always points to the next word to be shifted out. The shift is simulated by writing the value to the standard output and then setting that word of the buffer to zero. When nextOut reaches the end of the buffer, it jumps back to the beginning. */ if ((obuf1 = (MYFLT*) csound->Calloc(csound, obuflen * sizeof(MYFLT))) == NULL) { ERR(Str("dnoise: insufficient memory\n")); } if ((obuf2 = (MYFLT*) csound->Calloc(csound, obuflen * sizeof(MYFLT))) == NULL) { ERR(Str("dnoise: insufficient memory\n")); } /* set up analysis buffer for (N/2 + 1) channels: The input is real, so the other channels are redundant. */ if ((fbuf = (MYFLT*) csound->Calloc(csound, Np2 * sizeof(MYFLT))) == NULL) { ERR(Str("dnoise: insufficient memory\n")); } /* noise reduction: calculate noise reference by taking as many consecutive FFT's as possible in noise soundfile, and averaging them all together. Multiply by th*th to establish threshold for noise-gating in each bin. */ if ((nref = (MYFLT*) csound->Calloc(csound, (N2 + 1) * sizeof(MYFLT))) == NULL) { ERR(Str("dnoise: insufficient memory\n")); } if ((mbuf = (MYFLT*) csound->Calloc(csound, (m * Np2) * sizeof(MYFLT))) == NULL) { ERR(Str("dnoise: insufficient memory\n")); } if ((nbuf = (MYFLT*) csound->Calloc(csound, (m * Np2) * sizeof(MYFLT))) == NULL) { ERR(Str("dnoise: insufficient memory\n")); } if ((rsum = (MYFLT*) csound->Calloc(csound, (N2 + 1) * sizeof(MYFLT))) == NULL) { ERR(Str("dnoise: insufficient memory\n")); } if ((ssum = (MYFLT*) csound->Calloc(csound, (N2 + 1) * sizeof(MYFLT))) == NULL) { ERR(Str("dnoise: insufficient memory\n")); } /* skip over nMin samples */ while (nMin > (long)ibuflen) { if (!csound->CheckEvents(csound)) csound->LongJmp(csound, 1); nread = csound->getsndin(csound, fp, ibuf1, ibuflen, pn); for(i=0; i < nread; i++) ibuf1[i] *= 1.0/csound->Get0dBFS(csound); if (nread < ibuflen) { ERR(Str("dnoise: begin time is greater than EOF of noise file!")); } nMin -= (long) ibuflen; } if (!csound->CheckEvents(csound)) csound->LongJmp(csound, 1); i = (int) nMin; nread = csound->getsndin(csound, fp, ibuf1, i, pn); for(i=0; i < nread; i++) ibuf1[i] *= 1.0/csound->Get0dBFS(csound); if (nread < i) { ERR(Str("dnoise: begin time is greater than EOF of noise file!")); } k = 0; lj = Beg; /* single channel only */ while (lj < End) { if (!csound->CheckEvents(csound)) csound->LongJmp(csound, 1); lj += (long) N; nread = csound->getsndin(csound, fp, fbuf, N, pn); for(i=0; i < nread; i++) fbuf[i] *= 1.0/csound->Get0dBFS(csound); if (nread < N) break; fbuf[N] = FL(0.0); fbuf[N + 1] = FL(0.0); fast(csound, fbuf, N); f = fbuf; for (i = 0; i <= N+1; i++, f++) *f *= Ninv; f = nref; i0 = fbuf; i1 = i0 + 1; for (i = 0; i <= N2; i++, f++, i0 += 2, i1 += 2) { fac = *i0 * *i0; /* fac = fbuf[2*i] * fbuf[2*i]; */ fac += *i1 * *i1; /* fac += fbuf[2*i+1] * fbuf[2*i+1]; */ *f += fac; /* nref[i] += fac; */ } k++; } if (k == 0) { ERR(Str("dnoise: not enough samples of noise reference\n")); } fac = th * th / k; f = nref; for (i = 0; i <= N2; i++, f++) *f *= fac; /* nref[i] *= fac; */ /* initialization: input time starts negative so that the rightmost edge of the analysis filter just catches the first non-zero input samples; output time equals input time. */ /* zero ibuf1 to start */ f = ibuf1; for (i = 0; i < ibuflen; i++, f++) *f = FL(0.0); if (!csound->CheckEvents(csound)) csound->LongJmp(csound, 1); /* fill ibuf2 to start */ nread = csound->getsndin(csound, inf, ibuf2, ibuflen, p); /* nread = read(inf, ibuf2, ibuflen*sizeof(MYFLT)); */ /* nread /= sizeof(MYFLT); */ for(i=0; i < nread; i++) ibuf2[i] *= 1.0/csound->Get0dBFS(csound); lnread = nread; f = ibuf2 + nread; for (i = nread; i < ibuflen; i++, f++) *f = FL(0.0); //rIn = ((MYFLT) R / D); //rOut = ((MYFLT) R / I); invR = FL(1.0) / R; nI = -(aLen / D) * D; /* input time (in samples) */ nO = nI; /* output time (in samples) */ ibs = ibuflen + Chans * (nI - aLen - 1); /* starting position in ib1 */ ib1 = ibuf1; /* filled with zeros to start */ ib2 = ibuf2; /* first buffer of speech */ obs = Chans * (nO - sLen - 1); /* starting position in ob1 */ while (obs < 0) { obs += obuflen; first++; } ob1 = obuf1; /* filled with garbage to start */ ob2 = obuf2; /* first output buffer */ nImodR = nI; /* for reporting progress */ mi = 0; mj = m - md; if (mj >= m) mj = 0; mp = mi * Np2; nMax = (long)(input_dur * R); /* Do it all */ nMaxOut = (long) (nMax * Chans); while (nI < (nMax + aLen)) { time = nI * invR; for (chan = 0; chan < Chans; chan++) { /* prepare for analysis: always begin reading from ib1 */ /* always begin writing to ob1 */ if (ibs >= ibuflen) { /* done reading from ib1 */ if (!csound->CheckEvents(csound)) csound->LongJmp(csound, 1); /* swap buffers */ ib0 = ib1; ib1 = ib2; ib2 = ib0; ibs -= ibuflen; /* fill ib2 */ nread = csound->getsndin(csound, inf, ib2, ibuflen, p); for(i=0; i < nread; i++) ibuf2[i] *= 1.0/csound->Get0dBFS(csound); lnread += nread; f = ib2 + nread; for (i = nread; i < ibuflen; i++, f++) *f = FL(0.0); } ibc = ibs + chan; ibp = ib1 + ibs + chan; if (obs >= obuflen) { /* done writing to ob1 */ /* dump ob1 (except at beginning) */ if (first > 0) { first--; } else { if ((oCnt + obuflen) < nMaxOut) { oCnt += writebuffer(csound, outfd, ob1, obuflen, &nrecs, &O); } else { i = (int) (nMaxOut - oCnt); oCnt += writebuffer(csound, outfd, ob1, i, &nrecs, &O); } } /* zero ob1 */ f = ob1; for (i = 0; i < obuflen; i++, f++) *f = FL(0.0); /* swap buffers */ ob0 = ob1; ob1 = ob2; ob2 = ob0; obs -= obuflen; } obc = obs + chan; obp = ob1 + obs + chan; /* analysis: The analysis subroutine computes the complex output at time n of (N/2 + 1) of the phase vocoder channels. It operates on input samples (n - aLen) thru (n + aLen). It expects aWin to point to the center of a symmetric window of length (2 * aLen + 1). It is the responsibility of the main program to ensure that these values are correct. The results are returned in fbuf as succesive pairs of real and imaginary values for the lowest (N/2 + 1) channels. The subroutine fast implements an efficient FFT call for a real input sequence. */ f = fbuf; for (i = 0; i < N+2; i++, f++) *f = FL(0.0); lk = nI - (long) aLen - 1; /*time shift*/ while ((long) lk < 0L) lk += (long) N; k = (int) (lk % (long) N); f = fbuf + k; w = aWin - aLen; for (i = -aLen; i <= aLen; i++, k++, f++, w++) { ibp += Chans; ibc += Chans; if (ibc >= ibuflen) { ibc = chan; ibp = ib2 + chan; } if (k >= N) { k = 0; f = fbuf; } *f += *w * *ibp; } fast(csound, fbuf, N); /* noise reduction: for each bin, calculate average magnitude-squared and calculate corresponding gain. Apply this gain to delayed FFT values in mbuf[mj*Np2 + i?]. */ if (chan == 0) { f = rsum; i0 = mbuf + mp; i1 = i0 + 1; j0 = mbuf + mj * Np2; j1 = j0 + 1; f0 = fbuf; f1 = f0 + 1; for (i = 0; i <= N2; i++, f++, i0+=2, i1+=2, f0+=2, f1+=2, j0+=2, j1+=2) { /* * ii0 = 2 * i; * ii1 = ii0 + 1; * * rsum[i] -= mbuf[mp + ii0] * mbuf[mp + ii0]; * rsum[i] -= mbuf[mp + ii1] * mbuf[mp + ii1]; * rsum[i] += fbuf[ii0] * fbuf[ii0]; * rsum[i] += fbuf[ii1] * fbuf[ii1]; */ *f -= *i0 * *i0; *f -= *i1 * *i1; *f += *f0 * *f0; *f += *f1 * *f1; avg = minv * *f; /* avg = minv * rsum[i]; */ if (avg < FL(0.0)) avg = FL(0.0); if (avg == FL(0.0)) fac = FL(0.0); else fac = avg / (avg + nref[i]); for (j = 1; j < sh; j++) fac *= fac; gain = g0m * fac + g0; /* * mbuf[mp + ii0] = fbuf[ii0]; * mbuf[mp + ii1] = fbuf[ii1]; * fbuf[ii0] = gain * mbuf[mj*Np2 + ii0]; * fbuf[ii1] = gain * mbuf[mj*Np2 + ii1]; */ *i0 = *f0; *i1 = *f1; *f0 = gain * *j0; *f1 = gain * *j1; } } else { f = ssum; i0 = nbuf + mp; i1 = i0 + 1; j0 = nbuf + mj * Np2; j1 = j0 + 1; f0 = fbuf; f1 = f0 + 1; for (i = 0; i <= N2; i++, f++, i0+=2, i1+=2, f0+=2, f1+=2, j0+=2, j1+=2) { /* * ii0 = 2 * i; * ii1 = ii0 + 1; * * ssum[i] -= nbuf[mp + ii0] * nbuf[mp + ii0]; * ssum[i] -= nbuf[mp + ii1] * nbuf[mp + ii1]; * ssum[i] += fbuf[ii0] * fbuf[ii0]; * ssum[i] += fbuf[ii1] * fbuf[ii1]; */ *f -= *i0 * *i0; *f -= *i1 * *i1; *f += *f0 * *f0; *f += *f1 * *f1; avg = minv * *f; /* avg = minv * ssum[i]; */ if (avg < FL(0.0)) avg = FL(0.0); if (avg == FL(0.0)) fac = FL(0.0); else fac = avg / (avg + nref[i]); for (j = 1; j < sh; j++) fac *= fac; gain = g0m * fac + g0; /* * nbuf[mp + ii0] = fbuf[ii0]; * nbuf[mp + ii1] = fbuf[ii1]; * fbuf[ii0] = gain * nbuf[mj*Np2 + ii0]; * fbuf[ii1] = gain * nbuf[mj*Np2 + ii1]; */ *i0 = *f0; *i1 = *f1; *f0 = gain * *j0; *f1 = gain * *j1; } } if (chan == (Chans - 1)) { if (++mi >= m) mi = 0; if (++mj >= m) mj = 0; mp = mi * Np2; } /* synthesis: The synthesis subroutine uses the Weighted Overlap-Add technique to reconstruct the time-domain signal. The (N/2 + 1) phase vocoder channel outputs at time n are inverse Fourier transformed, windowed, and added into the output array. */ fsst(csound, fbuf, N); lk = nO - (long) sLen - 1; /*time shift*/ while (lk < 0) lk += (long) N; k = (int) (lk % (long) N); f = fbuf + k; w = sWin - sLen; for (i = -sLen; i <= sLen; i++, k++, f++, w++) { obp += Chans; obc += Chans; if (obc >= obuflen) { obc = chan; obp = ob2 + chan; } if (k >= N) { k = 0; f = fbuf; } *obp += *w * *f; } if (flag) { if (nread < ibuflen) { /* EOF detected */ flag = 0; if ((lnread / Chans) < nMax) nMax = (lnread / Chans); } } } ibs += (Chans * D); /* starting point in ibuf */ obs += (Chans * I); /* starting point in obuf */ nI += (long) D; /* increment time */ nO += (long) I; if (Verbose) { nImodR += D; if (nImodR > (long) R) { nImodR -= (long) R; csound->Message(csound, Str("%5.1f seconds of input complete\n"),(time+D*invR)); } } } nMaxOut = (long) (nMax * Chans); i = (int) (nMaxOut - oCnt); if (i > obuflen) { writebuffer(csound, outfd, ob1, obuflen, &nrecs, &O); i -= obuflen; ob1 = ob2; } if (i > 0) writebuffer(csound, outfd, ob1, i, &nrecs, &O); /* csound->rewriteheader(outfd); */ csound->Message(csound, "\n\n"); if (Verbose) { csound->Message(csound, Str("processing complete\n")); csound->Message(csound, "N = %d\n", N); csound->Message(csound, "M = %d\n", M); csound->Message(csound, "L = %d\n", L); csound->Message(csound, "D = %d\n", D); } return 0; }
char &str::operator[](long i) { if (i < 0) i += size(); return fast(i); }
char str::operator[](long i) const { if (i < 0) i += size(); return fast(i); }