/* Merr si parametra nje imazh ne format Mat dhe nje string dhe e shfaq imazhin e bere blur ne 
   ne dritaren me emer @param emriDritares. Blur behet duke rreshkitur nje matrice katrore te 
   rendit n > 1(n tek) mbi imazh sipas metodes "Median Blur". 
   Shkalla me te cilen behen blur kontrollohet nga madhesia e matrices
   e cila caktohet nga perduruesi duke perdorur nje trackbar
 */
void Efekte::Blur_Or_Smooth(Mat &Imazh, string emriDritares)
{
    int vleraSliderBlur = 2; //vlera fillestare ne trackbar
    createTrackbar("Blur", emriDritares, &vleraSliderBlur, 41);
    cout << "Shtypni ESC per te caktivizuar blur" <<endl;
    while (true)
    {
        int madhesiaKernelit; //logaritet duke perdorur vleraSliderBlur
        if (vleraSliderBlur <=2){ // nuk behet dot blur sepse e do madhesine te pakten 3.
            goBack(Imazh);
        }
        else if ((vleraSliderBlur>2)&&(vleraSliderBlur%2 == 0)){ //nqs eshte >2 dhe cift
            goBack(Imazh); //shkohet si fillim ne foton origjinale
            madhesiaKernelit = vleraSliderBlur+1;
            medianBlur(Imazh,Imazh,madhesiaKernelit);
        }
        else if (vleraSliderBlur>2){ //nqs eshte > 2 dhe tek
            goBack(Imazh);
            madhesiaKernelit = vleraSliderBlur;
            medianBlur(Imazh,Imazh,madhesiaKernelit);
        }
        
        imshow(emriDritares, Imazh); // shfaqet imazhi ne dritare
        int key = waitKey(50);
        if (key==27)
        {
            cout << "Efekti u caktivizua";
            break;
        }
        
    }
    return;
}
Example #2
0
void DepthMap::SGBMdisparityCalc(Mat g1,Mat g2)
{
    cv::Ptr<cv::StereoSGBM> sgbm = cv::StereoSGBM::create(0,16,7);
    int sgbmWinSize = 3;
    sgbm->setBlockSize(3);
    sgbm->setDisp12MaxDiff(2);
    sgbm->setUniquenessRatio(10);
    sgbm->setMode(StereoSGBM::MODE_SGBM);
    sgbm->setMinDisparity(-32);
    sgbm->setNumDisparities(64);
    sgbm->setP1(8*g1.channels()*sgbmWinSize*sgbmWinSize);
    sgbm->setP2(32*g2.channels()*sgbmWinSize*sgbmWinSize);
    sgbm->setPreFilterCap(12);
    sgbm->setSpeckleRange(2);
    sgbm->setSpeckleWindowSize(200);
    sgbm->compute(g1, g2, disp);
    //sgbm->save("j.txt");
    normalize(disp, disp8, 0, 255, CV_MINMAX, CV_8U);
    imwrite("dispSGBM.png", disp);
    imwrite(disparityImage, disp8);

     //bilateralFilter(g1,g2,0,6.0,6.0);
    medianBlur(disp,dispf,5);
    medianBlur(disp8,dispf8,5);

    imwrite("dispSGBMMedian.png", dispf);
    imwrite("disp8SGBMMedian.png", dispf8);


}
/******************************************************************************
 * Input argument(s) : QImage *inputImage - Input image for the filter
 *                     const int &radius - Radius of structuring element
 *                     const bool &roiFlag - Flag to enable region of interest
 *                     QRect *roiRect - Region of  interest rectangle
 * Return type       : QImage* - Output image after median filtering
 * Functionality     : Function to apply median filter on the given
 *                     input image and returns the processed image
 ******************************************************************************/
QImage *ImageSmootheningFilter::applyMedianFilter(QImage *inputImage, const int &radius, const bool &roiFlag, QRect *roiRect) const
{
    cv::Mat inputMat =  qtOpenCVBridge->QImage2Mat(inputImage);
    cv::Mat outputMat = inputMat.clone();
    if(roiFlag == true){
        cv::Rect regionOfInterest(roiRect->x(), roiRect->y(), roiRect->width(), roiRect->height());
        cv::Mat croppedInputMat(inputMat, regionOfInterest);
        cv::Mat croppedOutputMat(outputMat, regionOfInterest);
        medianBlur(croppedInputMat, croppedOutputMat, radius);
    }
    else{
        medianBlur(inputMat, outputMat, radius);
    }
    return qtOpenCVBridge->Mat2QImage(outputMat);
}
Example #4
0
	void PostFilterSet::operator()(Mat& src, Mat& dest, int median_r, int gaussian_r, int minmax_r, int brange_r, int brange_th, int brange_method)
	{
		medianBlur(src, buff, 2 * median_r + 1);
		smallGaussianBlur(buff, buff, 2 * gaussian_r + 1, gaussian_r + 0.5);
		blurRemoveMinMax(buff, buff, minmax_r);
		binalyWeightedRangeFilter(buff, dest, Size(2 * brange_r + 1, 2 * brange_r + 1), (float)brange_th, brange_method);
	}
Example #5
0
FeaturesExtractor::FeaturesExtractor(string source, int div) {
	this->div = div;
	this->name = source;
	this->originalImg = imread(name);
	this->binaryImg = Mat(originalImg.rows, originalImg.cols, CV_BGR2GRAY);
	this->greyscaleImg = Mat(originalImg.rows, originalImg.cols, CV_THRESH_BINARY);

	// Preprocessing
	cvtColor(this->originalImg, this->greyscaleImg, CV_BGR2GRAY);
	medianBlur(this->greyscaleImg, this->greyscaleImg, 5);
	GaussianBlur(this->greyscaleImg, this->greyscaleImg, Size(3, 3), 0, 0, BORDER_DEFAULT);
	threshold(this->greyscaleImg, this->binaryImg, 230, 255, CV_THRESH_BINARY);

	// Calculation of BoudingBox
	Rect bb = this->find_boundingBox();

	// Division of imags
	// main image and sub-images are added to a vector
	this->originalBox = vector<Mat>(div + 1);
	this->binaryBox = vector<Mat>(div + 1);
	this->greyscaleBox = vector<Mat>(div + 1);

	try {
		this->greyscaleBox[0] = this->greyscaleImg(bb);
		this->binaryBox[0] = this->binaryImg(bb);
		this->originalBox[0] = this->originalImg(bb);
	} catch(...) {
		cout << "wrong " << name << endl; 
	}
	divide();	

	// computation of center of gravity on all (sub) images
	computeCoG();
}
void  getEndPointOfLine(const Mat & src,vector<Cline> & lines){
    
    //二值化
    Mat gray;
    cvtColor(src,gray,CV_BGR2GRAY);
    Mat binary;
    double thre = 10;
    double maxval = 255;
    threshold(gray, binary, thre, maxval,CV_THRESH_BINARY_INV);
    medianBlur(binary, binary, 3);
    //线的细化
    Mat bin;
    int intera = 8;
    imageThin(binary,bin,intera);
    //寻找曲线的端点
    vector<vector<Point> > contours;
    Mat copyBin;
    bin.copyTo(copyBin);
    findContours(copyBin, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
    for (size_t i = 0; i < contours.size(); i++) {
        if (contours[i].size() < 10) {
            continue;
        }
        vector<Point> endPoint;
        findEndPoint(bin,contours[i], endPoint);
        if (endPoint.size() > 0) {
            Cline line;
            line.numPoint = (int)endPoint.size();
            for (size_t k = 0;k < endPoint.size();k++) {
                line.endPoint.push_back(endPoint[k]);
            }
            lines.push_back(line);
        }
    }
}
Example #7
0
	/* apply background subtraction and manipulate the resultant frame */
void BackSubs::find_forgnd(Mat frame, Point *movementMassCenter)  
{
	Mat bgSubIn = frame.clone();

	medianBlur	(bgSubIn,	bgSubIn,	3); 
	mog->apply(bgSubIn,foreground, BackSubs_LearningRate);	

	frame_counter++;
	if (BgSubt_Status == BG_RECOVER_FROM_LOST)	
		cycles_number_after_lost++;
 
	/* wait for at least # initial frames, after reset or lost */
	if (frame_counter < init_frames_number)
		return ;

	/* start manipulating and checking result */
	/* open:  dst = open( src, element)   = dilate( erode( src, element ) ) */
	/* close: dst = close( src, element ) = erode( dilate( src, element ) ) */
	dilate		(foreground,	foreground,	Mat());
    erode		(foreground,	foreground,	Mat()); 
	threshold	(foreground,	foreground,	128,	255,THRESH_BINARY);  

	middle_tmp_frame = foreground.clone();

#ifndef COMPILING_ON_ROBOT
	myGUI.showContours(middle_tmp_frame);
#endif

	checkBgSubt_MaskResult(middle_tmp_frame, movementMassCenter);	//also prints. to screen
}
Example #8
0
void LabelOCR::preProcess(const Mat &InputImage, Mat &binImage)
{
	IplImage* iplInputImage = new IplImage(InputImage);
	IplImage* newInputImage = NULL;
	ImageProcess pro;
	int resize_ret = pro.ImageResize(iplInputImage, 2.5, newInputImage);
	if (resize_ret < 0) {
		return;
	}

	
    Mat midImage, midImage2, dst;
    Mat Morph = getStructuringElement(MORPH_CROSS,Size( 1, 1 ) );
    Mat HPKernel = (Mat_<float>(5,5) << -1.0,  -1.0, -1.0, -1.0,  -1.0,
                                        -1.0,  -1.0, -1.0, -1.0,  -1.0,
                                        -1.0,  -1.0, 25, -1.0,  -1.0,
                                        -1.0,  -1.0, -1.0, -1.0,  -1.0,
                                        -1.0,  -1.0, -1.0, -1.0,  -1.0);
    medianBlur( cv::Mat(newInputImage), dst, 1);
	filter2D(dst, midImage2, InputImage.depth(), HPKernel);
	cvtColor(midImage2, binImage, COLOR_RGB2GRAY);
	/*IplImage* temIplImg = new IplImage(midImage);
	CvSize sz;
	sz.width = temIplImg->width;
	sz.height = temIplImg->height;
	IplImage* temIplImg1 = cvCreateImage(sz, temIplImg->depth, temIplImg->nChannels);
    cvThreshold(temIplImg, temIplImg1, 60, 255, CV_THRESH_BINARY);
	binImage = temIplImg1;*/
    //threshold(binImage, binImage ,0, 255, CV_THRESH_BINARY | CV_THRESH_OTSU);
    //erode(binImage, binImage, 3, Point(-1, -1), 2, 1, 1);
    //morphologyEx( binImage,binImage,MORPH_CLOSE, Morph);
}
Example #9
0
void CubeAnalyzer::analyze(Mat cubeMat){
    Mat display;
    Size imageSize = cubeMat.size();
    int w = imageSize.width;
    this->cubeMat = cubeMat;

    medianBlur(cubeMat, cubeMat, 5);
    cubeMat.copyTo(display);

    Color sideColor = detectSide();
    if (isPressed(lockChar)){
        cube.lockWall(sideColor);
    }else if (isPressed(unlockChar)){
        cube.unlockWall(sideColor);
    }

    if (w != 0 && sideColor != UNDEF){
        int step = w / numberOfCellsInRow;
        int start = w * drawingPercentShift;
        int x, y, cellNumber;
        for (size_t horizontal = 0; horizontal < numberOfCellsInRow; horizontal++){
            for (size_t vertical = 0; vertical < numberOfCellsInRow; vertical++){
                x = start + step * horizontal;
                y = start + step * vertical;
                Color color = reconizeColor(x, y);
                drawCircles(display, Point(x,y), color);
                if (!cube.isWallLocked(sideColor)){
                    cellNumber = horizontal + vertical * numberOfCellsInRow;
                    cube.setCell(sideColor, cellNumber, color);
                }
            }
        }
        imshow(windowName, display);
    }
}
KDvoid Smoothing ( KDint nIdx )
{
	Mat		tSrc;
	Mat		tDst;

	KDint	MAX_KERNEL_LENGTH = 9;	// 31;
	KDint	i;

	// Load the source image
	tSrc = imread ( "/res/image/lena.jpg", 1 ); 
	tDst = tSrc.clone ( );

	for ( i = 1; i < MAX_KERNEL_LENGTH; i = i + 2 )
	{
		switch ( nIdx )
		{
			case 0 : blur ( tSrc, tDst, Size ( i, i ), Point ( -1, -1 ) );	break; // Applying Homogeneous blur 
			case 1 : GaussianBlur ( tSrc, tDst, Size ( i, i ), 0, 0 );		break; // Applying Gaussian blur 
			case 2 : medianBlur ( tSrc, tDst, i );							break; // Applying Median blur
			case 3 : bilateralFilter ( tSrc, tDst, i, i * 2, i / 2 );		break; // Applying Bilateral Filter
		}
	}

	g_pController->setFrame ( 1, tSrc );
	g_pController->setFrame ( 2, tDst );
}
Example #11
0
/**
 *  Update model based on next frame and number of tasks, blurring algorithm, motion compesation.
 *  A Timing struct is completed by this function
 */
void DualSGM::updateModel(Mat *next_frame, int num_threads, int use_opencv_blur, int do_motion_comp, Timing *run_times) 
{
    double start; 
    Mat origin;
    if (SHOW_IMAGES) {
        origin = next_frame->clone(); 
    }

    /* Pre processing */
    start = timer();
    Mat destination = next_frame->clone();
    Size gb_size = Size(GAUSSIAN_SIZE,GAUSSIAN_SIZE);
    if (use_opencv_blur) {
        GaussianBlur(*next_frame, destination, gb_size, 0, 0); 
        medianBlur(destination, *next_frame, MEDIAN_SIZE);
        cvWaitKey(1);
    } else {
        if (num_threads == 0) {
            serialGaussianBlur(*next_frame, destination, gb_size);
            serialMedianBlur(destination, *next_frame, MEDIAN_SIZE);
        } else {
            tbbGaussianBlur(*next_frame, destination, gb_size, num_threads);
            tbbMedianBlur(destination, *next_frame, MEDIAN_SIZE, num_threads);
        }
    }
    run_times->t_blur += timer() - start;

    /* Motion Compensation */
    if (do_motion_comp) {
        start = timer();
        motionCompensation(next_frame);
        run_times->t_mtnc += timer() - start;
    }

    /* Duel Gaussian Model */
    start = timer();
    if (num_threads == 0) {
        core_dsgm_update(next_frame, bin_mat, 
            app_u_mat, app_var_mat, 
            can_u_mat, can_var_mat, 
            app_ages, can_ages, 
            0, next_frame->rows);
    } else {
        cv::parallel_for_(cv::Range(0,num_threads), Dsgm_process(next_frame, bin_mat, app_u_mat, 
            app_var_mat, can_u_mat, can_var_mat, app_ages, can_ages, num_threads));
    }
    run_times->t_dsgm += timer() - start;

    if (SHOW_IMAGES) {
        // Show update
        imshow("origin", origin);
        cvWaitKey(1);
        imshow("blurred", *next_frame);
        cvWaitKey(1);
        imshow("processing", *app_u_mat);
        cvWaitKey(1);
        imshow("result", *bin_mat);
        cvWaitKey(1);
    }
}
/*!
 * @brief メソッドImageProcessing::getBackgroundSubstractionBinImage().背景差分によって得られた二値画像(c75)
 * @param cv::Mat& current_image, cv::Mat& background_image 
 * @return cv::Mat median_bin_image
 */
Mat ImageProcessing::getBackgroundSubstractionBinImage(Mat& current_image, Mat& background_gray_image/*, int threshold, int neighborhood, int closing_times*/)
{
	Mat current_gray_image; //!<現在のグレースケール画像(c75)
	Mat diff_gray_image; //!<背景差分画像(c74)
	Mat diff_bin_image; //!<背景差分画像の二値画像(c75)
	Mat median_bin_image; //!<背景差分画像の二値画像を平滑化したもの(c75)
	//Mat opening_image; //(仮)
	Mat closing_image;

	cvtColor(current_image, current_gray_image, CV_BGR2GRAY); //現フレームの画像をグレースケールに
	absdiff(current_gray_image, background_gray_image, diff_gray_image); //差分画像取得
	//showImage("差分画像", diff_gray_image);
	
	//EV3用
	//threshold(diff_gray_image, diff_bin_image, /*13*/20, 255, THRESH_BINARY); //二値化
	////showImage("二値画像", diff_bin_image);
	//medianBlur(diff_bin_image, median_bin_image, 7); //ノイズ除去
	////showImage("平滑化処理後", median_bin_image);
	////morphologyEx(median_bin_image, opening_image, MORPH_OPEN, Mat(), Point(-1, -1), 5); //オープニング(縮小→膨張)処理
	//morphologyEx(median_bin_image, closing_image, MORPH_CLOSE, Mat(), Point(-1, -1), 7); //クロージング(膨張→収縮)処理.穴埋めに使われる
	////showImage("穴埋め処理後", closing_image);


	threshold(diff_gray_image, diff_bin_image, th, 255, THRESH_BINARY); //二値化
	//showImage("二値画像", diff_bin_image);
	medianBlur(diff_bin_image, median_bin_image, 2*neighborhood+1); //ノイズ除去
	//showImage("平滑化処理後", median_bin_image);
	//morphologyEx(median_bin_image, opening_image, MORPH_OPEN, Mat(), Point(-1, -1), 5); //オープニング(縮小→膨張)処理
	morphologyEx(median_bin_image, closing_image, MORPH_CLOSE, Mat(), Point(-1, -1), 2*closing_times+1); //クロージング(膨張→収縮)処理.穴埋めに使われる
	//showImage("穴埋め処理後", closing_image);
	return closing_image;
	//return median_bin_image;
}
Example #13
0
void SharpnessFilter::updateSharpType(int type){

    switch (type) {
    case 0:
        noneType = true;
        somethingChanged();
    case 1:                     //Very fine
        noneType = false;
        kernal = (cv::Mat_<char>(4,4) <<   0.272, 0.534, 0.131, 0,
                     0.349, 0.686, 0.168, 0,
                     0.393, 0.769, 0.189, 0,
                     0, 0, 0, 1);
        cv::filter2D(originalImg, tempImage, originalImg.depth(), kernal);
        somethingChanged();
        break;
    case 2:                     // Fine
        noneType = false;
        medianBlur(originalImg, tempImage, 3);
        somethingChanged();
        break;
    case 3:                     // Coarse
        noneType = false;
        GaussianBlur(originalImg, tempImage, cv::Size(0, 0), 3);
        somethingChanged();
        break;
    default:
        noneType = true;
        break;
    }
}
Example #14
0
void cv::BackgroundSubtractorGMG::operator ()(InputArray _frame, OutputArray _fgmask, double newLearningRate)
{
    Mat frame = _frame.getMat();

    CV_Assert(frame.depth() == CV_8U || frame.depth() == CV_16U || frame.depth() == CV_32F);
    CV_Assert(frame.channels() == 1 || frame.channels() == 3 || frame.channels() == 4);

    if (newLearningRate != -1.0)
    {
        CV_Assert(newLearningRate >= 0.0 && newLearningRate <= 1.0);
        learningRate = newLearningRate;
    }

    if (frame.size() != frameSize_)
        initialize(frame.size(), 0.0, frame.depth() == CV_8U ? 255.0 : frame.depth() == CV_16U ? std::numeric_limits<ushort>::max() : 1.0);

    _fgmask.create(frameSize_, CV_8UC1);
    Mat fgmask = _fgmask.getMat();

    GMG_LoopBody body(frame, fgmask, nfeatures_, colors_, weights_,
                      maxFeatures, learningRate, numInitializationFrames, quantizationLevels, backgroundPrior, decisionThreshold,
                      maxVal_, minVal_, frameNum_, updateBackgroundModel);
    parallel_for_(Range(0, frame.rows), body, frame.total()/(double)(1<<16));

    if (smoothingRadius > 0)
    {
        medianBlur(fgmask, buf_, smoothingRadius);
        cv::swap(fgmask, buf_);
    }

    // keep track of how many frames we have processed
    ++frameNum_;
}
void  binaryImage(const Mat & src,Mat & binary,double thre,int mode){
    //二值化
    Mat gray;
    cvtColor(src,gray,CV_BGR2GRAY);
    double maxval = 255;
    threshold(gray, binary, thre, maxval,mode);
    medianBlur(binary, binary, 3);
}
Example #16
0
void AFH::Segmentation(Mat Gray) {
    Img.copyTo(Img_pre);
    Gray.copyTo(Img);
    HistOpr_Nnscore();
    HistOpr_Thresh();
    medianBlur(Flag, Smooth, 5);
    SeedFill(Smooth, Smooth.cols*Smooth.rows/2000, true);
}
Mat& CHandGestureRecognitionSystemDlg::Preprocess(const Mat& image_input, Mat& image_output)
{
    image_input.copyTo(image_output);
    medianBlur(image_output, image_output, 5);
    //cvtColor(image_input,image_input,CV_BGR2GRAY, 1);
    //GaussianBlur(image_input, image_input, Size(3, 3), 2.5);
    //adaptiveThreshold(image_input, image_input, 255, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, 3, 0);
    return image_output;
}
void BallDetector::learnBg() 
{
    pMOG = createBackgroundSubtractorMOG2();
    for (int i = 0; i < COUNT; i++)
    {
        cap.read(frame);
        medianBlur(frame, frame, 5);
        pMOG->apply(frame, fg);
    }
}
Example #19
0
void vehicle_det::get_foreground(Mat & background, Mat & foreground)
{
    //cout<<__PRETTY_FUNCTION__<<endl;
    mog(background, foreground, -1);
    threshold(foreground, foreground, 175, 255, THRESH_BINARY);
    //threshold(foreground, foreground, 150, 255, THRESH_TOZERO);
    medianBlur(foreground, foreground, 9);
    erode(foreground, foreground, Mat());
    dilate(foreground, foreground, Mat());
}
Example #20
0
	void PostFilterSet::filterDisp8U2Depth32F(Mat& src, Mat& dest, double focus, double baseline, double amp, int median_r, int gaussian_r, int minmax_r, int brange_r, float brange_th, int brange_method)
	{
		medianBlur(src, buff, 2 * median_r + 1);
		smallGaussianBlur(buff, buff, 2 * gaussian_r + 1, gaussian_r + 0.5);
		blurRemoveMinMax(buff, buff, minmax_r);

		disp8U2depth32F(buff, bufff, (float)(focus*baseline), (float)amp, 0.f);

		binalyWeightedRangeFilter(bufff, dest, Size(2 * brange_r + 1, 2 * brange_r + 1), brange_th, brange_method);
	}
//applique un flou moyen à l'image de taille blurSize
Mat1b PreProcessing::getMedianBlur(Mat img, int blurSize)
{

    Mat1b blur = Mat(img.rows,img.cols,CV_8UC1);

    for ( int i = 1; i < blurSize; i = i + 2 )
    {
        medianBlur(img,blur,i);
    }
    return blur;
}
Example #22
0
	void PostFilterSet::filterDisp8U2Disp32F(Mat& src, Mat& dest, int median_r, int gaussian_r, int minmax_r, int brange_r, float brange_th, int brange_method)
	{
		medianBlur(src, buff, 2 * median_r + 1);
		smallGaussianBlur(buff, buff, 2 * gaussian_r + 1, gaussian_r + 0.5);
		blurRemoveMinMax(buff, buff, minmax_r);

		buff.convertTo(bufff, CV_32F);
		binalyWeightedRangeFilter(bufff, bufff, Size(2 * brange_r + 1, 2 * brange_r + 1), brange_th, brange_method);

		bufff.convertTo(dest, CV_16U);
	}
Example #23
0
  bool BlurBlock::run(bool oneShot){
    Mat imgSrc = _myInputs["BLOCK__BLUR_IN_IMG"].get<cv::Mat>(),
      imgOut;

    switch (_myInputs["BLOCK__BLUR_IN_METHOD"].get<int>())
    {
    case 0://Mean
    {
      blur(imgSrc, imgOut, 
        cv::Size(_mySubParams["BLOCK__BLUR_IN_METHOD.Mean.kernel size X"].get<int>(),
        _mySubParams["BLOCK__BLUR_IN_METHOD.Mean.kernel size Y"].get<int>()),
        cv::Point(_mySubParams["BLOCK__BLUR_IN_METHOD.Mean.anchor point X"].get<int>(),
        _mySubParams["BLOCK__BLUR_IN_METHOD.Mean.anchor point Y"].get<int>()),
        cv::BORDER_DEFAULT);
      break;
    }
    case 1://Gaussian
    {
      cv::Size ksize(_mySubParams["BLOCK__BLUR_IN_METHOD.Gaussian.kernel size X"].get<int>(),
        _mySubParams["BLOCK__BLUR_IN_METHOD.Gaussian.kernel size Y"].get<int>());
      if (ksize.width <= 0) ksize.width = 1;
      if (ksize.width % 2 == 0) ksize.width += 1;
      if (ksize.height <= 0) ksize.height = 1;
      if (ksize.height % 2 == 0) ksize.height += 1;

      GaussianBlur(imgSrc, imgOut, ksize,
        _mySubParams["BLOCK__BLUR_IN_METHOD.Gaussian.Sigma X"].get<double>(),
        _mySubParams["BLOCK__BLUR_IN_METHOD.Gaussian.Sigma Y"].get<double>(),
        cv::BORDER_DEFAULT);
      break;
    }
    case 2://Median
    {
      int medianSize = _mySubParams["BLOCK__BLUR_IN_METHOD.Median.kernel size"].get<int>();
      if (medianSize % 2 != 1)
        medianSize += 1;
      medianBlur(imgSrc, imgOut, medianSize);
      break;
    }
    case 3://Bilateral
    {
      bilateralFilter(imgSrc, imgOut, _mySubParams["BLOCK__BLUR_IN_METHOD.Bilateral.Diameter"].get<int>(),
        _mySubParams["BLOCK__BLUR_IN_METHOD.Bilateral.Sigma color"].get<double>(),
        _mySubParams["BLOCK__BLUR_IN_METHOD.Bilateral.Sigma space"].get<double>());
      break;
    }
    default:
      return false;//nothing to do as we don't support this type of operation
      break;
    }
    _myOutputs["BLOCK__BLUR_OUT_IMAGE"] = imgOut;

    return true;
  };
Example #24
0
void DeNoiser::DeNoiseStatic(Mat &image, AlgParameters* params)
{
	if(params==NULL)
	{
		params = new AlgParameters();
		params->P0 = 1;
		params->P1 = 3;
		params->P2 = 1;
		params->P3 = 0;
		params->P4 = 10;
		params->P5 = 0;
		params->P6 = 0;
		params->P7 = 0;
		params->P8 = 0;
		params->P9 = 0;	
	}
	long t = getTickCount();
	if(params->P0>0)
	{		
		for(int i = 0;i<params->P1;i++)	medianBlur(image,image,params->P2*2+1);
	}
	if(params->P3 >0)
	{
		if(image_count<hist_size-1)
		{
			accumulate(image,Accum);
			image.copyTo(*images[(hist_size-1)-image_count]);		
			image_count++;
		}
		else
		{
			//acumular el frame actual
			accumulate(image,Accum);
			//guardar el actual en el inicio del historial
			image.copyTo(*images[0]);	
			//poner como resultado el prom de los history;
			Accum.convertTo(image,image.type(),1.0/hist_size);
			//en este punto la imágen esta lista, falta correr el historial	
			subtract(Accum,*images[hist_size-1],Accum,noArray(),CV_32F);
			//correr las imagenes
			Mat* last = images[hist_size-1];
			for(int i =hist_size-1;i>0;i--) images[i] = images[i-1];
			images[0] = last;
		}
	}

	t = getTickCount() - t;
	float time = t*1000/getTickFrequency();
	if(first_time)
	{
		printf("Noise time: %fms, Fps: %f\n",time,1000/time);
		first_time = false;
	}
}
void TrackingContours(const Mat &img)
{
	Mat cimg = img.clone();
	CvSize size = img.size();	

	//binary threshold, val = 235
	threshold(img, cimg, 235, 255, 0);
	medianBlur(cimg, cimg, 5);

	//circle detection with contours	
	bool enableRadiusCulling = false;
	int minTargetRadius = 5;
	vector<vector<Point> > contours;
	vector<Vec4i> heirarchy;

	//create copy, so findContours will not change binary image
	Mat cont = cimg.clone();
	findContours(cont, contours, heirarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);

	size_t count = contours.size();

	//get circle with largest radius
	float radius = 0;
	Point2i center;

	for (int i = 0; i < count; i++)
	{
		Point2f c;
		float r;
		minEnclosingCircle(contours[i], c, r);

		if (!enableRadiusCulling || r >= minTargetRadius)
		{
			if (r > radius) {
				radius = r;
				center = (Point2i) c;
			}
		}
	}

	cvtColor(cimg, cimg, CV_GRAY2BGR);
	
	Scalar red(0, 0, 255);
	Scalar blue(255, 0, 0);

	if (radius > 0) { //circle was found
		circle(cimg, center, radius, red, 1);
		circle(cimg, center, 1, blue, 2);
		//cout << "Center: " << center.x << "; " << center.y << "\n";
	}

	imshow("detected circles", cimg);	
}
static void computeEdgeMap( const Mat &image, Mat &edges )
{
    //get edge map
    Mat gray;
    cvtColor( image, gray, CV_BGR2GRAY );
    const int MEDIAN_BLUR_FILTER_SIZE = 7;
    medianBlur( gray, gray, MEDIAN_BLUR_FILTER_SIZE );

    const int LAPLACIAN_FILTER_SIZE = 5;
    Laplacian( gray, edges, CV_8U, LAPLACIAN_FILTER_SIZE );
    //***************

}
Example #27
0
void ShapeFeature::compute(Mat& src)
{
    resultingImage = src;

    Mat channel[3];
    // The actual splitting.
    split(resultingImage, channel);

    channel[1].setTo(Scalar(0));

    Mat br;
    merge(channel,3,br);

    channel[0].setTo(Scalar(0));
    Mat r;
    merge(channel,3,r);

    cvtColor(r, r, CV_BGR2GRAY);
    medianBlur(r, r, 9 );
    equalizeHist(r, r);

    threshold(r, r, 120, 255, THRESH_BINARY);

    erode(r, r, Mat());
    dilate(r, r, Mat());




    vector< vector <Point> > contours; // Vector for storing contour
    vector< Vec4i > hierarchy;
    int largest_contour_index=0;
    int largest_area=0;
    findContours( r.clone(), contours, hierarchy,RETR_EXTERNAL, CHAIN_APPROX_SIMPLE ); // Find the contours in the image
    for( int i = 0; i< contours.size(); i++ ){
        double a=contourArea( contours[i],false);  //  Find the area of contour
        if(a>largest_area){
            largest_area=a;
            largest_contour_index=i;                //Store the index of largest contour
        }
    }

    Mat pointsf;
    Mat(contours[largest_contour_index]).convertTo(pointsf, CV_32F);
    RotatedRect boxE = fitEllipse(pointsf);
    if(boxE.size.width<boxE.size.height)
        value = (float)boxE.size.width/boxE.size.height;
    else
        value = (float)boxE.size.height/boxE.size.width;

}
Example #28
0
/*
Mat bwareaopen(Mat& img, int size)
 {
     CBlobResult blobs;
     blobs = CBlobResult( img ,Mat(),4);
     blobs.Filter( blobs, B_INCLUDE, CBlobGetLength(), B_GREATER, size );

     Mat newimg(img.size(),img.type());
     newimg.setTo(0);
     for(int i=0;i<blobs.GetNumBlobs();i++)
     {
         blobs.GetBlob(i)->FillBlob(newimg,CV_RGB(255,255,255),0,0,true);
     }
     return newimg;
 }

Mat removeUseless(Mat& img, int low, int hight)
 {
     CBlobResult blobs;
     blobs = CBlobResult( img ,Mat(),4);
	 blobs.Filter( blobs, B_OUTSIDE, CBlobGetLength(), low, hight );

     Mat newimg(img.size(),img.type());
     newimg.setTo(0);
     for(int i=0;i<blobs.GetNumBlobs();i++)
     {
         blobs.GetBlob(i)->FillBlob(newimg,CV_RGB(255,255,255),0,0,true);
     }
     return newimg;
 }
 */
Mat computeWhiteMaskLight(Mat& input){
	Mat img, gray;
	input.clone().convertTo(img,CV_64F);
	Mat BGRbands[3] = {Mat::zeros(img.size(), CV_64F), Mat::zeros(img.size(), CV_64F),Mat::zeros(img.size(), CV_64F)};  
	Mat I1 = Mat::zeros(img.size(), CV_64F);
	Mat I2 = Mat::zeros(img.size(), CV_64F);
	Mat I3 = Mat::zeros(img.size(), CV_64F);
	Mat Id1 = Mat::zeros(img.size(), CV_64F);
	Mat Id2 = Mat::zeros(img.size(), CV_64F);
	Mat Id3 = Mat::zeros(img.size(), CV_64F);
	Mat I = Mat::zeros(img.size(), CV_64F);
	Mat mask = Mat::zeros(img.size(), CV_8U);
	vector< vector<Point> > contours;
	Mat mask2 = Mat::zeros(img.size(), CV_8U);
	split(img,BGRbands);
	I1 = BGRbands[0]-BGRbands[1];
	I1 = I1.mul(I1);
	I2 = BGRbands[0]-BGRbands[2];
	I2 = I2.mul(I2);
	I3 = BGRbands[1]-BGRbands[2];
	I3 = I3.mul(I3);
	Id1 = I1-I2;
	Id2 = I1-I3;
	Id3 = I3-I2;
	Id1 = Id1.mul(Id1);
	Id2 = Id2.mul(Id2);
	Id3 = Id3.mul(Id3);
	I = Id1+Id2+Id3;
	sqrt(I,I);
	sqrt(I,I);
	I.convertTo(mask,CV_8U);
	threshold(mask,mask,50,255,THRESH_BINARY_INV);
	Mat d = detectShadows(input);
	bitwise_and(mask,d,mask);
	cvtColor(input,gray,CV_BGR2GRAY);
	threshold(gray,mask2,160,255,THRESH_BINARY);
	mask = mask+mask2;
	medianBlur(mask,mask,9);
	findContours(mask, contours, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE);
	vector<double> areas = computeArea(contours);
	for(int j = areas.size()-1; j>=0; j--){
		if(areas.at(j)>MAX_AREA || areas.at(j)<MIN_AREA ) // 10000 400
			contours.erase(contours.begin()+j);
	}
	Mat out = Mat::zeros(Size(img.cols,img.rows), CV_8U);
	for (int idx = 0; idx < contours.size(); idx++)
		drawContours(out, contours, idx, Scalar(255,255,255), CV_FILLED, 8);
	return out;
}
void
CVImageDeblurring::blind_deblurring (const cv::Mat &blurred, cv::Mat &deblurred, cv::Mat &kernel, int kernel_size, float noise_power, bool use_edgetaper)
{
    cv::Mat gray_blurred;
    cv::cvtColor (blurred, gray_blurred, cv::COLOR_BGR2GRAY);
    if (noise_power < 0)
    {
        cv::Mat median_blurred;
        medianBlur (gray_blurred, median_blurred, 3);
        noise_power = 1.0f / _helper->get_snr (gray_blurred, median_blurred);
        XCAM_LOG_DEBUG ("estimated inv snr %f", noise_power);
    }
    if (kernel_size < 0)
    {
        kernel_size = estimate_kernel_size (gray_blurred);
        XCAM_LOG_DEBUG ("estimated kernel size %d", kernel_size);
    }
    if (use_edgetaper) {
        XCAM_LOG_DEBUG ("edgetaper will be used");
    }
    else {
        XCAM_LOG_DEBUG ("edgetaper will not be used");
    }
    std::vector<cv::Mat> blurred_rgb (3);
    cv::split (blurred, blurred_rgb);
    std::vector<cv::Mat> deblurred_rgb (3);
    cv::Mat result_deblurred;
    cv::Mat result_kernel;
    blind_deblurring_one_channel (gray_blurred, result_kernel, kernel_size, noise_power);
    for (int i = 0; i < 3; i++)
    {
        cv::Mat input;
        if (use_edgetaper)
        {
            _edgetaper->edgetaper (blurred_rgb[i], result_kernel, input);
        }
        else
        {
            input = blurred_rgb[i].clone ();
        }
        _wiener->wiener_filter (input, result_kernel, deblurred_rgb[i], noise_power);
        _helper->apply_constraints (deblurred_rgb[i], 0);
    }
    cv::merge (deblurred_rgb, result_deblurred);
    result_deblurred.convertTo (result_deblurred, CV_8UC3);
    cv::fastNlMeansDenoisingColored (result_deblurred, deblurred, 3, 3, 7, 21);
    kernel = result_kernel.clone ();
}
Example #30
0
/*******************************************************************************
* Function:      subtractBGMedian
* Description:   BG subtraction via opening with diagonal structuring elements
* Arguments:
	inImg           -   input image
	bgsImg          -   BG subtracted image
	threshVal       -   threshold value for converting to binary image
	seLength        -   length of structuring elements
	
* Returns:       void
* Comments:
* Revision: 
*******************************************************************************/
void
FGExtraction::subtractBGMedian(InputArray src, OutputArray dst, int threshVal, int seLength)
{
	Mat inImg = src.getMat();
	Mat medImg;
	
    // median filter
	Mat tempImg = inImg.clone();
	medianBlur(tempImg, medImg, 31);
	//showImage("median", medImg);
	
    Mat bin;
	double thresh = threshold(medImg, bin, threshVal, 255, THRESH_BINARY);
	
	dst.getMatRef() = bin;
}