python laplace filter returns wrong values

2019-07-12 04:05发布

问题:

As I need to implement a sort of image processing program in python I also wanted to implement the laplace filter. I used the matrix
-1 -1 -1
-1 8 -1
-1 -1 -1

and implemented the following code:

    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 is the image array. In another method I converted the image to

np.array(img)

and after processing the filter method, I reconvert the image using

Image.fromarray(...)

But when I start the program, it returns a strange result:

I already have changed my code lots of time but can't figure out, what I'm doing wrong. Is there something wrong with my implementation? Or do I misunderstand the filter?
Thank you in advance!

回答1:

You must not modify the array in place, i.e. if you are applying the filter to self._dataIn, then you must not store the result in self._dataIn because on the next filter operation, the input will not be the correct one.

By the way, it is easier to use numpy matrix multiplication to do the filtering (and to use a one component image):

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

Result: