sobel

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”)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

二月断痕

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值