In [1]:
hws=3 # half window size
batch_size=5 # batch size

import numpy as np
import cv2
from skimage.feature import local_binary_pattern
#from algae_core import cmap
import pickle
import os, fnmatch

#lbp
radius = 3
cmax=640
rmax=480
clmax=2
def get_image_pair(file_pair):
    """ """
    oim=cv2.imread(file_pair['raw'])#BGR
    im=cv2.resize(oim, (cmax,rmax),interpolation = cv2.INTER_CUBIC) 
       
    ocl=cv2.imread(file_pair['label'],0)
    cl=cv2.resize(ocl, (cmax,rmax),interpolation = cv2.INTER_NEAREST )
    #print cl.shape
    if cl is None:# not found
         cl=np.zeros( (im.shape[0],im.shape[1]),dtype=np.uint8 )
    
    print "raw: %s, label: %s"%(file_pair['raw'], file_pair['label'])
    
    im_grey=cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
    lbp = local_binary_pattern( im_grey, 8 * radius, radius, 'uniform')
    #cv2.imshow("lbp", lbp)
    return cl,im,lbp

def get_xy(train_pairs):
    xrmax= ( (rmax-2*hws)*(cmax-2*hws)*len(train_pairs) )
    xcmax= 3+(2*hws)**2    
    x=np.zeros((xrmax,xcmax), dtype=np.uint8)
    
    yrmax= ( (rmax-2*hws)*(cmax-2*hws)*len(train_pairs) )
    y=np.zeros((yrmax), dtype=np.uint8)
    k=0
    for count,i in enumerate(train_pairs):    
        #print "------- processed %d from %d"%(count,len(train_pairs))
        cl,im,lbp=get_image_pair(i)
        #show_overlay(cl,im)
        if im.shape[0]!=rmax or im.shape[1]!=cmax or lbp.shape[0]!=rmax or lbp.shape[1]!=cmax:
            print "Error: image pair has missmatch size."
        for r in xrange(hws,lbp.shape[0]-hws):
            for c in xrange(hws,lbp.shape[1]-hws):
                xrow=np.concatenate([im[r,c],
                        lbp[r-hws:r+hws,c-hws:c+hws].reshape(1,-1)[0],])
                x[k,:]=xrow
                y[k]=cl[r,c]
                k+=1
    return x,y


---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-1-b693b8ab5e33> in <module>()
      4 import numpy as np
      5 import cv2
----> 6 from skimage.feature import local_binary_pattern
      7 #from algae_core import cmap
      8 import pickle

ImportError: No module named skimage.feature

In [ ]:
#%reload_ext autoreload
#%autoreload 2
from algae_app.models import *
from django.db.models import Q, Sum, Count
import pandas as pd
from django.utils import timezone
from django.core.files import File
import cv2
import uuid
import numpy as np

In [ ]:
pwd

In [ ]:
import os, fnmatch
#dataset_path="C:\\Users\\Wasit\\Google Drive\\Projects\\2014_algae\\dataset_2016_sept_labelled\\dataset"
dataset_path="/root/dataset"
os.listdir(dataset_path)

In [ ]:
raw_files=fnmatch.filter(os.listdir(dataset_path), '*.jpg')
raw_list=[i[:-4] for i in raw_files]

label_files=fnmatch.filter(os.listdir(dataset_path), '*.png')
label_list={i[:-4]:None for i in label_files}

train_pairs=[]
for count,i in enumerate(raw_list):
    if i in label_list:
        train_pairs.append({
            'raw': os.path.join(dataset_path,i)+'.jpg',
            'label': os.path.join(dataset_path,i)+'.png',
            'recall': os.path.join(dataset_path,i+"_recall")+'.jpg',
        })
        
cmap=np.array([  
    ( 0  , 255, 255,  ),
    ( 14 , 127, 255,  ),
    ( 44 , 160, 44 ,  ),
    ( 40 , 39 , 214,  ),
    ( 0  , 0  , 255,  ),
    ( 0  , 255, 0  ,  ),
    ( 194, 119, 227,  ),
    ( 255, 0  , 0  ,  ),
    ( 34 , 189, 188,  ),
    ( 207, 190, 23 ,  ),])

In [ ]:
with open('forest.pic','rb') as f:
    forest = pickle.load(f)
    
for i in train_pairs[:10]:
    raw=RawImage()
    fname=i['raw']
    print fname
    raw.img.save(fname, File(open(fname, 'rb')))
    
    label=LabelImage(raw=raw)
    fname=i['label']
    label.img.save(fname, File(open(fname, 'rb')))
    
    x,y=get_xy( [i] )
    oim=cv2.imread(i['raw'])#BGR
    im=cv2.resize(oim, (cmax,rmax),interpolation = cv2.INTER_CUBIC) 
    cl_p=forest.predict( x )
    cl_p.resize((rmax-2*hws,cmax-2*hws))
    #cl_p=cv2.imread(i['label'],cv2.CV_LOAD_IMAGE_GRAYSCALE)
    ol=im.copy()
    algae_pixel=0
    for r in xrange(rmax-2*hws):
        for c in xrange(cmax-2*hws):
            predicting_class=cl_p[r,c]
            if predicting_class>0:
                ol[r+hws,c+hws] = cmap[ predicting_class-1 ]
                algae_pixel+=1
    ol_rgb = cv2.cvtColor(ol, cv2.COLOR_BGR2RGB)

    temp_fname=str(uuid.uuid4())+'.jpg'
    cv2.imwrite(temp_fname, ol)
    
    recall=RecallImage(raw=raw,algae_pixel=algae_pixel)
    fname=i['recall']
    recall.img.save(fname, File(open(temp_fname, 'rb')))
    
    os.remove(temp_fname)

End


In [ ]:
recall.img.name

In [ ]:
recall.img.path

In [ ]:
oim.shape

In [ ]:
im.shape

In [ ]:
cl_p.shape

In [ ]:
%matplotlib inline
import numpy as np
from matplotlib import pyplot as plt

cmap=np.array([  
    ( 0  , 255, 255,  ),
    ( 14 , 127, 255,  ),
    ( 44 , 160, 44 ,  ),
    ( 40 , 39 , 214,  ),
    ( 0  , 0  , 255,  ),
    ( 0  , 255, 0  ,  ),
    ( 194, 119, 227,  ),
    ( 255, 0  , 0  ,  ),
    ( 34 , 189, 188,  ),
    ( 207, 190, 23 ,  ),])

In [ ]:
#dummy labelling for debug only

hws=3
cmax=640
rmax=480
oim=cv2.imread(i['raw'])#BGR
im=cv2.resize(oim, (cmax,rmax),interpolation = cv2.INTER_CUBIC) 
#cl_p=forest.predict( x )
#cl_p.resize((rmax-2*hws,cmax-2*hws))
cl_p=cv2.imread(i['label'],cv2.CV_LOAD_IMAGE_GRAYSCALE)
cl_p=cv2.resize(cl_p, (cmax,rmax),interpolation = cv2.INTER_NEAREST) 
ol=im.copy()
for r in xrange(rmax-2*hws):
    for c in xrange(cmax-2*hws):
        predicting_class=cl_p[r,c]
        if predicting_class>0:
            ol[r+hws,c+hws] = cmap[ predicting_class-1 ]
ol_rgb = cv2.cvtColor(ol, cv2.COLOR_BGR2RGB)

temp_fname=str(uuid.uuid4())+'.jpg'
cv2.imwrite(temp_fname, ol_rgb)
os.remove(temp_fname)
plt.imshow(ol_rgb)
plt.show()

In [ ]:
x=uuid.uuid4()

In [ ]:


In [ ]: