Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- std::pair<cv::Mat, cv::Mat> gradient(cv::Mat & img, float spaceX, float spaceY)
- {
- cv::Mat gradY = gradientY(img, spaceY);
- cv::Mat gradX = gradientX(img, spaceX);
- std::pair<cv::Mat, cv::Mat> retValue(gradX, gradY);
- return retValue;
- }
- static cv::Mat gradientX(cv::Mat & mat, float spacing)
- {
- cv::Mat grad = cv::Mat::zeros(mat.rows, mat.cols, CV_32F);
- /* last row */
- int maxCols = mat.cols;
- int maxRows = mat.rows;
- /* get gradients in each border */
- /* first row */
- cv::Mat col = (-mat.col(0) + mat.col(1)) / (float)spacing;
- col.copyTo(grad(cv::Rect(0, 0, 1, maxRows)));
- col = (-mat.col(maxCols - 2) + mat.col(maxCols - 1)) / (float)spacing;
- col.copyTo(grad(cv::Rect(maxCols - 1, 0, 1, maxRows)));
- /* centered elements */
- cv::Mat centeredMat = mat(cv::Rect(0, 0, maxCols - 2, maxRows));
- cv::Mat offsetMat = mat(cv::Rect(2, 0, maxCols - 2, maxRows));
- cv::Mat resultCenteredMat = (-centeredMat + offsetMat) / (((float)spacing)*2.0);
- resultCenteredMat.copyTo(grad(cv::Rect(1, 0, maxCols - 2, maxRows)));
- return grad;
- }
- static cv::Mat gradientY(cv::Mat & mat, float spacing)
- {
- cv::Mat grad = cv::Mat::zeros(mat.rows, mat.cols, CV_32F);
- /* last row */
- const int maxWidth = mat.cols;
- const int maxHeight = mat.rows;
- /* get gradients in each border */
- /* first row */
- cv::Mat row = (-mat.row(0) + mat.row(1)) / (float)spacing;
- row.copyTo(grad(cv::Rect(0, 0, maxWidth, 1)));
- row = (-mat.row(maxHeight - 2) + mat.row(maxHeight - 1)) / (float)spacing;
- row.copyTo(grad(cv::Rect(0, maxHeight - 1, maxWidth, 1)));
- /* centered elements */
- cv::Mat centeredMat = mat(cv::Rect(0, 0, maxWidth, maxHeight - 2));
- cv::Mat offsetMat = mat(cv::Rect(0, 2, maxWidth, maxHeight - 2));
- cv::Mat resultCenteredMat = (-centeredMat + offsetMat) / (((float)spacing)*2.0);
- resultCenteredMat.copyTo(grad(cv::Rect(0, 1, maxWidth, maxHeight - 2)));
- return grad;
- }
- int main(void)
- {
- cv::Mat imgMat = cv::imread("sample.jpg", CV_LOAD_IMAGE_COLOR);
- cv::Mat imgMat_bw = cv::Mat::zeros(imgMat.rows, imgMat.cols, CV_32FC(1));
- cv::cvtColor(imgMat, imgMat_bw, cv::COLOR_RGB2GRAY);
- std::pair<cv::Mat, cv::Mat> grad;
- grad = gradient(imgMat_bw, 1.0f, 1.0f);
- cv::Mat_<float> dX = grad.first;
- cv::Mat_<float> dY = grad.second;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement