void Psola::freq2MidiCents() { for (int n=0; n<nBlocks; n++) { if (f0[n]!=0) { midi[n] = 69 + round( 12.0*log2(f0[n]/440) ); float midiFreq = 440*pow(2.0, ((float)midi[n]-69.0)/12.0 ); cents[n] = 1200*log2(f0[n]/midiFreq); } else { midi[n] = 0; cents[n] = 0; } } medianFilter(midi, nBlocks, 7); for (int n=1; n<nBlocks; n++) { if (midi[n]!=midi[n-1]) { pitchBorders.push_back(n*HOP_SIZE); midiNums.push_back(midi[n-1]); centDeviations.push_back(cents[n-1]); } } pitchBorders.push_back(nBlocks*HOP_SIZE+BLOCK_SIZE-1); midiNums.push_back(midi[nBlocks]); centDeviations.push_back(cents[nBlocks]); }
/* src: input image method: name of noise reduction method that shall be performed "average" ==> moving average "median" ==> median filter "adaptive" ==> edge preserving average filter "bilateral" ==> bilateral filter kSize: (spatial) kernel size param: if method == "adaptive" : threshold ; if method == "bilateral" standard-deviation of radiometric kernel can be ignored otherwise (default value = 0) return: output image */ Mat Dip2::noiseReduction(Mat& src, string method, int kSize, double param){ // apply moving average filter if (method.compare("average") == 0){ return averageFilter(src, kSize); } // apply median filter if (method.compare("median") == 0){ return medianFilter(src, kSize); } // apply adaptive average filter if (method.compare("adaptive") == 0){ return adaptiveFilter(src, kSize, param); } // apply bilateral filter if (method.compare("bilateral") == 0){ return bilateralFilter(src, kSize, param); } // if none of above, throw warning and return copy of original cout << "WARNING: Unknown filtering method! Returning original" << endl; cout << "Press enter to continue" << endl; cin.get(); return src.clone(); }
int getDistance(int channel){ static const int adcCh[2] ={2,3}; static int distanceValue[2][9]={{255,255,255,255,255,255,255,255,255} ,{255,255,255,255,255,255,255,255,255} }; int tempData[9]; volatile int i,adcValue,distance; adcValue = (int)A2D_GetSingleCh_10bit((unsigned long)adcCh[channel]); adcValue = (int)adcToDistance(adcValue); //new distance //shift for(i=8;i>0;i--) distanceValue[channel][i] = distanceValue[channel][i-1]; distanceValue[channel][0] = adcValue; for(i=0;i<9;i++) tempData[i] = distanceValue[channel][i]; //median filter distance = medianFilter(tempData,9,5); return distance; }
// Calibrate the vertical distance (in meters) of the front sensor to the floor // people typically hold a walking stick at a 45-degree angle // calibrated threshold for front sensor is the hypotenuse of a 45-45-90 triangle, // with the vertical distance as a leg of the triangle void calibrateFront(void) { float sonarFront = 0; float calibArray[nCalibCycles]; for (int i = 0; i < 2*nCalibCycles; i++) { //turn on RX of sonar3 PORTC = PORTC ^ 0x08; _delay_ms(80); // read ADC of front sensor and convert to meters sonarFront = adc_read(2); calibArray[i%nCalibCycles] = (float)sonarFront * 0.0508;// distance = adc reading * (5/256)*(512/5)*.0254 _delay_ms(30); //turn off RX PORTC = PORTC ^ 0x08; _delay_ms(30); } F_calibrated = medianFilter(calibArray) * 1.41; // hypotenuse of 45-45-90 triangle -> sqrt(2) = 1.41 //fprintf(stdout, "val: %f, %f, %f\n\r", calibArray[0], calibArray[1], calibArray[2]); //fprintf(stdout, "val: %f\n\r", F_calibrated); }
void DFProcess::process(double *src, double* dst) { if (m_length == 0) return; removeDCNormalize( src, filtSrc ); m_FiltFilt->process( filtSrc, filtDst, m_length ); medianFilter( filtDst, dst ); }
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); connect(ui->actionOpen, SIGNAL(triggered()), this, SLOT(open())); connect(ui->actionReset, SIGNAL(triggered()), this, SLOT(reset())); connect(ui->btn_Left, SIGNAL(clicked()), this, SLOT(turnLeft())); connect(ui->btn_Right, SIGNAL(clicked()), this, SLOT(turnRight())); connect(ui->actionRgb2gray, SIGNAL(triggered()), this, SLOT(rgb2gray())); connect(ui->actionRgb2bw, SIGNAL(triggered()), this, SLOT(rgb2bw())); connect(ui->actionNegative, SIGNAL(triggered()), this, SLOT(negative())); connect(ui->actionStretch, SIGNAL(triggered()), this, SLOT(stretch())); connect(ui->actionLog, SIGNAL(triggered()), this, SLOT(log())); connect(ui->actionHistogramEqualize, SIGNAL(triggered()), this, SLOT(histogramEqualize())); connect(ui->actionHistogramExactSpecifiedEqualize, SIGNAL(triggered()), this, SLOT(histogramExactSpecifiedEqualize())); connect(ui->actionSpatialFilter, SIGNAL(triggered()), this, SLOT(spatialFilter())); connect(ui->actionMedianFilter, SIGNAL(triggered()), this, SLOT(medianFilter())); connect(ui->actionFFT, SIGNAL(triggered()), this, SLOT(makeFFT())); connect(ui->actionOilPaint, SIGNAL(triggered()), this, SLOT(oilPaint())); connect(ui->actionRelief, SIGNAL(triggered()), this, SLOT(relief())); connect(ui->actionEdgeExtraction, SIGNAL(triggered()), this, SLOT(edgeExtraction())); connect(ui->actionGaussianBlur, SIGNAL(triggered()), this, SLOT(gaussianBlur())); connect(ui->actionOpenOperate, SIGNAL(triggered()), this, SLOT(openOp())); connect(ui->actionCloseOperate, SIGNAL(triggered()), this, SLOT(closeOp())); connect(ui->actionExpansion, SIGNAL(triggered()), this, SLOT(expansionOp())); connect(ui->actionCorrosion, SIGNAL(triggered()), this, SLOT(corrosionOp())); connect(ui->checkBox, SIGNAL(toggled(bool)), this, SLOT(saveCheck(bool))); connect(ui->actionSave, SIGNAL(triggered()), this, SLOT(save())); this->ui->graphicsView->setScene(Q_NULLPTR); this->pixmapItem = Q_NULLPTR; this->directory = new QDir(); this->imageProcessor = Q_NULLPTR; this->ui->actionReset->setEnabled(false); this->ui->btn_Left->setEnabled(false); this->ui->btn_Right->setEnabled(false); this->ui->actionRgb2gray->setEnabled(false); this->ui->actionRgb2bw->setEnabled(false); this->ui->actionNegative->setEnabled(false); this->ui->actionStretch->setEnabled(false); this->ui->actionLog->setEnabled(false); this->ui->actionHistogramEqualize->setEnabled(false); this->ui->actionHistogramExactSpecifiedEqualize->setEnabled(false); this->ui->actionSpatialFilter->setEnabled(false); this->ui->actionMedianFilter->setEnabled(false); this->ui->actionFFT->setEnabled(false); this->ui->actionOilPaint->setEnabled(false); this->ui->actionRelief->setEnabled(false); this->ui->actionEdgeExtraction->setEnabled(false); this->ui->actionGaussianBlur->setEnabled(false); this->ui->actionSave->setEnabled(false); }
int sonarGetDistance(void){ static int distanceValue[9]={ 9999,9999,9999,9999,9999,9999,9999,9999,9999 }; static const int ch =0; unsigned long int tempDistance,temp; volatile int i,distance; int tempData[9]; switch(sonarStatus){ case SONAR_WAIT_RISING: //sonar trigger GPIO_SetState(SONAR0_CONTROL_CH,1); for(i=0;i<110;i++); GPIO_SetState(SONAR0_CONTROL_CH,0); SIU.IRER.R = 0x00000001; //set rising temp = SIU.IREER.R; temp |= (1<<ch); SIU.IREER.R = temp; temp = SIU.IFEER.R; temp &= ~(1<<ch); SIU.IFEER.R = temp; break; case SONAR_WAIT_END: sonarStatus = SONAR_WAIT_RISING; break; } tempDistance = counter; distance = counterToDistance(tempDistance); //shift for(i=8;i>0;i--) distanceValue[i] = distanceValue[i-1]; distanceValue[0] = distance; for(i=0;i<9;i++) tempData[i] = distanceValue[i]; //median filter distance = medianFilter(tempData,9,5); return distance; }
void Psola::getPitches() { int minLag = (int)floor(SAMPLE_RATE/FREQUENCY_UPPER_LIMIT); float rmsMax = 0; for (int n = 0; n<nBlocks; n++) { //compute RMS for each block blockRMS[n] = 0; for (int i = 0; i<BLOCK_SIZE; i++) { blockRMS[n] += audioIn[n*HOP_SIZE+i]*audioIn[n*HOP_SIZE+i]; } blockRMS[n] = sqrt(blockRMS[n]/BLOCK_SIZE); if (rmsMax<blockRMS[n]) { rmsMax=blockRMS[n]; } //compute autocorrelation halfAutoCorr(n*HOP_SIZE); int zeroIndex = getZeroCrsIndex(); //Pick the larger value between minimum lag and zero crossing int initLag = (minLag>zeroIndex)?minLag:zeroIndex; //find index of acf maximum after initial lag int maxInd = initLag; for (int i = initLag; i<BLOCK_SIZE; i++) { if (acf[i]>acf[maxInd]) { maxInd = i; } } //get the fundamental freq from max acf f0[n] = SAMPLE_RATE/(float)maxInd; } medianFilter(f0, nBlocks, MEDIAN_FILTER_LENGTH); for (int n = 0; n<nBlocks; n++) { if (blockRMS[n]<0.05*rmsMax) { f0[n] = 0; } } }
bool filtering::getPreprocessedCloud(pcl::PointCloud<PointType>::Ptr preprocessed_cloud_ptr){ if(number_of_average_clouds_ + number_of_median_clouds_ > cloud_vector_.size()){ std::cout << "There are too few clouds in the input vector, for these filter parameters!" << std::endl; return false; } if(!medianFilter(*preprocessed_cloud_ptr)) return false; if(!averageFilter(*preprocessed_cloud_ptr)) return false; if(!planarSegmentation(preprocessed_cloud_ptr)) std::cout << "Couldn't find a plane!" << std::endl; return true; }
// checks basic properties of the filtering result void Dip2::test_medianFilter(void){ Mat input = Mat::ones(9,9, CV_32FC1); input.at<float>(4,4) = 255; Mat output = medianFilter(input, 3); if ( (input.cols != output.cols) || (input.rows != output.rows) ){ cout << "ERROR: Dip2::medianFilter(): input.size != output.size --> Wrong border handling?" << endl; return; } if ( (sum(output.row(0) < 0).val[0] > 0) || (sum(output.row(0) > 255).val[0] > 0) || (sum(output.row(8) < 0).val[0] > 0) || (sum(output.row(8) > 255).val[0] > 0) || (sum(output.col(0) < 0).val[0] > 0) || (sum(output.col(0) > 255).val[0] > 0) || (sum(output.col(8) < 0).val[0] > 0) || (sum(output.col(8) > 255).val[0] > 0) ){ cout << "ERROR: Dip2::medianFilter(): Border of convolution result contains too large/small values --> Wrong border handling?" << endl; return; }else{ if ( (sum(output < 0).val[0] > 0) || (sum(output > 255).val[0] > 0) ){ cout << "ERROR: Dip2::medianFilter(): Convolution result contains too large/small values!" << endl; return; } } for(int y=1; y<8; y++){ for(int x=1; x<8; x++){ if (abs(output.at<float>(y,x) - 1.) > 0.0001){ cout << "ERROR: Dip2::medianFilter(): Result contains wrong values!" << endl; return; } } } cout << "Message: Dip2::medianFilter() seems to be correct" << endl; }
void MainWindow::median() { image = medianFilter(image); setImages(); }
void smoothCompletedHour(IPResponseTimes &ipResponseTimes, SmoothedValues &smoothedValues, PrevBinTime &prevBinTime, const size_t &, const uint32_t &hourStartTime, SmoothedReadings &smoothedReadings){ /*Variables that maintain bin states for each IP*/ uint32_t currentInterval, binReadingCount, binStartTime, currentTime, binIndex, firstBinTime=0; std::vector <double> bins; double minBinReading=0, previousBinReading=0; std::set <uint32_t> processedIPs; std::vector<std::pair <uint32_t, double> > filteredDelta; std::vector<std::pair <uint32_t, double> >::iterator rTimingsLastElement; std::map<uint32_t, SmoothedReadings>::iterator smoothedValuesItr(smoothedValues.end()); /*Looping through completed hour's data*/ for(std::map <uint32_t, ResponseTimings>::const_iterator ipRTimesItr = ipResponseTimes.begin(); ipRTimesItr != ipResponseTimes.end(); ++ipRTimesItr) { smoothedValuesItr = smoothedValues.end(); binIndex=0;firstBinTime=0;binReadingCount=0; processedIPs.insert(ipRTimesItr->first); filteredDelta.clear(); /*applying median filter with 5 spatial moments*/ filteredDelta = medianFilter(ipRTimesItr->second, MEDIAN_FILTER_MAX_SIZE); /*If IP is new add it to smoothed timings and set bin start time as current hours start time*/ if(!isSeenIP(ipRTimesItr->first, prevBinTime)) { smoothedValuesItr = smoothedValues.insert(std::make_pair(ipRTimesItr->first, SmoothedReadings())).first; binStartTime = hourStartTime; minBinReading = previousBinReading = filteredDelta.begin()->second; firstBinTime = binStartTime; } /*If IP already exists in smoothed timings map read out the last bin time from prevBinTime map, move the bin offset to current hour*/ else{ smoothedValuesItr = smoothedValues.find(ipRTimesItr->first); if(smoothedValuesItr == smoothedValues.end()) smoothedValuesItr = smoothedValues.insert(std::make_pair(ipRTimesItr->first, SmoothedReadings())).first; binStartTime = getLastBinEndTime(ipRTimesItr->first, prevBinTime); if(binStartTime > hourStartTime) binStartTime = hourStartTime; while(binStartTime < hourStartTime){ binStartTime += BIN_SIZE; } previousBinReading = getLastBinValue(ipRTimesItr->first, prevBinTime); minBinReading = filteredDelta.begin()->second; if(!firstBinTime){ firstBinTime = binStartTime; } } rTimingsLastElement = filteredDelta.end(); --rTimingsLastElement; for(std::vector <std::pair <uint32_t, double> >::const_iterator rTimingsItr = filteredDelta.begin(); rTimingsItr != filteredDelta.end(); ++rTimingsItr) { currentTime = rTimingsItr->first; /*This bucket was already closed last hour, pushing value to new bucket*/ if(binStartTime > currentTime ){ currentTime = binStartTime; } /*Detemining bin interval*/ currentInterval = (currentTime - binStartTime)/BIN_SIZE; /*Either a value in a new bin was seen OR we know no further readings exist for this IP*/ if(currentInterval > 0 || rTimingsItr == rTimingsLastElement){ if(rTimingsItr == rTimingsLastElement){ /*Still in current interval, just close open bin*/ if(currentInterval == 0){ bins.push_back(rTimingsItr->second); minBinReading = *(bins.begin() + bins.size()/2) ; ++binReadingCount; fillBins(smoothedValuesItr, ipRTimesItr->first, smoothedReadings, binIndex, minBinReading, firstBinTime, 1, binReadingCount); binStartTime += BIN_SIZE; } /*Fill all missed intervals and current interval*/ else{ if(binReadingCount){ fillBins(smoothedValuesItr, ipRTimesItr->first, smoothedReadings, binIndex, minBinReading, firstBinTime, currentInterval, binReadingCount); } else{ fillBins(smoothedValuesItr, ipRTimesItr->first, smoothedReadings, binIndex, previousBinReading, firstBinTime, currentInterval, binReadingCount); } /*Also write current new bin since no more values will be seen*/ minBinReading = rTimingsItr->second; /*Additional +1 since we also close current bin*/ binStartTime += (currentInterval+1) * BIN_SIZE; fillBins(smoothedValuesItr, ipRTimesItr->first, smoothedReadings, binIndex, minBinReading, firstBinTime, 1, 1); previousBinReading = minBinReading; } /*Now lets make sure we pad empty bins for this hour*/ if(binIndex < BINS_IN_HOUR){ fillBins(smoothedValuesItr, ipRTimesItr->first, smoothedReadings, binIndex, previousBinReading, firstBinTime, BINS_IN_HOUR-binIndex, 0); binStartTime += (BINS_IN_HOUR-binIndex-1) * BIN_SIZE; } bins.clear(); } /*Close open bin, fill missing intervals and open new bin*/ else{ if(binReadingCount){ fillBins(smoothedValuesItr, ipRTimesItr->first, smoothedReadings, binIndex, minBinReading, firstBinTime, currentInterval, binReadingCount); binReadingCount = 1; previousBinReading = minBinReading; minBinReading = rTimingsItr->second; binStartTime += currentInterval * BIN_SIZE; } else{ fillBins(smoothedValuesItr, ipRTimesItr->first, smoothedReadings, binIndex, previousBinReading, firstBinTime, currentInterval, binReadingCount); binReadingCount = 1; minBinReading = rTimingsItr->second; binStartTime += currentInterval * BIN_SIZE; } bins.clear(); } } /*Current bin value was read, Just updating minimum bin reading and count */ else{ bins.push_back(rTimingsItr->second); minBinReading = *(bins.begin() + bins.size()/2) ; ++binReadingCount; } } /*Done with current IP, store last bin time and last bin value*/ storePrevBinTime(ipRTimesItr->first, binStartTime, previousBinReading, prevBinTime); filteredDelta.clear(); } ipResponseTimes.clear(); /*Padding bins for IP's seen in previous hours but not in the current hour*/ for(std::map <uint32_t, std::pair<uint32_t, double> >::iterator prevBinTimeItr = prevBinTime.begin(); prevBinTimeItr != prevBinTime.end(); ++prevBinTimeItr) { smoothedValuesItr = smoothedValues.find(prevBinTimeItr->first); if(smoothedValuesItr == smoothedValues.end()) smoothedValuesItr = smoothedValues.insert(std::make_pair(prevBinTimeItr->first, SmoothedReadings())).first; if(processedIPs.find(prevBinTimeItr->first) == processedIPs.end()){ binIndex=0; firstBinTime = prevBinTimeItr->second.first; if(firstBinTime > hourStartTime){ firstBinTime = hourStartTime; } while(firstBinTime < hourStartTime){ firstBinTime += BIN_SIZE; } fillBins(smoothedValuesItr, prevBinTimeItr->first, smoothedReadings, binIndex, prevBinTimeItr->second.second, firstBinTime, BINS_IN_HOUR, 0); prevBinTimeItr->second.first += BIN_SIZE * BINS_IN_HOUR; } } processedIPs.clear(); }
// Navigation logic // send haptic feedback depending on distance from sensors void navLogic(void* args) { // where is the object? #define NONE 0 #define LEFT 1 #define RIGHT 2 int L_thresh = 2; int R_thresh = 2; uint8_t state = NONE; uint32_t rel, dead ; while(1) { if (firstRun == 0) // not the first run of this task { // Median filter if (iL >= 3) sonarL_range = medianFilter(rangeL); if (iR >= 3) sonarR_range = medianFilter(rangeR); if (iF >= 3) sonarF_range = medianFilter(rangeF); // obstacle found within threshold if ((sonarL_range < L_thresh) || (sonarR_range < R_thresh)) { if (sonarL_range < sonarR_range) state = LEFT; else if (sonarR_range < sonarL_range) state = RIGHT; } else { state = NONE; } switch (state) { case LEFT: { float durationL = 1/sonarL_range * 30; //pulse left PORTC = PORTC ^ 0x40; // PIN C6 //_delay_ms(90); _delay_ms(durationL); PORTC = PORTC ^ 0x40; state = NONE; } break; case RIGHT: { float durationR = 1/sonarR_range * 30; //pulse right PORTC = PORTC ^ 0x80; // PIN C7 //_delay_ms(90); _delay_ms(durationR); PORTC = PORTC ^ 0x80; state = NONE; } break; default: {} break; } // end of -- switch (state) } // end of -- if (firstRun == 0) // Sleep rel = trtCurrentTime() + SECONDS2TICKS(navFreq); dead = trtCurrentTime() + SECONDS2TICKS(navFreq+.1); trtSleepUntil(rel, dead); } // end of -- while }
int IEVChannelSumGadget::process(GadgetContainerMessage< ISMRMRD::ImageHeader>* m1) { GadgetContainerMessage<hoNDArray< float > > *unfiltered_unwrapped_msg_ptr = AsContainerMessage<hoNDArray<float>>(m1->cont()); GadgetContainerMessage<hoNDArray< float > > *filtered_unwrapped_msg_ptr = AsContainerMessage<hoNDArray<float>>(unfiltered_unwrapped_msg_ptr->cont()); GadgetContainerMessage<ISMRMRD::MetaContainer> *meta; static int c=0; int e; int echo = m1->getObjectPtr()->contrast; float inv_echo_time; int echo_offset=yres*xres*num_ch*echo; if(!filtered_unwrapped_msg_ptr || !unfiltered_unwrapped_msg_ptr) { GERROR("Wrong types received in IEVChannelSumGadget. Filtered and unfiltered phase expected.\n"); return GADGET_FAIL; } meta = AsContainerMessage<ISMRMRD::MetaContainer>(filtered_unwrapped_msg_ptr->cont()); //float* filtered_phase_ptr= filtered_unwrapped_msg_ptr->getObjectPtr()->get_data_ptr(); m1->getObjectPtr()->channels=1; //yes? inv_echo_time=1/echoTimes[echo];//to avoid millions of divisions per slice memcpy(filtered_phase_ptr+echo_offset, filtered_unwrapped_msg_ptr->getObjectPtr()->get_data_ptr(), xres*yres*num_ch*sizeof(float)); for (int i = 0; i < xres*yres*num_ch; i++) freq_ptr[echo_offset+i] = filtered_phase_ptr[echo_offset+i]*inv_echo_time; hdr_ptr[echo]=*(m1->getObjectPtr()); if(meta) { meta->getObjectPtr()->append("StudyInstanceUID", studyInstanceUID.c_str());//may be in xml header, may not be, in that case put it in xml so it can get to dicom char TE[10]; sprintf(TE, "%f", echoTimes[echo]*1000); meta->getObjectPtr()->append("TE", TE); attributes[echo]=*(meta->getObjectPtr()); } unfiltered_unwrapped_msg_ptr->release();//all data have been copied if(echo==(numEchos-1)) { float* weights= new float[xres*yres*num_ch]; float** channel_weights= new float* [num_ch]; float* to_normalize = new float[xres*yres]; int ch; if(iev.value()==int(IEV::YES))//just to allow this to work without IEV/make it very easy to compare { #pragma omp parallel //expanded parallel --- to allow sample to be allocated once { float* sample = new float[numEchos]; int start = omp_get_thread_num()/omp_get_num_threads()*xres*yres*num_ch; int end = (omp_get_thread_num()+1)/omp_get_num_threads()*xres*yres*num_ch; for(int i =start; i <end; i++) { ///////// for(int j = 0; j < numEchos; j++) sample[j]=freq_ptr[i+j*xres*yres*num_ch]; //assuming all(6-10 at at time) pages can be held in memory, this isn't terrible weights[i]=stdev(sample, numEchos); //find standard deviation between echoes ///// } delete[] sample; } #pragma omp parallel for private(ch) for(ch = 0; ch < num_ch; ch++) { float* temp_array; channel_weights[ch]=&weights[ch*xres*yres]; medianFilter(channel_weights[ch], xres, yres); for (int i = 0; i < xres*yres; i++) { channel_weights[ch][i]=1/(channel_weights[ch][i]+FLT_MIN); //weight as inverse, } } for (int i = 0; i < xres*yres; i++) to_normalize[i] = 0; for(int ch=0; ch< num_ch; ch++) for (int i = 0; i < xres*yres; i++) { to_normalize[i]+=channel_weights[ch][i]; } for(int ch=0; ch< num_ch; ch++) for (int i = 0; i < xres*yres; i++) { channel_weights[ch][i]/=to_normalize[i]; //normalize weights } } else { #pragma omp parallel for private(ch) for(int ch=0; ch< num_ch; ch++) { channel_weights[ch]=&weights[ch*xres*yres]; for (int i = 0; i < xres*yres; i++) { channel_weights[ch][i]=1; } } } for(e=0; e<numEchos; e++) { hdr_ptr[e].channels=1; hdr_ptr[e].contrast=e; hdr_ptr[e].data_type = ISMRMRD::ISMRMRD_FLOAT;//GADGET_IMAGE_REAL_FLOAT; hdr_ptr[e].image_type = ISMRMRD::ISMRMRD_IMTYPE_PHASE;//There is no frequency image type hdr_ptr[e].slice= (hdr_ptr[e].image_index) % num_slices;//was hdr_ptr[e].image_index___-1_____) % num_slices before decrementor was added upstream if(output_phase.value()) { // GadgetContainerMessage<ISMRMRD::ImageHeader>* phase_hdr = new GadgetContainerMessage<ISMRMRD::ImageHeader>(hdr_ptr[e]); //*(phase_hdr->getObjectPtr()) =*(hdr_ptr[e]->getObjectPtr()); GadgetContainerMessage<hoNDArray< float > > *comb_phase_msg = new GadgetContainerMessage<hoNDArray< float > >(); phase_hdr->getObjectPtr()->image_series_index=series_id_offset+1; try{comb_phase_msg->getObjectPtr()->create(xres,yres);} catch (std::runtime_error &err){ GEXCEPTION(err,"Unable to create output image\n"); return GADGET_FAIL; } float* output_ptr=comb_phase_msg->getObjectPtr()->get_data_ptr(); phase_hdr->cont(comb_phase_msg); // for (int i = 0; i < xres*yres; i++) { output_ptr[i]=filtered_phase_ptr[e*xres*yres*num_ch+i]*channel_weights[0][i]; //instead of setting to 0 and adding first channel } for(int ch=1; ch< num_ch; ch++) for (int i = 0; i < xres*yres; i++) { output_ptr[i]+=filtered_phase_ptr[e*xres*yres*num_ch+xres*yres*ch+i]*channel_weights[ch][i];; //instead of setting to 0 and adding first channel } // if(meta) { GadgetContainerMessage<ISMRMRD::MetaContainer>* meta = new GadgetContainerMessage<ISMRMRD::MetaContainer>(attributes[e]); comb_phase_msg->cont(meta); } // if (this->next()->putq(phase_hdr) == -1) { m1->release(); GERROR("Unable to put collapsed images on next gadget's queue\n"); return GADGET_FAIL; } } if(output_LFS.value()) { // GadgetContainerMessage<ISMRMRD::ImageHeader>* freq_hdr=new GadgetContainerMessage<ISMRMRD::ImageHeader>(hdr_ptr[e]); //*(freq_hdr->getObjectPtr()) =*(hdr_ptr[e]->getObjectPtr()); GadgetContainerMessage<hoNDArray< float > > *comb_freq_msg = new GadgetContainerMessage<hoNDArray< float > >(); freq_hdr->getObjectPtr()->image_series_index=series_id_offset+output_phase.value()+1; try{comb_freq_msg->getObjectPtr()->create(xres,yres);} catch (std::runtime_error &err){ GEXCEPTION(err,"Unable to create output image\n"); return GADGET_FAIL; } float* output_ptr=comb_freq_msg->getObjectPtr()->get_data_ptr(); freq_hdr->cont(comb_freq_msg); freq_hdr->getObjectPtr()->image_type = 6; // for (int i = 0; i < xres*yres; i++) output_ptr[i]=freq_ptr[e*xres*yres*num_ch+i]*channel_weights[0][i]; //instead of setting to 0 and adding first channel for(int ch=1; ch< num_ch; ch++) for (int i = 0; i < xres*yres; i++) { output_ptr[i]+=freq_ptr[e*xres*yres*num_ch+xres*yres*ch+i]*channel_weights[ch][i]; } // if(meta) { GadgetContainerMessage<ISMRMRD::MetaContainer>* meta = new GadgetContainerMessage<ISMRMRD::MetaContainer>(attributes[e]); meta->getObjectPtr()->set(GADGETRON_DATA_ROLE, GADGETRON_IMAGE_FREQMAP); //*(meta->getObjectPtr())=*(attributes[e]->getObjectPtr()); comb_freq_msg->cont(meta); } // if (this->next()->putq(freq_hdr) == -1) { //m1->release(); GERROR("Unable to put collapsed images on next gadget's queue\n"); return GADGET_FAIL; } } } delete[] to_normalize; delete[] weights; delete[] channel_weights; //if(output.value()==int(OUTPUT::PHASE)) // delete[] unfiltered_phase_ptr; } return GADGET_OK; }
medianFilter::medianFilter() { medianFilter(1,0); }
void generate_output_image() { assert(imageSize > 0); medianFilter(inputImage, outputImage, 1, IMAGE_HEIGHT, IMAGE_WIDTH); }
int main(int, char* argv[]) { // In assignment 2.1, we will fix filter_radius as 1, // and therefore it's filter size is 3x3. const unsigned int filter_radius = 1; unsigned int width, height; unsigned char* h_img = NULL; unsigned char* your_result = NULL; unsigned char* gold_result = NULL; // This is the filename of the image file in PGM format // and the file should be put under the subdirectory, "data". const char* image_filename = "test.pgm"; loadImage(&h_img, &width, &height, image_filename, argv[0]); if (width <= 2*filter_radius || height <= 2*filter_radius) { fprintf(stderr, "Filter radius is too large.\n"); exit(-1); } your_result = (unsigned char*) malloc(width*height*sizeof(unsigned char)); gold_result = (unsigned char*) malloc(width*height*sizeof(unsigned char)); // Run your median filter { unsigned int timer = 0; cutilCheckError(cutCreateTimer(&timer)); cutilCheckError(cutStartTimer(timer)); // You should implemnt medianFilter() in medianFilter_kernel.cu medianFilter(h_img, your_result, width, height, filter_radius); cutilCheckError(cutStopTimer(timer)); printf("[Yours] Processing time: %f (ms) \n", cutGetTimerValue(timer)); cutilCheckError(cutDeleteTimer(timer)); } // Run the reference median filter { unsigned int timer = 0; cutilCheckError(cutCreateTimer(&timer)); cutilCheckError(cutStartTimer(timer)); medianFilter_gold(h_img, gold_result, width, height, filter_radius); cutilCheckError(cutStopTimer(timer)); printf("[Gold] Processing time: %f (ms) \n", cutGetTimerValue(timer)); cutilCheckError(cutDeleteTimer(timer)); } // You can use saveImage() to save the result. // Under Windows, you can use IrfanView (http://www.irfanview.com/) to view PGM files. // Or you can convert PGM into JPEG, PNG, and etc. // saveImage(your_result, width, height, "output.pgm"); // saveImage(gold_result, width, height, "gold.pgm"); // Compare your result and the reference result. { if (test(your_result, gold_result, width, height, filter_radius)) { printf("PASSED\n"); } else { printf("FAILED\n"); } } free(gold_result); free(your_result); return 0; }