/** * customStructElem.c * OpenCV Introduction: Demo 4 * David Johnston, 2013-01-29 */ #include #include #include "cv.h" #include "highgui.h" void display(IplImage* img) { cvShowImage("DEBUG", img); cvWaitKey(0); } IplConvKernel* createCustomStructElem(IplImage* template) { IplConvKernel* rv = NULL; // the kernel to be returned CvSize size; // size of 'template' int* kernData; // where the template data is temporarily stored int* kernRow; // points into 'kernData' void* templateRow; // points into 'template->imageData' int y; // iterates over the rows int x; // iterates over the columns if (template == NULL || cvGetElemType(template) != CV_8UC1) { return rv; } /* * Copy the contents of 'template->imageData' (which is an unsigned char * array) into 'kernData' (which is an int array). * * Both arrays have (size.width * size.height) number of elements. */ size = cvGetSize(template); kernData = (int*) malloc(size.height * size.width * sizeof(int)); for (y = 0; y < size.height; y++) { // For both arrays, reinitialize to the 0th element of the y-th row: templateRow = template->imageData + (y * template->widthStep); kernRow = kernData + (y * size.width); // Copy every element on the y-th row: for (x = 0; x < size.width; x++) { kernRow[x] = ((unsigned char*) templateRow)[x]; } } rv = cvCreateStructuringElementEx( size.width, size.height, size.width / 2, size.height / 2, CV_SHAPE_CUSTOM, kernData ); free(kernData); return rv; } int main(const int argc, const char* argv[]) { IplImage* template; IplImage* testImage; IplConvKernel* rectKernel; IplConvKernel* customKernel; template = cvLoadImage("inputs/template.png", CV_LOAD_IMAGE_GRAYSCALE); testImage = cvLoadImage("inputs/test.png", CV_LOAD_IMAGE_GRAYSCALE); cvThreshold( template, template, 160, 0xFF, CV_THRESH_BINARY_INV); cvThreshold(testImage, testImage, 160, 0xFF, CV_THRESH_BINARY_INV); rectKernel = cvCreateStructuringElementEx(3, 3, 1, 1, CV_SHAPE_RECT, NULL); cvErode(template, template, rectKernel, 1); // decreases white area cvDilate(testImage, testImage, rectKernel, 1); // increases white area cvShowImage("Template", template); cvShowImage("Test Image", testImage); cvWaitKey(0); customKernel = createCustomStructElem(template); cvErode(testImage, testImage, customKernel, 1); cvDilate(testImage, testImage, customKernel, 1); cvShowImage("DEBUG", testImage); cvWaitKey(0); }