In [174]:
import numpy as np
import cv2

lena = cv2.imread('lena.jpg')
lena[:2]
Out[174]:
array([[[132, 134, 228],
        [132, 134, 228],
        [130, 135, 228],
        ..., 
        [136, 151, 244],
        [114, 132, 227],
        [ 82, 102, 197]],

       [[130, 135, 228],
        [130, 135, 228],
        [130, 135, 228],
        ..., 
        [124, 145, 237],
        [102, 127, 219],
        [ 73, 100, 191]]], dtype=uint8)
In [175]:
lena = cv2.imread('lena.jpg', cv2.CV_LOAD_IMAGE_GRAYSCALE)
lena
Out[175]:
array([[162, 162, 162, ..., 177, 158, 128],
       [162, 162, 162, ..., 170, 152, 124],
       [161, 161, 161, ..., 170, 152, 128],
       ..., 
       [ 45,  47,  48, ..., 101, 100,  98],
       [ 45,  46,  48, ..., 103, 104, 104],
       [ 44,  46,  48, ..., 105, 107, 108]], dtype=uint8)
In [176]:
print(type(lena))
print(lena.shape)
<type 'numpy.ndarray'>
(512, 512)
In [177]:
import matplotlib.pyplot as plot

plot.imshow(lena, cmap='gray')
Out[177]:
<matplotlib.image.AxesImage at 0x103b6e90>
In [178]:
cv2.imwrite('lenagray.png', lena)
Out[178]:
True
In [179]:
img = cv2.imread('lena.jpg')
b,g,r = cv2.split(img)
img2 = cv2.merge([r,g,b])
f = plot.figure()
f.add_subplot(1,2,1).imshow(img)
f.add_subplot(1,2,2).imshow(img2)
Out[179]:
<matplotlib.image.AxesImage at 0x10ab4bd0>

Filters

In [180]:
blurred = cv2.blur(lena, ksize=(1,1)) # Try ksize=(10,10), (1,10), (10,1)
plot.imshow(blurred[200:400, 200:400], cmap='gray')
Out[180]:
<matplotlib.image.AxesImage at 0x10f61510>
What blurring actually does?
In [181]:
img = np.array([[0, 9, 0, 9, 9, 9, 0, 0, 20, 40]],dtype='uint8')
blurred = cv2.blur(img, ksize=(1,1))  # Try (1,1), (3,1), (5,1), (11,1)
print(img.tolist())
print(blurred.tolist())
[[0, 9, 0, 9, 9, 9, 0, 0, 20, 40]]
[[0, 9, 0, 9, 9, 9, 0, 0, 20, 40]]
In [182]:
blurred = cv2.blur(lena, ksize=(5,5))
f = plot.figure()
f.add_subplot(1,2,1).imshow(lena[200:210, 200:210], cmap='gray', interpolation='none')
f.add_subplot(1,2,2).imshow(blurred[200:210, 200:210], cmap='gray', interpolation='none')
Out[182]:
<matplotlib.image.AxesImage at 0x11230510>
In [183]:
print(blurred.shahpe)
print(blurred[1:3,1:3])
(512, 512)
[[161 161]
 [161 161]]
In [183]: