IsaacLevon
IsaacLevon

Reputation: 2570

Applying a filter on an image with Python

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

Upvotes: 6

Views: 9559

Answers (1)

Cris Luengo
Cris Luengo

Reputation: 60444

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!

Upvotes: 3

Related Questions