In [1]:
%pylab inline
font = {'family' : 'normal',
        'weight' : 'normal',
        'size'   : 20}

pylab.rc('font', **font)
pylab.rcParams['figure.figsize'] = (10.0, 8.0)


Populating the interactive namespace from numpy and matplotlib

In [2]:
import cv2
import cv
import numpy as np
import pylab as pl
import scipy.ndimage
import itertools
import scipy.optimize
from sleepysnail.utils.figure_maker import FigureMaker

In [2]:


In [30]:
class Undistortor(object):
    def __init__(self, image):
        # preprocess image
        morph = self.pre_process(image)
        p = np.percentile(morph,90)
        fm(morph, "morph") ### FIXME
        _,morph = cv2.threshold(morph,p,255,cv.CV_THRESH_BINARY)
        fm(morph, "bin") ### FIXME
        rranges = (slice(1000, 10000, 500), slice(0, -15, -0.5))
        #rranges = (slice(4000, 6000, 1000), slice(0, -7, -1))
        
#         res = scipy.optimize.brute(self.distance_fun, 
#                                    rranges, args=(morph,),
#                                    finish=scipy.optimize.fmin)
        
        res, d, xy, z = scipy.optimize.brute(self.distance_fun, 
                                   rranges, args=(morph,),
                                   finish=scipy.optimize.fmin,
                                   full_output=True)
        #pl.figure(figsize=(16.0, 16.0))
        pl.figure()
        print xy
        pl.contourf(xy[0,:,:],xy[1,:,:],z, figsize=(8, 6), dpi=80, facecolor='w', edgecolor='k')
        pl.ylabel('f')
        pl.xlabel(r'$k\times10^{-3}$')
        pl.plot(res[0], res[1],'o', color="k", markersize=10)
        pl.plot(4,-8,'x', color="k", markersize=10)
        pl.colorbar()
        pl.savefig("lansdcape.svg")
        
        #print scipy.optimize.fmin(self.distance_fun, [5000,-3],args=(image,))
        self.cam_mat, self.coefs = self._find_cam_matrix(image, *res)
        
    def pre_process(self, image):
        erosion_size=9
        kern_size = 2*erosion_size + 1
        elem = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, 
                                         (kern_size, kern_size),
                                         (erosion_size, erosion_size))
        grey = cv2.medianBlur(image,3)
        morph = cv2.dilate(grey, elem)
        morph = cv2.erode(morph, elem)
        morph = cv2.subtract(morph, grey)
        return morph

    def distance_fun(self,x , *args):
        f,k = x
        f = f
        morph = args[0]
               
        cam_mat, coefs = self._find_cam_matrix(morph, f, k)
        tmp = cv2.undistort(morph, cam_mat, coefs)
        
        
        
        lines = cv2.HoughLinesP(tmp, rho=1, theta=np.pi/180.0, threshold=20, minLineLength=morph.shape[0]/2)
        if lines is None:
            return np.Inf
        
        
        grid_col = cv2.cvtColor(tmp, cv.CV_GRAY2BGR) ### FIXME
        
        for x1,y1,x2,y2 in lines[0]:### FIXME
            cv2.line(grid_col, (x1,y1),(x2,y2),(255,0,0),5)### FIXME
        fm(grid_col,"%f_%f" % (f,k))### FIXME

        pt1 = lines[0,:, 0] + 1j * lines[0, :, 1]
        pt2 = lines[0, :, 2] + 1j * lines[0, :, 3]
        out = np.log10(1 / np.sum(abs(pt1 - pt2)))
        fm(tmp,"_orig_%f_%f_%f" % (f,k,out))### FIXME
        return out

    def _find_cam_matrix(self, image,f,k):
        camera_matrix = np.zeros((3,3),'float32')
        camera_matrix[0,0]= f 
        camera_matrix[1,1]= f 
        camera_matrix[2,2]=1.0
        camera_matrix[0,2]=image.shape[1]/2.0
        camera_matrix[1,2]=image.shape[0]/2.0
        dist_coefs = np.array([k,k,0,0],'float32')
        return camera_matrix, dist_coefs


    def undistort(self, image):
        cam_mat=self.cam_mat
        coefs=self.coefs
        return cv2.undistort(image, cam_mat, coefs)

In [31]:
fm = FigureMaker("./", "undistort_fig")
grid_img = cv2.imread("orig_frame.png") 
grid_grey = cv2.cvtColor(grid_img, cv.CV_BGR2GRAY)
ud = Undistortor(grid_grey)


[[[  1.00000000e+03   1.00000000e+03   1.00000000e+03 ...,   1.00000000e+03
     1.00000000e+03   1.00000000e+03]
  [  1.50000000e+03   1.50000000e+03   1.50000000e+03 ...,   1.50000000e+03
     1.50000000e+03   1.50000000e+03]
  [  2.00000000e+03   2.00000000e+03   2.00000000e+03 ...,   2.00000000e+03
     2.00000000e+03   2.00000000e+03]
  ..., 
  [  8.50000000e+03   8.50000000e+03   8.50000000e+03 ...,   8.50000000e+03
     8.50000000e+03   8.50000000e+03]
  [  9.00000000e+03   9.00000000e+03   9.00000000e+03 ...,   9.00000000e+03
     9.00000000e+03   9.00000000e+03]
  [  9.50000000e+03   9.50000000e+03   9.50000000e+03 ...,   9.50000000e+03
     9.50000000e+03   9.50000000e+03]]

 [[  0.00000000e+00  -5.00000000e-01  -1.00000000e+00 ...,  -1.35000000e+01
    -1.40000000e+01  -1.45000000e+01]
  [  0.00000000e+00  -5.00000000e-01  -1.00000000e+00 ...,  -1.35000000e+01
    -1.40000000e+01  -1.45000000e+01]
  [  0.00000000e+00  -5.00000000e-01  -1.00000000e+00 ...,  -1.35000000e+01
    -1.40000000e+01  -1.45000000e+01]
  ..., 
  [  0.00000000e+00  -5.00000000e-01  -1.00000000e+00 ...,  -1.35000000e+01
    -1.40000000e+01  -1.45000000e+01]
  [  0.00000000e+00  -5.00000000e-01  -1.00000000e+00 ...,  -1.35000000e+01
    -1.40000000e+01  -1.45000000e+01]
  [  0.00000000e+00  -5.00000000e-01  -1.00000000e+00 ...,  -1.35000000e+01
    -1.40000000e+01  -1.45000000e+01]]]

In [32]:
print ud.coefs
print ud.cam_mat
fm(ud.undistort(grid_img), "last")


[-3.5 -3.5  0.   0. ]
[[  6.00000000e+03   0.00000000e+00   6.40000000e+02]
 [  0.00000000e+00   6.00000000e+03   4.80000000e+02]
 [  0.00000000e+00   0.00000000e+00   1.00000000e+00]]

In [33]:
p = np.array([[ 263,415,1036,374],
              [ 272,330,984,293]])
grid_col = cv2.cvtColor(grid_grey, cv.CV_GRAY2RGB)
for x1,y1,x2,y2 in p:
    print (x1,y1),(x2,y2)
    cv2.line(grid_col, (x1,y1),(x2,y2),(255,0,0),5)
pl.imshow(grid_col)


(263, 415) (1036, 374)
(272, 330) (984, 293)
Out[33]:
<matplotlib.image.AxesImage at 0x60f9710>

In [34]:
pl.imshow(ud.pre_process(grid_grey))


Out[34]:
<matplotlib.image.AxesImage at 0x5bd9150>

In [35]:
pl.imshow(ud.undistort(grid_img))
print ud.coefs
print ud.cam_mat


[-3.5 -3.5  0.   0. ]
[[  6.00000000e+03   0.00000000e+00   6.40000000e+02]
 [  0.00000000e+00   6.00000000e+03   4.80000000e+02]
 [  0.00000000e+00   0.00000000e+00   1.00000000e+00]]

In [29]:


In [23]:


In [ ]: