吳恩達第四課第三週編程作業

目的

汽車識別

連接

鏈接:https://pan.baidu.com/s/1OmP2kolqjAXG5KaZvljAYQ 
提取碼:o8fw 

代碼

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 yad2k.models.keras_yolo import yolo_head, yolo_boxes_to_corners, preprocess_true_boxes, yolo_loss, yolo_body
import yolo_utils

#分類閾值過濾
def yolo_filter_boxes(box_confidence , boxes, box_class_probs, threshold = 0.6):
    """
    :param box_confidence: 維度(19,19,5,1),包含五個瞄框中的pc值
    :param boxes:維度(15,15,5,4),包含(px,py,ph,pw)
    :param box_class_probs:維度(15,15,5,80),包含所有對象檢測的概率(c1~~~c80)
    :param threshold:閾值,高於他將會保留
    """
    #計算瞄框的得分
    box_scores=box_confidence*box_class_probs
    #找到最大概率的框
    box_classes=K.argmax(box_scores,axis=-1)
    box_class_scores=K.max(box_scores,axis=-1)
    #創建掩碼
    filtering_mask=box_class_scores>=threshold
    scores=tf.boolean_mask(box_class_scores,filtering_mask)
    boxes=tf.boolean_mask(boxes,filtering_mask)
    classes=tf.boolean_mask(box_classes,filtering_mask)
    return scores,boxes,classes
#非最大值抑制
def iou(box1,box2):
    #計算相交域的面積
    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)
    #並集計算
    box1_area=(box1[2]-box1[0])*(box1[3]-box1[1])
    box2_area=(box2[2]-box2[0])*(box2[3]-box2[1])
    union_area=box1_area+box2_area-inter_area
    #交併集
    iou=inter_area/union_area
    return iou
def yolo_non_max_suppression(scores, boxes, classes, max_boxes=10, iou_threshold=0.5):
    """
    :param scores,boxes,classes: yolo_filter_boxes()的輸出
    :param max_boxes:整數,預測的錨框數量的最大值
    :param iou_threshold:實數,交併比閾值。
    """
    max_boxes_tensor =K.variable(max_boxes,dtype='int32')
    K.get_session().run(tf.variables_initializer([max_boxes_tensor]))#初始化變量
    #獲取與我們保留的框相對應的索引列表
    nms_indices=tf.image.non_max_suppression(boxes,scores,max_boxes,iou_threshold)

    scores=K.gather(scores,nms_indices)
    boxes=K.gather(boxes,nms_indices)
    classes=K.gather(classes,nms_indices)
    return scores,boxes,classes
#對所有框進行過濾
def yolo_eval(yolo_outputs, image_shape=(720.,1280.),
              max_boxes=10, score_threshold=0.6,iou_threshold=0.5):
    """
    :param yolo_outputs: 所有元素,維度(None,19,19,5,x)
    :param image_shape:輸入圖像的維度
    :param max_boxes:瞄框數量的最大值
    :param score_threshold:可能性閾值
    :param iou_threshold:交併比閾值
    """
    #獲取YOLO模型的輸出
    box_confidence, box_xy, box_wh, box_class_probs = yolo_outputs
    #中心點轉化爲邊角
    boxes=yolo_boxes_to_corners(box_xy,box_wh)
    #可信度分值過濾
    scores,boxes,classes=yolo_filter_boxes(box_confidence,boxes,box_class_probs,score_threshold)
    #縮放
    boxes=yolo_utils.scale_boxes(boxes,image_shape)
    #使用非最大抑制
    scores,boxes,classes=yolo_non_max_suppression(scores,boxes,classes,max_boxes,iou_threshold)
    return scores,boxes,classes



sess = K.get_session()
class_names = yolo_utils.read_classes("model_data/coco_classes.txt")
anchors = yolo_utils.read_anchors("model_data/yolo_anchors.txt")
image_shape = (720.,1280.)
yolo_model = load_model("model_data/yolov2.h5")
yolo_model.summary()
yolo_outputs = yolo_head(yolo_model.output, anchors, len(class_names))
scores, boxes, classes = yolo_eval(yolo_outputs, image_shape)
def predict(sess, image_file, is_show_info=True, is_plot=True):
    """
    運行存儲在sess的計算圖以預測image_file的邊界框,打印出預測的圖與信息。

    參數:
        sess - 包含了YOLO計算圖的TensorFlow/Keras的會話。
        image_file - 存儲在images文件夾下的圖片名稱
    返回:
        out_scores - tensor類型,維度爲(None,),錨框的預測的可能值。
        out_boxes - tensor類型,維度爲(None,4),包含了錨框位置信息。
        out_classes - tensor類型,維度爲(None,),錨框的預測的分類索引。
    """
    #圖像預處理
    image, image_data = yolo_utils.preprocess_image("images/" + image_file, model_image_size = (608, 608))

    #運行會話並在feed_dict中選擇正確的佔位符.
    out_scores, out_boxes, out_classes = sess.run([scores, boxes, classes], feed_dict = {yolo_model.input:image_data, K.learning_phase(): 0})

    #打印預測信息
    if is_show_info:
        print("在" + str(image_file) + "中找到了" + str(len(out_boxes)) + "個錨框。")

    #指定要繪製的邊界框的顏色
    colors = yolo_utils.generate_colors(class_names)

    #在圖中繪製邊界框
    yolo_utils.draw_boxes(image, out_scores, out_boxes, out_classes, class_names, colors)

    #保存已經繪製了邊界框的圖
    image.save(os.path.join("out", image_file), quality=100)

    #打印出已經繪製了邊界框的圖
    if is_plot:
        output_image = scipy.misc.imread(os.path.join("out", image_file))
        plt.imshow(output_image)

    return out_scores, out_boxes, out_classes

for i in range(1,120):

    #計算需要在前面填充幾個0
    num_fill = int( len("0000") - len(str(1))) + 1
    #對索引進行填充
    filename = str(i).zfill(num_fill) + ".jpg"

    print("當前文件:" + str(filename))
    #開始繪製,不打印信息,不繪製圖
    out_scores, out_boxes, out_classes = predict(sess, filename,is_show_info=False,is_plot=False)


print("繪製完成!")

注:參考網址:https://blog.csdn.net/u013733326/article/details/80341740

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章