我正在尝试在 Python 中实现 sobel 运算符并将其可视化。但是,我正在努力解决如何做到这一点。我有以下代码,它当前计算每个像素的梯度。
from PIL import Image
import math
def run():
try:
image = Image.open("brick-wall-color.jpg")
image = image.convert('LA')
apply_sobel_masks(image)
except RuntimeError, e:
print e
def apply_sobel_masks(image):
gx = [
[-1, 0, 1],
[-2, 0, 2],
[-1, 0, 1]
]
gy = [
[1, 2, 1],
[0, 0, 0],
[-1, -2, -1]
]
width, height = image.size
for y in range(0, height):
for x in range(0, width):
gradient_y = (
gy[0][0] * get_pixel_safe(image, x - 1, y - 1, 0) +
gy[0][1] * get_pixel_safe(image, x, y - 1, 0) +
gy[0][2] * get_pixel_safe(image, x + 1, y - 1, 0) +
gy[2][0] * get_pixel_safe(image, x - 1, y + 1, 0) +
gy[2][1] * get_pixel_safe(image, x, y + 1, 0) +
gy[2][2] * get_pixel_safe(image, x + 1, y + 1, 0)
)
gradient_x = (
gx[0][0] * get_pixel_safe(image, x - 1, y - 1, 0) +
gx[0][2] * get_pixel_safe(image, x + 1, y - 1, 0) +
gx[1][0] * get_pixel_safe(image, x - 1, y, 0) +
gx[1][2] * get_pixel_safe(image, x + 1, y, 0) +
gx[2][0] * get_pixel_safe(image, x - 1, y - 1, 0) +
gx[2][2] * get_pixel_safe(image, x + 1, y + 1, 0)
)
print "Gradient X: " + str(gradient_x) + " Gradient Y: " + str(gradient_y)
gradient_magnitude = math.sqrt(pow(gradient_x, 2) + pow(gradient_y, 2))
image.putpixel((x, y), #tbd)
image.show()
def get_pixel_safe(image, x, y, layer):
try:
return image.getpixel((x, y))[layer]
except IndexError, e:
return 0
run()
现在,gradient_magnitude 通常是一个远远超出 0-255 范围的值,例如 990.0、1002.0、778 等。
所以我想做的是可视化渐变,但我不确定如何。大多数在线资源只提到计算梯度角度和幅度,而不是如何在图像中表示它。