I have implemented the following code to perform filter2D on a matrix. After I compiled the program it returns Segmentation fault error. In this program, I want to assign an inp
According to the comments, the problem has been found! It is because of casting the Mat
object to InputArray
and OutputArray
in filter2D
function. I changed the implementation to the following program and it works.
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <time.h>
//Picture size for input and output are the same
#define MAX1 4096
#define Pxsize MAX1
#define Pysize Pxsize
//Kernel size
#define Kxsize 9
#define Kysize Kxsize
//number of iterations
#define NUM_LOOP 10000
using namespace std;
using namespace cv;
unsigned short int A[Pxsize][Pysize];
unsigned short int B[Pxsize][Pysize];
unsigned short int K[Kxsize][Kysize];
// measuring the time
double pTime = 0, mTime = 10; // to indicate how much program time is (pTime) and how much i want to wait (mTime)
struct timespec start;
int main(){
//singleCore
struct timespec tStart, tEnd;//used to record the processiing time
double tTotal , tBest=10000;//minimum of toltal time will asign to the best time
int w=0;
//filter arguments
Point anchor;
double delta;
int ddepth;
//assign data between 0 and 255 to the input matrix
int i,j;
for (i=0; i<Pxsize; i++)
for (j=0; j<Pysize; j++)
A[i][j] = (i+j)%255;
//assign data to the kernel
//assign data between 0 and 255 to the input matrix
for (i=0; i<Kxsize; i++)
for (j=0; j<Kysize; j++)
K[i][j]=1;
cv::Mat input = cv::Mat(Pxsize, Pysize, CV_8UC1, A);
cv::Mat kernel = cv::Mat::ones(Kxsize, Kysize, CV_8UC1);
//name for out put
// Initialize arguments for the filter
anchor = Point( -1, -1 );
delta = 0;
ddepth = -1;
do{// this loop repeat the body to record the best time
clock_gettime(CLOCK_MONOTONIC,&tStart);
//the problem is here:
filter2D( input, output, ddepth , kernel, anchor, delta, 1 );
clock_gettime(CLOCK_MONOTONIC,&tEnd);
tTotal = (tEnd.tv_sec - tStart.tv_sec);
tTotal += (tEnd.tv_nsec - tStart.tv_nsec) / 1000000000.0;
if(tTotal<tBest)
tBest=tTotal;
pTime += tTotal;
} while(w++ < NUM_LOOP && pTime < mTime);
//cout<<" "<< input<<endl;
//cout<<" "<< output<<endl;
printf("\nThe best time: %f sec in %d repetition for %dX%d matrix for %d, %d kernel \n",tBest,w, Pxsize, Pysize, Kxsize, Kysize);
return 0;
}