给网友们整理python相关的编程文章,网友家飞航根据主题投稿了本篇教程内容,涉及到python、robert、sobel、laplace、算子、图像边缘提取相关内容,已被665网友关注,内容中涉及的知识点可以在下方直接下载获取。
实现思路:
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()
结果:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持码农之家。