您可以像这样计算幅度:
- 计算
dx
和dy
派生(使用cv::Sobel
) - 计算幅度
sqrt(dx^2 + dy^2)
(使用cv::magnitude
)
这是一个计算梯度大小的简单C ++代码。您可以轻松移植到Python,因为这只是对OpenCV函数的一些调用:
#include <opencv2/opencv.hpp>using namespace cv;int main(){ //Load image Mat3b img = imread("path_to_image"); //Convert to grayscale Mat1b gray; cvtColor(img, gray, COLOR_BGR2GRAY); //Compute dx and dy derivatives Mat1f dx, dy; Sobel(gray, dx, CV_32F, 1, 0); Sobel(gray, dy, CV_32F, 0, 1); //Compute gradient Mat1f magn; magnitude(dx, dy, magn); //Show gradient imshow("Magnitude", magn); waitKey(); return 0;}


