python
import cv2 as cv
import numpy as np
img = cv.imread('../images/test.jpg')
h, w = img.shape[0 : 2]
grad_x = cv.Sobel(img, cv.CV_32F, 1, 0)
grad_y = cv.Sobel(img, cv.CV_32F, 0, 1)
grad_x = cv.convertScaleAbs(grad_x)
grad_y = cv.convertScaleAbs(grad_y)
grad_xy = cv.add(grad_x, grad_y, dtype = cv.CV_16S)
grad_xy = cv.convertScaleAbs(grad_xy)
result = np.zeros([h, w * 2, 3], dtype = img.dtype)
result[0:h, 0 : w, :] = img
result[0:h, w : 2 * w, :] = grad_xy
cv.imshow('result', result)
cv.waitKey(0)
cv.destroyAllWindows()
python中新知识点:
此处注意python中不用filter2D()方法,替代方法为Sobel
c++
#include "all.h"
using namespace std;
using namespace cv;
void MyClass::day031() {
Mat img = MyClass::read(PATH + "images\\test.jpg");
imshow("input", img);
Mat robert_x = (Mat_(2, 2) << 1, 0, 0, -1);
Mat robert_y = (Mat_(2, 2) << 0, -1, 1, 0);
Mat prowitt_x = (Mat_(3, 3) << -1, 0, 1, -1, 0, 1, -1, 0, 1);
Mat prowitt_y = (Mat_(3, 3) << -1, -1, -1, 0, 0, 0, 1, 1, 1);
Mat robert_grad_x, robert_grad_y, prowitt_grad_x, prowitt_grad_y;
filter2D(img, robert_grad_x, CV_16S, robert_x);
filter2D(img, robert_grad_y, CV_16S, robert_y);
convertScaleAbs(robert_grad_x, robert_grad_x);
convertScaleAbs(robert_grad_y, robert_grad_y);
imshow("robert_x", robert_grad_x);
imshow("robert_y", robert_grad_y);
filter2D(img, prowitt_grad_x, CV_32F, prowitt_x);
filter2D(img, prowitt_grad_y, CV_32F, prowitt_y);
convertScaleAbs(prowitt_grad_x, prowitt_grad_x);
convertScaleAbs(prowitt_grad_y, prowitt_grad_y);
imshow("prowitt_x", prowitt_grad_x);
imshow("prowitt_y", prowitt_grad_y);
waitKey(0);
}
c++新知识点:
Mat模板类:(Mat_
边缘提取算子:Sobel, Isotropic Sobel, Roberts, Prewitt, Laplacian, Canny
filter2D():根据边缘提取算子来过滤图像,效果是暴露图像的梯度
convertScaleAbs():该函数经常用于图像增强,args1:input,args2:output,args3:alpha,args4:belta