图像分析之图像梯度处理
1、Sobel算子
dst = cv2.Sobel(src, ddepth, dx, dy, ksize)
- ddepth:图像的深度
- dx和dy分别表示水平和竖直方向,值为1表示沿着当前方向,0表示不沿着当前方向,如dx=1表示沿着x方向
- ksize是Sobel算子的大小,一般为3
import cv2 #opencv读取的格式是BGR import numpy as np import matplotlib.pyplot as plt#Matplotlib是RGB img = cv2.imread('pie.png',cv2.IMREAD_GRAYSCALE) cv2.imshow("img",img) sobelx = cv2.Sobel(img, cv2.CV_64F, 1, 1, ksize=3) cv2.imshow('sobelx', sobelx) cv2.waitKey() cv2.destroyAllWindows()
注意:白到黑是正数,黑到白就是负数了,所有的负数会被截断成0,所以要取绝对值
sobelx1 = cv2.Sobel(img,cv2.CV_64F,1,0,ksize=3) sobelx1 = cv2.convertScaleAbs(sobelx1) cv2.imshow('sobelx1', sobelx1)
因为沿着x或沿着y的处理结果有缝隙,所以将沿着x和y的处理结果合并
import cv2 #opencv读取的格式是BGR import numpy as np import matplotlib.pyplot as plt#Matplotlib是RGB img = cv2.imread('pie.png',cv2.IMREAD_GRAYSCALE) cv2.imshow("img",img) sobelx = cv2.Sobel(img, cv2.CV_64F, 0, 1, ksize=3) sobelx = cv2.convertScaleAbs(sobelx) cv2.imshow('sobelx', sobelx) sobelx1 = cv2.Sobel(img,cv2.CV_64F,1,0,ksize=3) sobelx1 = cv2.convertScaleAbs(sobelx1) cv2.imshow('sobelx1', sobelx1) sobel = cv2.addWeighted(sobelx, 0.5, sobelx1, 0.5, 0) cv2.imshow('sobel', sobel) cv2.waitKey() cv2.destroyAllWindows()
2、