tata色々な備忘録

データ解析、画像解析、化学分析などなど

scipy+Opencv+numpyによる画像分類

ヒストグラムを利用した分類法。
定番っすね。

import cv2
import numpy as np
import pylab as plt
import scipy.ndimage as nd

def mask_test(im):
    if im.ndim == 2:
        im2= im[0:890,:]
        im_gray = im2

    else :
        im2= im[0:890,:]
        im_gray =cv2.cvtColor(im2,cv2.COLOR_BGR2GRAY)
    im_gray_smooth=cv2.medianBlur(im_gray,5)
        
    bubbles = (im_gray_smooth <= 50) 
    sand = (im_gray_smooth > 50) & (im_gray_smooth <= 110)
    glass = (im_gray_smooth > 110)
     
    for img in (bubbles,sand,glass):
        img[:] = nd.binary_opening(img, iterations=3)
        img[:] = nd.binary_closing(img, iterations=3)
    
    colors = np.zeros((im2.shape[0],im2.shape[1],3),np.uint8)
    colors[bubbles]= (100,100,200)
    colors[sand]= (255,0,0)
    colors[glass]= (0,255,0)
        
    list = [('picture',im),('gray',im_gray),('gray_smooth',im_gray_smooth),('dummpy','dummy'),('glass',glass),('sand',sand),('bubbles',bubbles),('color',colors)]
    i=1
    for name,data in list :
        if i == 4:
            i += 1
        else:
            plt.subplot(2,4,i),plt.imshow(data,'gray')
            plt.title(name)
            plt.axis('off')
            i += 1

    plt.subplot(2,4,4),plt.hist(im_gray.flat,bins=80,range=(0,150))
    plt.show()
        
if __name__ == '__main__':
    im = cv2.imread("babble.jpg")
    if not (im == None):
        mask_test(im)

f:id:tatabox2000:20130811214629p:plain 後で修正予定。

参考
Scikit-Image
http://vimeo.com/53065496
Scipyチュートリアル
http://www.ike-dyn.ritsumei.ac.jp/~uchida/scipy-lecture-notes/intro/summary-exercises/answers_image_processing.html