最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python構(gòu)建圖像分類識(shí)別器的方法

 更新時(shí)間:2019年01月12日 16:16:11   作者:AI專家  
今天小編就為大家分享一篇Python構(gòu)建圖像分類識(shí)別器的方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧

機(jī)器學(xué)習(xí)用在圖像識(shí)別是非常有趣的話題。

我們可以利用OpenCV強(qiáng)大的功能結(jié)合機(jī)器學(xué)習(xí)算法實(shí)現(xiàn)圖像識(shí)別系統(tǒng)。

首先,輸入若干圖像,加入分類標(biāo)記。利用向量量化方法將特征點(diǎn)進(jìn)行聚類,并得出中心點(diǎn),這些中心點(diǎn)就是視覺碼本的元素。

其次,利用圖像分類器將圖像分到已知的類別中,ERF(極端隨機(jī)森林)算法非常流行,因?yàn)镋RF具有較快的速度和比較精確的準(zhǔn)確度。我們利用決策樹進(jìn)行正確決策。

最后,利用訓(xùn)練好的ERF模型后,創(chuàng)建目標(biāo)識(shí)別器,可以識(shí)別未知圖像的內(nèi)容。

當(dāng)然,這只是雛形,存在很多問題:

界面不友好。

準(zhǔn)確率如何保證,如何調(diào)整超參數(shù),只有認(rèn)真研究算法機(jī)理,才能真正清除內(nèi)部實(shí)現(xiàn)機(jī)制后給予改進(jìn)。

下面,上代碼:

import os

import sys
import argparse
import json
import cv2
import numpy as np
from sklearn.cluster import KMeans
# from star_detector import StarFeatureDetector
from sklearn.ensemble import ExtraTreesClassifier
from sklearn import preprocessing

try:
 import cPickle as pickle #python 2
except ImportError as e:
 import pickle #python 3

def load_training_data(input_folder):
 training_data = []
 if not os.path.isdir(input_folder):
  raise IOError("The folder " + input_folder + " doesn't exist")
  
 for root, dirs, files in os.walk(input_folder):
  for filename in (x for x in files if x.endswith('.jpg')):
   filepath = os.path.join(root, filename)
   print(filepath)
   object_class = filepath.split('\\')[-2]
   print("object_class",object_class)
   training_data.append({'object_class': object_class, 'image_path': filepath})
     
 return training_data
class StarFeatureDetector(object):
 def __init__(self):
  self.detector = cv2.xfeatures2d.StarDetector_create()
 def detect(self, img):
  return self.detector.detect(img)

class FeatureBuilder(object):
 def extract_features(self, img):
  keypoints = StarFeatureDetector().detect(img)
  keypoints, feature_vectors = compute_sift_features(img, keypoints)
  return feature_vectors
 def get_codewords(self, input_map, scaling_size, max_samples=12):
  keypoints_all = []
  count = 0
  cur_class = ''
  for item in input_map:
   if count >= max_samples:
    if cur_class != item['object_class']:
     count = 0
    else:
     continue
   count += 1
   if count == max_samples:
    print ("Built centroids for", item['object_class'])

   cur_class = item['object_class']
   img = cv2.imread(item['image_path'])
   img = resize_image(img, scaling_size)
   num_dims = 128
   feature_vectors = self.extract_features(img)
   keypoints_all.extend(feature_vectors)

  kmeans, centroids = BagOfWords().cluster(keypoints_all)
  return kmeans, centroids
class BagOfWords(object):
 def __init__(self, num_clusters=32):
  self.num_dims = 128
  self.num_clusters = num_clusters
  self.num_retries = 10

 def cluster(self, datapoints):
  kmeans = KMeans(self.num_clusters, 
      n_init=max(self.num_retries, 1),
      max_iter=10, tol=1.0)
  res = kmeans.fit(datapoints)
  centroids = res.cluster_centers_
  return kmeans, centroids

 def normalize(self, input_data):
  sum_input = np.sum(input_data)

  if sum_input > 0:
   return input_data / sum_input
  else:
   return input_data
 def construct_feature(self, img, kmeans, centroids):
  keypoints = StarFeatureDetector().detect(img)
  keypoints, feature_vectors = compute_sift_features(img, keypoints)
  labels = kmeans.predict(feature_vectors)
  feature_vector = np.zeros(self.num_clusters)

  for i, item in enumerate(feature_vectors):
   feature_vector[labels[i]] += 1

  feature_vector_img = np.reshape(feature_vector, ((1, feature_vector.shape[0])))
  return self.normalize(feature_vector_img)
# Extract features from the input images and 
# map them to the corresponding object classes
def get_feature_map(input_map, kmeans, centroids, scaling_size):
 feature_map = []
 for item in input_map:
  temp_dict = {}
  temp_dict['object_class'] = item['object_class']
 
  print("Extracting features for", item['image_path'])
  img = cv2.imread(item['image_path'])
  img = resize_image(img, scaling_size)

  temp_dict['feature_vector'] = BagOfWords().construct_feature(img, kmeans, centroids)
  if temp_dict['feature_vector'] is not None:
   feature_map.append(temp_dict)
 return feature_map

# Extract SIFT features
def compute_sift_features(img, keypoints):
 if img is None:
  raise TypeError('Invalid input image')

 img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
 keypoints, descriptors = cv2.xfeatures2d.SIFT_create().compute(img_gray, keypoints)
 return keypoints, descriptors

# Resize the shorter dimension to 'new_size' 
# while maintaining the aspect ratio
def resize_image(input_img, new_size):
 h, w = input_img.shape[:2]
 scaling_factor = new_size / float(h)

 if w < h:
  scaling_factor = new_size / float(w)

 new_shape = (int(w * scaling_factor), int(h * scaling_factor))
 return cv2.resize(input_img, new_shape)

def build_features_main():
 data_folder = 'training_images\\'
 scaling_size = 200
 codebook_file='codebook.pkl'
 feature_map_file='feature_map.pkl'
 # Load the training data
 training_data = load_training_data(data_folder)

 # Build the visual codebook
 print("====== Building visual codebook ======")
 kmeans, centroids = FeatureBuilder().get_codewords(training_data, scaling_size)
 if codebook_file:
  with open(codebook_file, 'wb') as f:
   pickle.dump((kmeans, centroids), f)
 
 # Extract features from input images
 print("\n====== Building the feature map ======")
 feature_map = get_feature_map(training_data, kmeans, centroids, scaling_size)
 if feature_map_file:
  with open(feature_map_file, 'wb') as f:
   pickle.dump(feature_map, f)
# --feature-map-file feature_map.pkl --model- file erf.pkl
#----------------------------------------------------------------------------------------------------------
class ERFTrainer(object):
 def __init__(self, X, label_words):
  self.le = preprocessing.LabelEncoder()
  self.clf = ExtraTreesClassifier(n_estimators=100,
    max_depth=16, random_state=0)

  y = self.encode_labels(label_words)
  self.clf.fit(np.asarray(X), y)

 def encode_labels(self, label_words):
  self.le.fit(label_words)
  return np.array(self.le.transform(label_words), dtype=np.float32)

 def classify(self, X):
  label_nums = self.clf.predict(np.asarray(X))
  label_words = self.le.inverse_transform([int(x) for x in label_nums])
  return label_words
#------------------------------------------------------------------------------------------

class ImageTagExtractor(object):
 def __init__(self, model_file, codebook_file):
  with open(model_file, 'rb') as f:
   self.erf = pickle.load(f)

  with open(codebook_file, 'rb') as f:
   self.kmeans, self.centroids = pickle.load(f)

 def predict(self, img, scaling_size):
  img = resize_image(img, scaling_size)
  feature_vector = BagOfWords().construct_feature(
    img, self.kmeans, self.centroids)
  image_tag = self.erf.classify(feature_vector)[0]
  return image_tag

def train_Recognizer_main():
 feature_map_file = 'feature_map.pkl'
 model_file = 'erf.pkl'
 # Load the feature map
 with open(feature_map_file, 'rb') as f:
  feature_map = pickle.load(f)
 # Extract feature vectors and the labels
 label_words = [x['object_class'] for x in feature_map]
 dim_size = feature_map[0]['feature_vector'].shape[1]
 X = [np.reshape(x['feature_vector'], (dim_size,)) for x in feature_map]

 # Train the Extremely Random Forests classifier
 erf = ERFTrainer(X, label_words)
 if model_file:
  with open(model_file, 'wb') as f:
   pickle.dump(erf, f)
 #--------------------------------------------------------------------
 # args = build_arg_parser().parse_args()
 model_file = 'erf.pkl'
 codebook_file ='codebook.pkl'
 import os
 rootdir=r"F:\airplanes"
 list=os.listdir(rootdir)
 for i in range(0,len(list)):
  path=os.path.join(rootdir,list[i])
  if os.path.isfile(path):
   try:
    print(path)
    input_image = cv2.imread(path)
    scaling_size = 200
    print("\nOutput:", ImageTagExtractor(model_file,codebook_file)\
      .predict(input_image, scaling_size))
   except:
    continue
 #-----------------------------------------------------------------------
build_features_main()
train_Recognizer_main()

以上這篇Python構(gòu)建圖像分類識(shí)別器的方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • 如何利用PyQt5制作一個(gè)簡單的登錄界面

    如何利用PyQt5制作一個(gè)簡單的登錄界面

    初學(xué)者制作登錄界面時(shí)常遇到網(wǎng)上代碼看不懂、不會(huì)用、用不了的問題,下面這篇文章主要給大家介紹了關(guān)于如何利用PyQt5制作一個(gè)簡單的登錄界面,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2022-06-06
  • Python八皇后問題解答過程詳解

    Python八皇后問題解答過程詳解

    這篇文章主要介紹了Python講解八皇后問題過程詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-07-07
  • Win10 安裝PyCharm2019.1.1(圖文教程)

    Win10 安裝PyCharm2019.1.1(圖文教程)

    這篇文章主要介紹了Win10 安裝PyCharm2019.1.1(圖文教程),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-09-09
  • python分布式系統(tǒng)Celery安裝使用實(shí)例講解

    python分布式系統(tǒng)Celery安裝使用實(shí)例講解

    這篇文章主要為大家介紹了python分布式系統(tǒng)Celery安裝使用實(shí)例講解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-12-12
  • 源碼解析python中randint函數(shù)的效率缺陷

    源碼解析python中randint函數(shù)的效率缺陷

    這篇文章主要介紹了源碼解析python中randint函數(shù)的效率缺陷,通過討論?random?模塊的實(shí)現(xiàn),并討論了一些更為快速的生成偽隨機(jī)整數(shù)的替代方法展開主題,需要的盆友可以參考一下
    2022-06-06
  • 利用Python繪制隨機(jī)游走圖的詳細(xì)過程

    利用Python繪制隨機(jī)游走圖的詳細(xì)過程

    隨機(jī)游走(random walk)也稱隨機(jī)漫步,隨機(jī)行走等,是以隨機(jī)的方式采取連續(xù)步驟的過程,下面這篇文章主要給大家介紹了關(guān)于利用Python繪制隨機(jī)游走圖的相關(guān)資料,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2024-02-02
  • python得到電腦的開機(jī)時(shí)間方法

    python得到電腦的開機(jī)時(shí)間方法

    今天小編就為大家分享一篇python得到電腦的開機(jī)時(shí)間方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-10-10
  • python函數(shù)實(shí)例萬花筒實(shí)現(xiàn)過程

    python函數(shù)實(shí)例萬花筒實(shí)現(xiàn)過程

    這篇文章主要為大家介紹了python函數(shù)實(shí)例萬花筒實(shí)現(xiàn)過程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-06-06
  • Python 實(shí)現(xiàn)Serial 與STM32J進(jìn)行串口通訊

    Python 實(shí)現(xiàn)Serial 與STM32J進(jìn)行串口通訊

    今天小編就為大家分享一篇Python 實(shí)現(xiàn)Serial 與STM32J進(jìn)行串口通訊,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-12-12
  • Python裝飾器原理與用法分析

    Python裝飾器原理與用法分析

    這篇文章主要介紹了Python裝飾器原理與用法,結(jié)合實(shí)例形式分析了Python裝飾器的概念、原理、使用方法及相關(guān)操作注意事項(xiàng),需要的朋友可以參考下
    2018-04-04

最新評論

榆林市| 张北县| 夏邑县| 墨脱县| 南宁市| 郯城县| 哈尔滨市| 辉南县| 洛南县| 阜城县| 晋宁县| 当涂县| 怀宁县| 梧州市| 沿河| 永顺县| 壶关县| 张掖市| 密山市| 肥乡县| 香港| 元江| 梁平县| 利辛县| 高尔夫| 奎屯市| 内乡县| 雷山县| 汤阴县| 嘉荫县| 宜州市| 闸北区| 咸丰县| 高清| 永川市| 鄂托克旗| 榆树市| 隆昌县| 宜州市| 四会市| 江阴市|