日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

如何使用CNN进行物体识别和分类_RCNN物体识别

發布時間:2024/7/23 编程问答 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 如何使用CNN进行物体识别和分类_RCNN物体识别 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

? ? ? ? ? ? ? ? R-CNN,圖片識別

目標檢測(Object Detection)是圖像分類的延伸,除了分類任務,還要給定多個檢測目標的坐標位置。R-CNN是最早基于CNN的目標檢測方法,然后基于這條路線依次演進出了SPPnet,Fast R-CNN和Faster R-CNN,然后到2017年的Mask R-CNN。

R-CNN 模型由候選區域(Region Proposal)、特征提取(Feature Extractor)和分類器(Classifier)三個模塊組成。候選區域生成并提取獨立類別的候選區域。特征提取從每個候選區域中提取特征,通常使用深度卷積神經網絡。分類器使用線性 SVM 分類器模型將提取出的特征目標分類為已知類別之一。R-CNN 結構如下圖所示。

1.候選區域

????R-CNN 生成候選區域時使用了選擇性搜索(Selective Search)算法,用來提出候選區域或圖像中潛在對象的邊界框。選擇性搜索算法把圖像分割成 1000-2000 個小區域,遍歷分割的小區域并合并可能性最高的相鄰區域,知道整張圖像合并成一個區域位置,合并后輸出所有存在過的區域,即候選區域。

通過選擇性搜索算法選出的候選邊框為矩形,不同物體矩形邊框大小不同。但CNN模型的輸入層圖片必須固定分辨率,如果選擇性搜索算法選出的矩形邊框不進行預處理,則不能作為CNN的輸入提取圖像特征。因此每個輸入圖像的矩形候選框均要進行大小格式化處理。

2.特征提取

對特定目標的識別檢測的難點之一是已標記物體分類標簽的訓練數據不多,CNN通常進行隨機初始化神經網絡參數,對訓練數據量的要求非常高,因此 R-CNN 采用有監督的預訓練,網絡優化求解時采用隨機梯度下降法,學習率大小為 0.001。

特征提取網絡預訓練后,采用選擇性搜索算法搜索出來的候選框繼續對經過了預訓練 CNN模型進行訓練。其原理是,假設模型需要檢測的目標類別有N個,則要對前述經預訓練的CNN模型最后一層進行替換,輸出成N+1個神經元,其中多出一個背景神經元。該層的訓練過程使用隨機初始化參數的方法,其它網絡層則參數不變。輸入一張圖片,可以得到 2000個左右候選框(Bounding? Box)。數據集中的圖片是提前進行人工標注的數據,每張圖片都標注了涵蓋目標物體的正確邊框,因此在CNN階段需要用重疊度(Intersection over Union,Io U)為 2000 個 Bounding Box 打分。若通過選擇性搜索算法選出的 Bounding Box 與人工標注目標物體框的 Io U 大于 0.5,則將被 Bounding Box選中的物體標注成目標物體類別,該類物體成為正樣本,若 Io U 小于 0.5 則該 Bounding Box 所框為背景類別,也成為負樣本。

3.分類器

CNN的輸出是一個4096個元素向量,用于描述圖像的內容,并將其輸入線性SVM進行分類,對每個已知類別的目標物體都訓練一個支持向量機(Support? Vector Machine,SVM),因此這是一個二分類問題。在特征提取過程中 R-CNN 模型通過選擇性搜索算法選取了 2000 個左右 Bounding Box,即一個 2000×4096 特征向量矩陣,之后將矩陣與 SVM 權值矩陣 4096×N 點乘,可得到 2000×N 的結果矩陣,該矩陣表示了 2000個 Bounding Box 的分類結果。

R-CNN有如下缺點:

(1)需固定每一張子圖片的大小,改變了原有圖片的尺寸,影響CNN分類器的效果。

(2)將每一候選圖片放入分類器訓練,速度很慢并且有重復計算。

(3)其訓練是分階段的,對于目標檢測而言,R-CNN首先需要對預訓練模型進行特定類別物體的微調訓練,然后再訓練SVM對提取到的特征進行分類,最后還需要訓練候選框回歸器(Bounding-box Regressor)對候選子圖中的目標進行精確的提取。

主程序:

import time

start = time.time()

import numpy as np

import os

import six.moves.urllib as urllib

import sys

import tarfile

import tensorflow.compat.v1 as tf

tf.disable_v2_behavior()

import zipfile

import cv2

from collections import defaultdict

from io import StringIO

from matplotlib import pyplot as plt

from PIL import Image

os.chdir('C://Users//fxlir//Desktop//my_detect')#文件夾路徑

#Env setup

# This is needed to display the images.

#%matplotlib inline

# This is needed since the notebook is stored in the object_detection folder.

sys.path.append("..")

#Object detection imports

from object_detection.utils import label_map_util

from object_detection.utils import visualization_utils as vis_util

#Model preparation

# What model to download.

#這是我們剛才訓練的模型

MODEL_NAME = 'C://Users//fxlir//Desktop//my_detect//models'#訓練好的模型文件夾

#對應的Frozen model位置

# Path to frozen detection graph. This is the actual model that is used for the object detection.

PATH_TO_CKPT = MODEL_NAME + '//frozen_inference_graph.pb'#訓練好的模型

# List of the strings that is used to add correct label for each box.

PATH_TO_LABELS = os.path.join('training', 'object-detection.pbtxt') #類別標簽

#改成自己例子中的類別數,4

NUM_CLASSES = 1

#Load a (frozen) Tensorflow model into memory.???

detection_graph = tf.Graph()

with detection_graph.as_default():

? od_graph_def = tf.GraphDef()

? with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:

??? serialized_graph = fid.read()

??? od_graph_def.ParseFromString(serialized_graph)

??? tf.import_graph_def(od_graph_def, name='')???

#Loading label map

label_map = label_map_util.load_labelmap(PATH_TO_LABELS)

categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True)

category_index = label_map_util.create_category_index(categories)

#Helper code

def load_image_into_numpy_array(image):

? (im_width, im_height) = image.size

? return np.array(image.getdata()).reshape(

????? (im_height, im_width, 3)).astype(np.uint8)

#Detection

# If you want to test the code with your images, just add path to the images to the TEST_IMAGE_PATHS.

#測試圖片位置

PATH_TO_TEST_IMAGES_DIR = 'C://Users//fxlir//Desktop//my_detect//raccoon'

os.chdir(PATH_TO_TEST_IMAGES_DIR)

TEST_IMAGE_PATHS = os.listdir(PATH_TO_TEST_IMAGES_DIR)

# Size, in inches, of the output images.

IMAGE_SIZE = (12, 8)

output_path = ('C://Users//fxlir//Desktop//my_detect//test_out//')

with detection_graph.as_default():

? with tf.Session(graph=detection_graph) as sess:

??? # Definite input and output Tensors for detection_graph

??? image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')

??? # Each box represents a part of the image where a particular object was detected.

??? detection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0')

??? # Each score represent how level of confidence for each of the objects.

??? # Score is shown on the result image, together with the class label.

??? detection_scores = detection_graph.get_tensor_by_name('detection_scores:0')

??? detection_classes = detection_graph.get_tensor_by_name('detection_classes:0')

??? num_detections = detection_graph.get_tensor_by_name('num_detections:0')

??? for image_path in TEST_IMAGE_PATHS:

????? image = cv2.imread(image_path, 0)

????? image_BGR = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR)#

????? #image_RGB = cv2.cvtColor(image_BGR, cv2.COLOR_BGR2RGB)#

????? image_np = image_BGR

????? image_np_expanded = np.expand_dims(image_np, axis=0)

????? (boxes, scores, classes, num) = sess.run(

??????? [detection_boxes, detection_scores, detection_classes, num_detections],

??????? feed_dict={image_tensor: image_np_expanded})

????? vis_util.visualize_boxes_and_labels_on_image_array(

??????????? image_np,

??????????? np.squeeze(boxes),

??????????? np.squeeze(classes).astype(np.int32),

??????????? np.squeeze(scores),

??????????? category_index,

??????????? use_normalized_coordinates=True,

??????????? line_thickness=8)

????? cv2.imwrite(output_path+image_path.split('\\')[-1],image_np)

????? cv2.imshow('object detection', image_np)

????? cv2.waitKey(0)

????? cv2.destroyAllWindows()

end =? time.time()

print("Execution Time: ", end - start)

#歡迎訂閱,一起學習,一起交流

總結

以上是生活随笔為你收集整理的如何使用CNN进行物体识别和分类_RCNN物体识别的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。