python laplace过滤器返回错误的值

时间:2015-07-24 16:33:07

标签: python image filter python-imaging-library edge-detection

由于我需要在python中实现一种图像处理程序,我还想实现laplace过滤器。我用了矩阵
-1 -1 -1
-1 8 -1
-1 -1 -1

并实现了以下代码:

    for row in range(1, (len(self._dataIn) - 1)):
         for col in range(1, (len(self._dataIn[row])- 1)):
             value =  (- int(self._dataIn[row - 1][col -1][0])
                       - int(self._dataIn[row - 1][col][0])
                       - int(self._dataIn[row - 1][col + 1][0])
                       - int(self._dataIn[row][col -1][0]) + 
                       (8 * int(self._dataIn[row][col][0]))
                       - int(self._dataIn[row][col +1][0])
                       - int(self._dataIn[row + 1][col -1][0])
                       - int(self._dataIn[row + 1][col][0])
                       - int(self._dataIn[row + 1][col +1][0]))
             self._dataIn[row][col][0] = np.minimum(255, np.maximum(0, value))
             self._dataIn[row][col][1] = np.minimum(255, np.maximum(0, value))
             self._dataIn[row][col][2] = np.minimum(255, np.maximum(0, value))
    self.update()

self._dataIn是图像数组。在另一种方法中,我将图像转换为

np.array(img)

在处理过滤方法后,我使用

重新转换图像
Image.fromarray(...)

但是当我启动程序时,它会返回一个奇怪的结果: enter image description here

我已经很多时间改变了我的代码,但无法弄清楚,我做错了什么。我的实施有问题吗?或者我误解了过滤器?
提前谢谢!

1 个答案:

答案 0 :(得分:5)

您不能在适当的位置修改数组,即如果要将过滤器应用于self._dataIn,则不得将结果存储在self._dataIn中,因为在下一次过滤操作时,输入不会是正确的。

顺便说一句,使用numpy矩阵乘法来进行过滤(以及使用单个分量图像)更容易:

img = img.mean(2) # get a NxM image
imgOut = np.zeros (img.shape, dtype = uint8)
M = np.array([
    [-1, -1, -1], 
    [-1,  8, -1], 
    [-1, -1, -1]
])
for row in range(1, img.shape[0] - 1):
    for col in range(1, img.shape[1] - 1):
        value = M * img[(row - 1):(row + 2), (col - 1):(col + 2)]
        imgOut[row, col] = min(255, max(0, value.sum ()))

结果:

enter image description here enter image description here

相关问题