Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 463
yaseco Avatar asked Dec 21 '18 20:12

yaseco


People also ask

How do you apply a filter in Python?

syntax: filter(function, sequence) Parameters: function: function that tests if each element of a sequence true or not. sequence: sequence which needs to be filtered, it can be sets, lists, tuples, or containers of any iterators. Returns: returns an iterator that is already filtered.

What does filter () do in Python?

Python's filter() is a built-in function that allows you to process an iterable and extract those items that satisfy a given condition. This process is commonly known as a filtering operation.

What is image filtering?

Image filtering is changing the appearance of an image by altering the colors of the pixels. Increasing the contrast as well as adding a variety of special effects to images are some of the results of applying filters.


1 Answers

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!

like image 136
Cris Luengo Avatar answered Nov 15 '22 08:11

Cris Luengo