I've got some working code to compute the Hough transform for circles:
#include <stdio.h>
#include <opencv/cv.hpp>
#include <math.h>
#include <string>
#include <iostream>
int *** allocate3DArray(int y, int x, int r) {
int ***array = (int***)malloc(sizeof(int**)*y);
for (int i = 0; i < y; i++) {
array[i] = (int**)malloc(sizeof(int*)*x);
for (int j = 0; j < x; j++) {
array[i][j] = (int*)malloc(sizeof(int)*r);
for(int k = 0; k < r; k++) {
array[i][j][k] = 0;
}
}
}
return array;
}
void free3d(int ***arr, int y, int x, int r) {
for (int i = 0; i < y; i++) {
for (int j = 0; j < x; j++) {
free(arr[i][j]);
}
free(arr[i]);
}
free(arr);
}
vector<Circle> HoughTransformCircles(Mat image, Mat &gradient_mag, Mat &gradient_dir) {
//Maximum circle radius is rLen = image.width / 2
int rLen = image.rows/2;
int ***houghSpace = allocate3DArray(image.rows, image.cols, rLen);
for (int y = 0; y < image.rows; y++) {
for (int x = 0; x < image.cols; x++) {
for (int r = 0; r < rLen; r++) {
int x0 = x - (int)(r*cos(gradient_dir.at<double>(y, x)));
int y0 = y - (int)(r*sin(gradient_dir.at<double>(y, x)));
if(x0 >= 0 && x0 < image.cols && y0 >= 0 && y0 < image.rows ) {
houghSpace[y0][x0][r]++;
}
x0 = x + (int)(r*cos(gradient_dir.at<double>(y, x)));
y0 = y + (int)(r*sin(gradient_dir.at<double>(y, x)));
if(x0 >= 0 && x0 < image.cols && y0 >= 0 && y0 < image.rows ) {
houghSpace[y0][x0][r]++;
}
}
}
}
vector<Circle> circles;
for (int y = 0; y < image.rows; y++) {
for (int x = 0; x < image.cols; x++) {
for (int r = 0; r < rLen; r++) {
if (houghSpace[y][x][r] > 30) {
Circle temp = Circle(x, y, r);
circles.push_back(temp);
}
}
}
}
free3d(houghSpace, image.rows, image.cols, rLen);
return circles;
}
How do I make this as idiomatic as possible? I am not allowed to use C++ 11 unfortunately.