Sobel算法代码(python)
import numpy as np
import imageio
#先获取灰度图
def rgb2gray(rgb):
“”"
convert rgb image into gray
Args:
rgb: grb image with numpy type
Returns:
gray: gray image
“”"
gray = rgb[:, :, 0] * 0.299 + rgb[:, :, 1] * 0.587 + rgb[:, :, 2] * 0.114
return gray
image_in = imageio.imread(“1.jpg”)
gray = rgb2gray(image_in)
imageio.imsave(im=gray.astype(np.uint8), uri=“gray_image.jpg”)
#然后进行sobel操作
def sobel(image):
“”"
implement sobel compute on a single gray image
Args:
image: a gray image
Returns:
the image that have been processd by sobel
Raises:
ValueError: the input's shape image must bigger than sobel(3x3)
"""
# change the data type of input image into np.uint8(cheaper compute cost)
image = image.astype(np.uint8)
assert len(image.shape) == 2
if image.shape[0] < 3 or image.shape[1] < 3:
raise ValueError("The width and height of input image must bigger than 3")
# create temp image container
sobel_image_x = np.zeros(shape=image.shape)
sobel_image_y = np.zeros(shape=image.shape)
# create sobel
sobel_x = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]])
sobel_y = np.array([[-1, -2, -1], [0, 0, 0], [1, 2, 1]])
for i in range(image.shape[0]-2):
for j in range(image.shape[1]-2):
# have to use np.abs() to make sure the value is positive
sobel_image_x[i, j] = np.abs(np.sum(image[i:i+3, j:j+3] * sobel_x))
sobel_image_y[i, j] = np.abs(np.sum(image[i:i+3, j:j+3] * sobel_y))
sobel_image = np.sqrt(sobel_image_x*sobel_image_x + sobel_image_y*sobel_image_y).astype(np.uint8)
return sobel_image
image_in = imageio.imread(“1.jpg”)
rgb = rgb2gray(image_in)
sobel_image = sobel(rgb)
imageio.imsave(im=sobel_image, uri=“sobel_image.jpg”)