Created
December 3, 2011 23:37
-
-
Save jotbe/1428509 to your computer and use it in GitHub Desktop.
Computer Vision: Linear filter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/env python | |
"""Chapter 16.21 Linear filter | |
We got the following matrix :math:`I` of a grayscale image from video 16.20:: | |
255 7 3 | |
212 240 4 | |
218 216 230 | |
The kernel :math:`g` is:: | |
+1 -1 | |
Action is: | |
:math:`I \otimes g \leadsto I'` | |
That means, we take an image, apply :math:`\otimes` the kernel | |
and receive a new image :math:`I'`:: | |
| -248 | -4 | | |
| 28 | -236 | | |
| -2 | 14 | | |
Linear filter formula: | |
:math:`I'(x,y) = \sum_{u,v} I(x-u, y-v) g(u,v)` | |
""" | |
__author__ = 'Jan Beilicke <dev +at+ jotbe-fx +dot+ de>' | |
__date__ = '2011-12-03' | |
class LinearFilter: | |
def __init__(self, image, kernel=None): | |
"""Create the initial filter.""" | |
self.image = image | |
self.kernel = kernel | |
def filter_with_kernel(self, kernel): | |
self.kernel = kernel | |
if not self.kernel: | |
return | |
self.filter() | |
def filter(self): | |
"""Filter the input image. | |
Iterate through all rows and columns and apply the kernel. | |
""" | |
rows_image = len(self.image) | |
cols_image = len(self.image[0]) | |
rows_kernel = len(self.kernel) | |
cols_kernel = len(self.kernel[0]) | |
self.image2 = [] | |
for x in range(rows_image - rows_kernel + 1): | |
self.image2.append([]) | |
for y in range(cols_image - cols_kernel + 1): | |
self.image2[x].append(0) | |
for u in range(rows_kernel): | |
for v in range(cols_kernel): | |
self.image2[x][y] += self.image[x + u][y + v] * self.kernel[u][v] | |
def print_in(self): | |
"""Print the source image.""" | |
self.print_matrix(self.image) | |
def print_out(self): | |
"""Print the filtered image.""" | |
self.print_matrix(self.image2) | |
def print_matrix(self, matrix): | |
"""Prints a two-dimensional array.""" | |
if matrix: | |
for row in range(len(matrix)): | |
print '|', | |
for col in range(len(matrix[row])): | |
val = matrix[row][col] | |
print repr(val).center(4), '|', | |
if __name__ == '__main__': | |
print '== 16.20/16.21 ==' | |
image = [[255, 7, 3], | |
[212, 240, 4], | |
[218, 216, 230]] | |
print 'Horizontal kernel:' | |
kernel = [[1, -1]] | |
lf = LinearFilter(image, kernel) | |
lf.filter() | |
lf.print_in() | |
lf.print_out() | |
print 'Optional (not in 16.20)' | |
print 'Vertical kernel:' | |
kernel2 = [[-1], | |
[1]] | |
lf.filter_with_kernel(kernel2) | |
lf.print_in() | |
lf.print_out() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment