Coursera-Deep Learning専門コース(4):畳み込みニューラルネットワーク:-weak3プログラミングの割り当て

自動運転における車両検出

自動運転-車の検出

import argparse
import os
import matplotlib.pyplot as plt
from matplotlib.pyplot import imshow
import scipy.io
import scipy.misc
import numpy as np
import pandas as pd
import PIL
import tensorflow as tf
from keras import backend as K
from keras.layers import Input, Lambda, Conv2D
from keras.models import load_model, Model
from yolo_utils import read_classes, read_anchors, generate_colors, preprocess_image, draw_boxes, scale_boxes
from yad2k.models.keras_yolo import yolo_head, yolo_boxes_to_corners, preprocess_true_boxes, yolo_loss, yolo_body

%matplotlib inline

1-問題の説明

ここに写真の説明を書きます

2-ヨロ

YOLO(「一度だけ見る」)は、リアルタイムで実行できると同時に高精度を実現するため、人気のあるアルゴリズムです。このアルゴリズムは、予測を行うためにネットワークを1回だけ順方向に伝搬する必要があるという意味で、画像を「1度だけ見る」だけです。非最大抑制後、認識されたオブジェクトを境界ボックスとともに出力します。

2.1-モデルの詳細

最初に知っておくべきこと:
入力は形状の画像のバッチ(m、608、608、3)です
。出力は、認識されたクラスと一緒に境界ボックスのリストです。上で説明したように、各境界ボックスは6つの数値(pc、bx、by、bh、bw、c)(pc、bx、by、bh、bw、c)で表されます。ccを80次元のベクトルに展開すると、各境界ボックスは85の数値で表されます。
5つのアンカーボックスを使用します。したがって、YOLOアーキテクチャは次のように考えることができます。IMAGE(m、608、608、3)-> DEEP CNN-> ENCODING(m、19、19、5、85)。
このエンコーディングが何を表すかをさらに詳しく見てみましょう。
ここに写真の説明を書きます
5つのアンカーボックスを使用しているため、19 x19の各セルは5つのボックスに関する情報をエンコードします。アンカーボックスは、幅と高さによってのみ定義されます。
簡単にするために、形状の最後の2つの次元(19、19、5、85)エンコーディングをフラット化します。したがって、Deep CNNの出力は(19、19、425)です。
ここに写真の説明を書きます
次に、(各セルの)各ボックスについて、次の要素ごとの積を計算し、ボックスに特定のクラスが含まれている確率を抽出します。
ここに写真の説明を書きます
これは、YOLOが画像で予測していることを視覚化する1つの方法です
。19x19のグリッドセルごとに、確率スコアの最大値を見つけます(5つのアンカーボックスと異なるクラスの両方で最大値をとります)。
そのグリッドセルが最も可能性が高いと見なすオブジェクトに従って、そのグリッドセルに色を付けます。
これを行うと、次の画像が表示されます。
ここに写真の説明を書きます
YOLOの出力を視覚化する別の方法は、YOLOが出力する境界ボックスをプロットすることです。これを行うと、次のような視覚化が得られ
ここに写真の説明を書きます
ます。上の図では、モデルが高い確率で割り当てたボックスのみをプロットしましたが、これでもまだボックスが多すぎます。アルゴリズムの出力をフィルタリングして、検出されたオブジェクトの数を大幅に減らします。これを行うには、非最大抑制を使用します。具体的には、次の手順を実行します。
スコアの低いボックスを取り除く(つまり、ボックスはクラスの検出にあまり自信がない)。
複数のボックスが重なり合って同じオブジェクトを検出する場合は、1つのボックスのみを選択します。

2.2-クラススコアのしきい値によるフィルタリング

# GRADED FUNCTION: yolo_filter_boxes

def yolo_filter_boxes(box_confidence, boxes, box_class_probs, threshold = .6):
    """Filters YOLO boxes by thresholding on object and class confidence.

    Arguments:
    box_confidence -- tensor of shape (19, 19, 5, 1)
    boxes -- tensor of shape (19, 19, 5, 4)
    box_class_probs -- tensor of shape (19, 19, 5, 80)
    threshold -- real value, if [ highest class probability score < threshold], then get rid of the corresponding box

    Returns:
    scores -- tensor of shape (None,), containing the class probability score for selected boxes
    boxes -- tensor of shape (None, 4), containing (b_x, b_y, b_h, b_w) coordinates of selected boxes
    classes -- tensor of shape (None,), containing the index of the class detected by the selected boxes

    Note: "None" is here because you don't know the exact number of selected boxes, as it depends on the threshold. 
    For example, the actual output size of scores would be (10,) if there are 10 boxes.
    """

    # Step 1: Compute box scores
    ### START CODE HERE ### (≈ 1 line)
    box_scores = box_confidence*box_class_probs
    ### END CODE HERE ###

    # Step 2: Find the box_classes thanks to the max box_scores, keep track of the corresponding score
    ### START CODE HERE ### (≈ 2 lines)
    box_classes = K.argmax(box_scores,axis=-1)
    box_class_scores = K.max(box_scores,axis=-1)
    ### END CODE HERE ###

    # Step 3: Create a filtering mask based on "box_class_scores" by using "threshold". The mask should have the
    # same dimension as box_class_scores, and be True for the boxes you want to keep (with probability >= threshold)
    ### START CODE HERE ### (≈ 1 line)
    filtering_mask =  box_class_scores>=threshold
    ### END CODE HERE ###

    # Step 4: Apply the mask to scores, boxes and classes
    ### START CODE HERE ### (≈ 3 lines)
    scores = tf.boolean_mask(box_class_scores,filtering_mask)
    boxes = tf.boolean_mask(boxes,filtering_mask)
    classes = tf.boolean_mask(box_classes,filtering_mask)
    ### END CODE HERE ###

    return scores, boxes, classes
with tf.Session() as test_a:
    box_confidence = tf.random_normal([19, 19, 5, 1], mean=1, stddev=4, seed = 1)
    boxes = tf.random_normal([19, 19, 5, 4], mean=1, stddev=4, seed = 1)
    box_class_probs = tf.random_normal([19, 19, 5, 80], mean=1, stddev=4, seed = 1)
    scores, boxes, classes = yolo_filter_boxes(box_confidence, boxes, box_class_probs, threshold = 0.5)
    print(box_class_scores)
    print("scores[2] = " + str(scores[2].eval()))
    print("boxes[2] = " + str(boxes[2].eval()))
    print("classes[2] = " + str(classes[2].eval()))
    print("scores.shape = " + str(scores.shape))
    print("boxes.shape = " + str(boxes.shape))
    print("classes.shape = " + str(classes.shape))

2.3-最大でない抑制

# GRADED FUNCTION: iou

def iou(box1, box2):
    """Implement the intersection over union (IoU) between box1 and box2

    Arguments:
    box1 -- first box, list object with coordinates (x1, y1, x2, y2)
    box2 -- second box, list object with coordinates (x1, y1, x2, y2)
    """

    # Calculate the (y1, x1, y2, x2) coordinates of the intersection of box1 and box2. Calculate its Area.
    ### START CODE HERE ### (≈ 5 lines)
    xi1 = np.maximum(box1[0],box2[0])
    yi1 = np.maximum(box1[1],box2[1])
    xi2 = np.minimum(box1[2],box2[2])
    yi2 = np.minimum(box1[3],box2[3])
    inter_area = (xi2 - xi1) * (yi2 - yi1)
    ### END CODE HERE ###    

    # Calculate the Union area by using Formula: Union(A,B) = A + B - Inter(A,B)
    ### START CODE HERE ### (≈ 3 lines)
    box1_area = (np.maximum(box1[0],box1[2])-np.minimum(box1[0],box1[2]))*(np.maximum(box1[1],box1[3])-np.minimum(box1[1],box1[3]))
    box2_area = (np.maximum(box2[0],box2[2])-np.minimum(box2[0],box2[2]))*(np.maximum(box2[1],box2[3])-np.minimum(box2[1],box2[3]))
    union_area = box1_area+box2_area-inter_area
    ### END CODE HERE ###

    # compute the IoU
    ### START CODE HERE ### (≈ 1 line)
    iou = inter_area/ union_area
    ### END CODE HERE ###

    return iou
box1 = (2, 1, 4, 3)
box2 = (1, 2, 3, 4) 
print("iou = " + str(iou(box1, box2)))

iou = 0.142857142857

# GRADED FUNCTION: yolo_non_max_suppression

def yolo_non_max_suppression(scores, boxes, classes, max_boxes = 10, iou_threshold = 0.5):
    """
    Applies Non-max suppression (NMS) to set of boxes

    Arguments:
    scores -- tensor of shape (None,), output of yolo_filter_boxes()
    boxes -- tensor of shape (None, 4), output of yolo_filter_boxes() that have been scaled to the image size (see later)
    classes -- tensor of shape (None,), output of yolo_filter_boxes()
    max_boxes -- integer, maximum number of predicted boxes you'd like
    iou_threshold -- real value, "intersection over union" threshold used for NMS filtering

    Returns:
    scores -- tensor of shape (, None), predicted score for each box
    boxes -- tensor of shape (4, None), predicted box coordinates
    classes -- tensor of shape (, None), predicted class for each box

    Note: The "None" dimension of the output tensors has obviously to be less than max_boxes. Note also that this
    function will transpose the shapes of scores, boxes, classes. This is made for convenience.
    """

    max_boxes_tensor = K.variable(max_boxes, dtype='int32')     # tensor to be used in tf.image.non_max_suppression()
    K.get_session().run(tf.variables_initializer([max_boxes_tensor])) # initialize variable max_boxes_tensor

    # Use tf.image.non_max_suppression() to get the list of indices corresponding to boxes you keep
    ### START CODE HERE ### (≈ 1 line)
    nms_indices = tf.image.non_max_suppression(boxes,scores,max_boxes,iou_threshold = 0.5)
    ### END CODE HERE ###

    # Use K.gather() to select only nms_indices from scores, boxes and classes
    ### START CODE HERE ### (≈ 3 lines)
    scores = K.gather(scores,nms_indices)
    boxes = K.gather(boxes,nms_indices)
    classes = K.gather(classes,nms_indices )
    ### END CODE HERE ###

    return scores, boxes, classes
with tf.Session() as test_b:
    scores = tf.random_normal([54,], mean=1, stddev=4, seed = 1)
    boxes = tf.random_normal([54, 4], mean=1, stddev=4, seed = 1)
    classes = tf.random_normal([54,], mean=1, stddev=4, seed = 1)
    scores, boxes, classes = yolo_non_max_suppression(scores, boxes, classes)
    print("scores[2] = " + str(scores[2].eval()))
    print("boxes[2] = " + str(boxes[2].eval()))
    print("classes[2] = " + str(classes[2].eval()))
    print("scores.shape = " + str(scores.eval().shape))
    print("boxes.shape = " + str(boxes.eval().shape))
    print("classes.shape = " + str(classes.eval().shape))

スコア[2] = 6.9384
ボックス[2] = [-5.299932 3.13798141 4.45036697 0.95942086]
クラス[2] = -2.24527
スコア。シェイプ=(10、)
ボックス。シェイプ=(
10、4 クラス。シェイプ=(10、)

2.4フィルタリングのまとめ

ディープCNN(19x19x5x85次元エンコーディング)の出力を取得し、実装したばかりの関数を使用してすべてのボックスをフィルタリングする関数を実装する時が来ました。
演習:YOLOエンコーディングの出力を取得し、スコアしきい値とNMSを使用してボックスをフィルタリングするyolo_eval()を実装します。最後に知っておくべき実装の詳細は1つだけです。ボックスのコーナーや中点、高さ/幅など、ボックスを表す方法はいくつかあります。(我々が提供されている)は、以下の関数を使用して、異なる時間にいくつかのそのようなフォーマット間YOLOの変換、:
箱= yolo_boxes_to_corners(box_xy、box_wh)
の角の座標をボックスにYOLOボックス座標(X、Y、W、H)に変換します(x1、y1、x2、y2)yolo_filter_boxesの入力に合わせる
box = scale_boxes(boxes、image_shape)
YOLOのネットワークは、608x608画像で実行するようにトレーニングされています。このデータを別のサイズの画像でテストしている場合(たとえば、自動車検出データセットに720x1280の画像があった場合)、この手順でボックスを再スケーリングして、元の720x1280画像の上にプロットできるようにします。
これら2つの関数について心配する必要はありません。それらを呼び出す必要がある場所を示します。

# GRADED FUNCTION: yolo_eval

def yolo_eval(yolo_outputs, image_shape = (720., 1280.), max_boxes=10, score_threshold=.6, iou_threshold=.5):
    """
    Converts the output of YOLO encoding (a lot of boxes) to your predicted boxes along with their scores, box coordinates and classes.

    Arguments:
    yolo_outputs -- output of the encoding model (for image_shape of (608, 608, 3)), contains 4 tensors:
                    box_confidence: tensor of shape (None, 19, 19, 5, 1)
                    box_xy: tensor of shape (None, 19, 19, 5, 2)
                    box_wh: tensor of shape (None, 19, 19, 5, 2)
                    box_class_probs: tensor of shape (None, 19, 19, 5, 80)
    image_shape -- tensor of shape (2,) containing the input shape, in this notebook we use (608., 608.) (has to be float32 dtype)
    max_boxes -- integer, maximum number of predicted boxes you'd like
    score_threshold -- real value, if [ highest class probability score < threshold], then get rid of the corresponding box
    iou_threshold -- real value, "intersection over union" threshold used for NMS filtering

    Returns:
    scores -- tensor of shape (None, ), predicted score for each box
    boxes -- tensor of shape (None, 4), predicted box coordinates
    classes -- tensor of shape (None,), predicted class for each box
    """

    ### START CODE HERE ### 

    # Retrieve outputs of the YOLO model (≈1 line)
    box_confidence, box_xy, box_wh, box_class_probs = yolo_outputs

    # Convert boxes to be ready for filtering functions 
    boxes = yolo_boxes_to_corners(box_xy, box_wh)

    # Use one of the functions you've implemented to perform Score-filtering with a threshold of score_threshold (≈1 line)
    scores, boxes, classes = yolo_filter_boxes(box_confidence, boxes, box_class_probs, threshold = .6)

    # Scale boxes back to original image shape.
    boxes = scale_boxes(boxes, image_shape)

    # Use one of the functions you've implemented to perform Non-max suppression with a threshold of iou_threshold (≈1 line)
    scores, boxes, classes = yolo_non_max_suppression(scores, boxes, classes, max_boxes = 10, iou_threshold = 0.5)

    ### END CODE HERE ###

    return scores, boxes, classes
with tf.Session() as test_b:
    yolo_outputs = (tf.random_normal([19, 19, 5, 1], mean=1, stddev=4, seed = 1),
                    tf.random_normal([19, 19, 5, 2], mean=1, stddev=4, seed = 1),
                    tf.random_normal([19, 19, 5, 2], mean=1, stddev=4, seed = 1),
                    tf.random_normal([19, 19, 5, 80], mean=1, stddev=4, seed = 1))
    scores, boxes, classes = yolo_eval(yolo_outputs)
    print("scores[2] = " + str(scores[2].eval()))
    print("boxes[2] = " + str(boxes[2].eval()))
    print("classes[2] = " + str(classes[2].eval()))
    print("scores.shape = " + str(scores.eval().shape))
    print("boxes.shape = " + str(boxes.eval().shape))
    print("classes.shape = " + str(classes.eval().shape))
scores[2] = 138.791
boxes[2] = [ 1292.32971191  -278.52166748  3876.98925781  -835.56494141]
classes[2] = 54
scores.shape = (10,)
boxes.shape = (10, 4)
classes.shape = (10,)

3-YOLOの事前トレーニング済みモデルを画像でテストする

このパートでは、事前学習済みモデルを使用して、自動車検出データセットでテストします。いつものように、グラフを開始するセッションを作成することから始めます。次のセルを実行します。

sess = K.get_session()

3.1-クラス、アンカー、画像形状の定義。

80のクラスを検出しようとし、5つのアンカーボックスを使用していることを思い出してください。80のクラスと5つのボックスに関する情報を「coco_classes.txt」と「yolo_anchors.txt」の2つのファイルに収集しました。次のセルを実行して、これらの量をモデルにロードしてみましょう。
車の検出デ​​ータセットには720x1280の画像があり、これを608x608の画像に前処理しました。

class_names = read_classes("model_data/coco_classes.txt")
anchors = read_anchors("model_data/yolo_anchors.txt")
image_shape = (720., 1280.)    

3.2-事前トレーニング済みモデルの読み込み

YOLOモデルのトレーニングには非常に長い時間がかかり、広範囲のターゲットクラスのラベル付きバウンディングボックスのかなり大きなデータセットが必要です。「yolo.h5」に保存されている既存の事前トレーニング済みKeras YOLOモデルをロードします。(これらの重みはYOLOの公式Webサイトから取得され、Allan Zelenerによって作成された関数を使用して変換されました。参照はこのノートブックの最後にあります。技術的には、これらは「YOLOv2」モデルのパラメーターですが、より簡単に参照します。このノートブックでは「YOLO」と表示されます。)このファイルからモデルをロードするには、以下のセルを実行します。

yolo_model = load_model("model_data/yolo.h5")
yolo_model.summary()

3.3-モデルの出力を使用可能な境界ボックステンソルに変換する

yolo_outputs = yolo_head(yolo_model.output, anchors, len(class_names))

3.4-フィルタリングボックス

yolo_outputsは、yolo_modelのすべての予測ボックスを正しい形式で提供しました。これで、フィルタリングを実行して、最適なボックスのみを選択する準備が整いました。これを行うには、以前に実装したyolo_evalを呼び出します。

scores, boxes, classes = yolo_eval(yolo_outputs, image_shape)

3.5-画像に対してグラフを実行する

def predict(sess, image_file):
    """
    Runs the graph stored in "sess" to predict boxes for "image_file". Prints and plots the preditions.

    Arguments:
    sess -- your tensorflow/Keras session containing the YOLO graph
    image_file -- name of an image stored in the "images" folder.

    Returns:
    out_scores -- tensor of shape (None, ), scores of the predicted boxes
    out_boxes -- tensor of shape (None, 4), coordinates of the predicted boxes
    out_classes -- tensor of shape (None, ), class index of the predicted boxes

    Note: "None" actually represents the number of predicted boxes, it varies between 0 and max_boxes. 
    """

    # Preprocess your image
    image, image_data = preprocess_image("images/" + image_file, model_image_size = (608, 608))

    # Run the session with the correct tensors and choose the correct placeholders in the feed_dict.
    # You'll need to use feed_dict={yolo_model.input: ... , K.learning_phase(): 0})
    ### START CODE HERE ### (≈ 1 line)
    out_scores, out_boxes, out_classes = sess.run(
                    [scores,boxes,classes],
                     feed_dict={
                         yolo_model.input:image_data,
                         K.learning_phase():0
                     })
    ### END CODE HERE ###

    # Print predictions info
    print('Found {} boxes for {}'.format(len(out_boxes), image_file))
    # Generate colors for drawing bounding boxes.
    colors = generate_colors(class_names)
    # Draw bounding boxes on the image file
    draw_boxes(image, out_scores, out_boxes, out_classes, class_names, colors)
    # Save the predicted bounding box on the image
    image.save(os.path.join("out", image_file), quality=90)
    # Display the results in the notebook
    output_image = scipy.misc.imread(os.path.join("out", image_file))
    imshow(output_image)

    return out_scores, out_boxes, out_classes
out_scores, out_boxes, out_classes = predict(sess, "0005.jpg")

0005.jpgの5つのボックスが見つかりました
車0.64(207、297 )(338、340)
車0.65(741、266 )(918、313
車0.67(15、313 )(128、362
車0.72(883、260) (1026、303)
車0.75(517、282)(689、336)
ここに写真の説明を書きます
別の画像を変更
ここに写真の説明を書きます

元の記事を34件公開 賞賛された4件 30,000回以上の閲覧

おすすめ

転載: blog.csdn.net/leaeason/article/details/78558183