为什么我的 Sobel 边缘检测代码不起作用?
Why does my Sobel edge detection code not work?
这是我使用 Sobel operator:
进行边缘检测的代码
from PIL import Image
import numpy as np
from scipy import misc
a = np.array([1, 2, 1])
b = np.array([1, 0, -1])
Gy = np.outer(a, b)
Gx = np.rot90(Gy, k=3)
def apply(X):
a = (X * Gx)
b = (X * Gy)
return np.abs(a.sum()) + np.abs(b.sum())
data = np.uint8(misc.lena())
data2 = np.copy(data)
center = offset = 1
for i in range(offset, data.shape[0]-offset):
for j in range(offset, data.shape[1]-offset):
X = data[i-offset:i+offset+1, j-offset:j+offset+1]
data[i, j] = apply(X)
image = Image.fromarray(data)
image.show()
image = Image.fromarray(data2)
image.show()
这导致:
而不是:
就其价值而言,我相当确定我的 for 循环和图像内核的一般想法是正确的。例如,我能够生成此自定义过滤器(减去中心的高斯):
我的 Sobel 过滤器有什么问题?
终于想通了。我不应该就地修改数组,因为它显然会更改在过滤器的后续应用程序中计算的值。这有效:
...
new_data = np.zeros(data.shape)
center = offset = 1
for i in range(offset, new_data.shape[0]-offset):
for j in range(offset, new_data.shape[1]-offset):
X = data[i-offset:i+offset+1, j-offset:j+offset+1]
new_data[i, j] = apply(X)
...
产生:
这是我使用 Sobel operator:
进行边缘检测的代码from PIL import Image
import numpy as np
from scipy import misc
a = np.array([1, 2, 1])
b = np.array([1, 0, -1])
Gy = np.outer(a, b)
Gx = np.rot90(Gy, k=3)
def apply(X):
a = (X * Gx)
b = (X * Gy)
return np.abs(a.sum()) + np.abs(b.sum())
data = np.uint8(misc.lena())
data2 = np.copy(data)
center = offset = 1
for i in range(offset, data.shape[0]-offset):
for j in range(offset, data.shape[1]-offset):
X = data[i-offset:i+offset+1, j-offset:j+offset+1]
data[i, j] = apply(X)
image = Image.fromarray(data)
image.show()
image = Image.fromarray(data2)
image.show()
这导致:
而不是:
就其价值而言,我相当确定我的 for 循环和图像内核的一般想法是正确的。例如,我能够生成此自定义过滤器(减去中心的高斯):
我的 Sobel 过滤器有什么问题?
终于想通了。我不应该就地修改数组,因为它显然会更改在过滤器的后续应用程序中计算的值。这有效:
...
new_data = np.zeros(data.shape)
center = offset = 1
for i in range(offset, new_data.shape[0]-offset):
for j in range(offset, new_data.shape[1]-offset):
X = data[i-offset:i+offset+1, j-offset:j+offset+1]
new_data[i, j] = apply(X)
...
产生: