簡體   English   中英

為Caffe2創建映像LMDB

[英]Creating an image LMDB for Caffe2

在原始的Caffe框架中, caffe/build/tools下有一個名為convert_imageset的可執行文件,該文件包含JPEG圖像目錄和帶有每個圖像標簽的文本文件,並輸出可以饋送到Caffe模型進行訓練的LMDB。 ,測試等。

使用Caffe2網站上此MNIST教程中AddInput()函數將原始JPEG圖像和標簽轉換為Caffe2可以攝取的AddInput()的最佳方法是什么?

根據我的研究,您不能簡單地使用此工具創建LMDB文件並提供Caffe2模型。

該教程腳本僅下載兩個LMDB( mnist-train-nchw-lmdbmnist-test-nchw-lmdb )並將它們傳遞給AddInput() ,但沒有提供有關如何創建LMDB的見解。

有一個名為make_image_db.cc的二進制make_image_db.cc ,它完全可以完成您所描述的事情。 它位於caffe2/build/bin/make_image_db

// This script converts an image dataset to a database.
//
// caffe2::FLAGS_input_folder is the root folder that holds all the images
//
// caffe2::FLAGS_list_file is the path to a file containing a list of files
// and their labels, as follows:
//
//   subfolder1/file1.JPEG 7
//   subfolder1/file2.JPEG 7
//   subfolder2/file1.JPEG 8
//   ...

https://github.com/caffe2/caffe2/issues/1755中所述,您可以通過以下方式使用二進制文件(也使用較少的參數):

caffe2/build/bin/make_image_db -color -db lmdb -input_folder ./some_input_folder
-list_file ./labels_file -num_threads 10 -output_db_name ./some_output_folder -raw -scale 256 -shuffle

有關如何創建和讀取lmdb數據庫(用於隨機圖像)的完整Caffe2示例,可以在官方github存儲庫中找到,並且可以用作適應您自己的圖像的框架https://github.com/caffe2/caffe2 /blob/master/caffe2/python/examples/lmdb_create_example.py 由於尚未使用此方法,因此我將簡單復制該示例。 為了創建數據庫,可以使用:

import argparse
import numpy as np

import lmdb
from caffe2.proto import caffe2_pb2
from caffe2.python import workspace, model_helper

def create_db(output_file):
    print(">>> Write database...")
    LMDB_MAP_SIZE = 1 << 40   # MODIFY
    env = lmdb.open(output_file, map_size=LMDB_MAP_SIZE)

    checksum = 0
    with env.begin(write=True) as txn:
        for j in range(0, 128):
            # MODIFY: add your own data reader / creator
            label = j % 10
            width = 64
            height = 32

            img_data = np.random.rand(3, width, height)
            # ...

            # Create TensorProtos
            tensor_protos = caffe2_pb2.TensorProtos()
            img_tensor = tensor_protos.protos.add()
            img_tensor.dims.extend(img_data.shape)
            img_tensor.data_type = 1

            flatten_img = img_data.reshape(np.prod(img_data.shape))
            img_tensor.float_data.extend(flatten_img)

            label_tensor = tensor_protos.protos.add()
            label_tensor.data_type = 2
            label_tensor.int32_data.append(label)
            txn.put(
                '{}'.format(j).encode('ascii'),
                tensor_protos.SerializeToString()
            )

            checksum += np.sum(img_data) * label
            if (j % 16 == 0):
                print("Inserted {} rows".format(j))

    print("Checksum/write: {}".format(int(checksum)))
    return checksum

然后可以通過以下方式加載數據庫:

def read_db_with_caffe2(db_file, expected_checksum):
    print(">>> Read database...")
    model = model_helper.ModelHelper(name="lmdbtest")
    batch_size = 32
    data, label = model.TensorProtosDBInput(
        [], ["data", "label"], batch_size=batch_size,
        db=db_file, db_type="lmdb")

    checksum = 0

    workspace.RunNetOnce(model.param_init_net)
    workspace.CreateNet(model.net)

    for _ in range(0, 4):
        workspace.RunNet(model.net.Proto().name)

        img_datas = workspace.FetchBlob("data")
        labels = workspace.FetchBlob("label")
        for j in range(batch_size):
            checksum += np.sum(img_datas[j, :]) * labels[j]

    print("Checksum/read: {}".format(int(checksum)))
    assert np.abs(expected_checksum - checksum < 0.1), \
        "Read/write checksums dont match"

最后但同樣重要的是,還有一個有關如何創建minidb數據庫的教程: https : //github.com/caffe2/caffe2/blob/master/caffe2/python/tutorials/create_your_own_dataset.ipynb 為此,可以使用以下功能:

def write_db(db_type, db_name, features, labels):
    db = core.C.create_db(db_type, db_name, core.C.Mode.write)
    transaction = db.new_transaction()
    for i in range(features.shape[0]):
        feature_and_label = caffe2_pb2.TensorProtos()
        feature_and_label.protos.extend([
            utils.NumpyArrayToCaffe2Tensor(features[i]),
            utils.NumpyArrayToCaffe2Tensor(labels[i])])
        transaction.put(
            'train_%03d'.format(i),
            feature_and_label.SerializeToString())
    # Close the transaction, and then close the db.
    del transaction
    del db

特征將是一個張量,包含您的圖像作為numpy數組。 標簽是要素的相應真實標簽。 然后,您只需將函數調用為

write_db("minidb", "train_images.minidb", train_features, train_labels)

最后,您可以通過以下方式從數據庫加載圖像:

net_proto = core.Net("example_reader")
dbreader = net_proto.CreateDB([], "dbreader", db="train_images.minidb", db_type="minidb")
net_proto.TensorProtosDBInput([dbreader], ["X", "Y"], batch_size=16)

用於在lmbd中創建數據庫:創建火車數據文件夾創建包含文件名標簽的train.txt文件創建驗證數據文件夾創建包含文件名和標簽的val.txt文件

編輯這個文件

gedit examples/imagenet/create_imagenet.sh

EXAMPLE= path to where *.lmbd folder wil be stored
DATA= path where val.txt and train.txt is present
TOOLS=build/tools

TRAIN_DATA_ROOT=test/make_caffe_data/train/ # path to trainfiles
VAL_DATA_ROOT=test/make_caffe_data/val/ # path to test_files

設置RESIZE=true可將圖像調整為256x256。 如果圖像已經使用其他工具調整大小,則保留為false RESIZE=true

./examples/imagenet/create_imagenet.sh

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM