6

Here's my code:

from matplotlib.pyplot import imread
import matplotlib.pyplot as plt
from scipy.ndimage.filters import convolve


k3 = np.array([ [-1, -1, -1], [-1, 8, -1], [-1, -1, -1] ])
img = imread("lena.jpg")
channels = []
for channel in range(3):
    res = convolve(img[:,:,channel], k3)
    channels.append(res)

img = np.dstack((channels[0], channels[1], channels[2]))
plt.imshow(img)
plt.show()

k3 filter suppose to be an edge detection filter. Instead, I'm getting a weird image looks like white noise.

Why?

Here's the output:

enter image description here

IsaacLevon
  • 2,260
  • 4
  • 41
  • 83
  • have you considered `np.convolve`? For loops in python are slow. There is no way around that, except to not use them. I suspect you can just run convolve with a 3-channel kernel and speed it up by 1000x – kevinkayaks Dec 21 '18 at 21:39
  • 2
    1. may be due to dtype. What happens if you convert `img_filtered` to uint8 (`img_filtered.astype(np.uint8)`)? – Paul Panzer Dec 21 '18 at 22:01
  • It didn't help. please see my edit – IsaacLevon Dec 22 '18 at 10:15
  • Well, I am not sure if there is something wrong with your filter settings. I used to set my kernel as the following in order to detect the edge. [[0, 1, 0], [-1, 0, 1], [0, -1, 0]] By the way, my graph is only four connection without the diagnoal pixel. – Sean Dec 22 '18 at 11:01
  • @Sean, basically, it is done for educational purposes so the numbers don't really matter to me. It seems that something is wrong with my code though – IsaacLevon Dec 22 '18 at 11:03

1 Answers1

3

img is likely an 8-bit unsigned integer. Convolving with the Laplace mask as you do, output values are likely to exceed the valid range of [0,255]. When assigning, for example, a -1 to such an image, the value written will be 254. That leads to an output as shown in the question.

With this particular filter, it is important to convert the image to a signed type first, for example a 16-bit signed integer or a floating-point type.

img = img.astype(np.int16)

PS: Note that Laplace is not an edge detector!

Cris Luengo
  • 55,762
  • 10
  • 62
  • 120