2019年6月22日、リアルタイムの映像検出

良いモデルのダウンロードによるリアルタイム映像検出、
インポートnumpyのNP AS
インポートのOS
インポートsix.moves.urllib AS urllibは
インポートSYS
インポートtarファイル
のインポートtensorflow TF AS
インポートZIPファイル
のインポートmatplotlibの
インポートCV2

matplotlibのは、デフォルトではXウィンドウのバックエンドを選択します。

matplotlib.use( 'AGG')

コレクションからdefaultdictインポート
IOインポートたStringIOから
PLTとしてmatplotlibのインポートpyplotから
PILインポートイメージから
label_map_utilをインポートobject_detection.utilsから
vis_utilとしてvisualization_utilsをインポートobject_detection.utilsから

「」「
検出対象のビデオ
」「」

キャップ= cv2.VideoCapture(0)#カメラをオンにします

#####################ダウンロードモデル

どのようなモデルをダウンロードします。

MODEL_NAME = 'ssd_mobilenet_v1_coco_2017_11_17'
'.tar.gzを' MODEL_FILE = MODEL_NAME +
DOWNLOAD_BASE = ' http://download.tensorflow.org/models/object_detection/ '

凍結された検出グラフへのパス。これは、オブジェクトの検出に使用される実際のモデルです。

PATH_TO_CKPT = 'C:\ユーザーは深い学習管理\デスクトップ\ \ \ ssd_mobilenet_v1_coco_2017_11_17 / frozen_inference_graph.pb'

各ボックスの正しいラベルを追加するために使用される文字列のリスト。

PATH_TO_LABELS = os.path.join( 'E:\アナコンダ\ ENVS \ tensorflow-OpenCVの\モデル\研究\ object_detectionの\データ'、 'mscoco_label_map.pbtxt')

NUM_CLASSES = 90

まだダウンロードしていない場合はモデルをダウンロード

ない場合os.path.existsは(PATH_TO_CKPT):
プリント( '(これは、5分以上かかる場合があります)...モデルのダウンロード')
オープナー= urllib.request.URLopener()
opener.retrieve(DOWNLOAD_BASE + MODEL_FILE、MODEL_FILE)
プリント( '抽出... ')
tar_file = tarfile.open(MODEL_FILE)
tar_file.getmembers()内のファイルのために:
FILE_NAME = os.path.basename(file.name
の場合':file_nameの中frozen_inference_graph.pb'
tar_file.extract(ファイル、os.getcwd ())
他:
プリント( 'モデルは、すでにダウンロード。')

メモリに(冷凍)Tensorflowモデルをロードし#####################。
印刷( '読み込んでモデル...')
detection_graph = tf.Graph()

:detection_graph.as_default()と
od_graph_def = tf.GraphDef()
tf.gfile.GFileと(PATH_TO_CKPT、 'RB')FIDとして:
serialized_graph = fid.read()
od_graph_def.ParseFromString(serialized_graph)
tf.import_graph_def(od_graph_def、名前= '')

##################### Loading label map

印刷( '読み込んでラベルマップ...')
label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
カテゴリ= label_map_util.convert_label_map_to_categories(label_map、max_num_classes = NUM_CLASSES、
use_display_name =真)
category_index = label_map_util.create_category_index(カテゴリ)

#####################ヘルパーコード
デフload_image_into_numpy_array(画像):
(im_width、im_height)= image.sizeの
戻りnp.array(image.getdata())。 (再構築
(im_height、im_width、3))。astype(np.uint8)

#####################検出###########

印刷( '検出...')
detection_graph.as_defaultと():
SESのようtf.Session(グラフ= detection_graph)と:

    # print(TEST_IMAGE_PATH)
    # image = Image.open(TEST_IMAGE_PATH)
    # image_np = load_image_into_numpy_array(image)
    while True:
        ret, image_np = cap.read()  # 从摄像头中获取每一帧图像
        image_np_expanded = np.expand_dims(image_np, axis=0)
        image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')
        boxes = detection_graph.get_tensor_by_name('detection_boxes:0')
        scores = detection_graph.get_tensor_by_name('detection_scores:0')
        classes = detection_graph.get_tensor_by_name('detection_classes:0')
        num_detections = detection_graph.get_tensor_by_name('num_detections:0')
        # Actual detection.
        (boxes, scores, classes, num_detections) = sess.run(
            [boxes, scores, classes, num_detections],
            feed_dict={image_tensor: image_np_expanded})
        # Print the results of a detection.
        print(scores)
        print(classes)
        print(category_index)
        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.imshow('object detection', cv2.resize(image_np, (800, 600)))
        # cv2.waitKey(0)
        if cv2.waitKey(25) & 0xFF == ord('q'):
            cv2.destroyAllWindows()
            break

おすすめ

転載: blog.csdn.net/weixin_43732462/article/details/93330959