对待健康,偏见比无知更可怕!微笑不用成本,但能创造财富。赞美不用花钱,但能产生力量。分享不用费用,但能倍增快乐。
实现思路:
1,将传进来的图片矩阵用算子进行卷积求和(卷积和取绝对值)
2,用新的矩阵(与原图一样大小)去接收每次的卷积和的值
3,卷积图片所有的像素点后,把新的矩阵数据类型转化为uint8
注意:
必须对求得的卷积和的值求绝对值;矩阵数据类型进行转化。
完整代码:
import cv2 import numpy as np # robert 算子[[-1,-1],[1,1]] def robert_suanzi(img): r, c = img.shape r_sunnzi = [[-1,-1],[1,1]] for x in range(r): for y in range(c): if (y + 2 <= c) and (x + 2 <= r): imgChild = img[x:x+2, y:y+2] list_robert = r_sunnzi*imgChild img[x, y] = abs(list_robert.sum()) # 求和加绝对值 return img # # sobel算子的实现 def sobel_suanzi(img): r, c = img.shape new_image = np.zeros((r, c)) new_imageX = np.zeros(img.shape) new_imageY = np.zeros(img.shape) s_suanziX = np.array([[-1,0,1],[-2,0,2],[-1,0,1]]) # X方向 s_suanziY = np.array([[-1,-2,-1],[0,0,0],[1,2,1]]) for i in range(r-2): for j in range(c-2): new_imageX[i+1, j+1] = abs(np.sum(img[i:i+3, j:j+3] * s_suanziX)) new_imageY[i+1, j+1] = abs(np.sum(img[i:i+3, j:j+3] * s_suanziY)) new_image[i+1, j+1] = (new_imageX[i+1, j+1]*new_imageX[i+1,j+1] + new_imageY[i+1, j+1]*new_imageY[i+1,j+1])**0.5 # return np.uint8(new_imageX) # return np.uint8(new_imageY) return np.uint8(new_image) # 无方向算子处理的图像 # Laplace算子 # 常用的Laplace算子模板 [[0,1,0],[1,-4,1],[0,1,0]] [[1,1,1],[1,-8,1],[1,1,1]] def Laplace_suanzi(img): r, c = img.shape new_image = np.zeros((r, c)) L_sunnzi = np.array([[0,-1,0],[-1,4,-1],[0,-1,0]]) # L_sunnzi = np.array([[1,1,1],[1,-8,1],[1,1,1]]) for i in range(r-2): for j in range(c-2): new_image[i+1, j+1] = abs(np.sum(img[i:i+3, j:j+3] * L_sunnzi)) return np.uint8(new_image) img = cv2.imread('1.jpg', cv2.IMREAD_GRAYSCALE) cv2.imshow('image', img) # # robers算子 out_robert = robert_suanzi(img) cv2.imshow('out_robert_image', out_robert) # sobel 算子 out_sobel = sobel_suanzi(img) cv2.imshow('out_sobel_image', out_sobel) # Laplace算子 out_laplace = Laplace_suanzi(img) cv2.imshow('out_laplace_image', out_laplace) cv2.waitKey(0) cv2.destroyAllWindows()
结果:
以上就是python通过robert、sobel、Laplace算子实现图像边缘提取详解。人生就应该:尽己力,听天命。无愧于心,不惑于情。顺势而为,随遇而安。知错即改,迷途知返。在喜欢自己的人身上用心,在不喜欢自己的人身上健忘。更多关于python通过robert、sobel、Laplace算子实现图像边缘提取详解请关注haodaima.com其它相关文章!