1. 程式人生 > >caffe-將圖片轉化為siamese網路需要的資料庫格式

caffe-將圖片轉化為siamese網路需要的資料庫格式

// This program converts a set of gray images to a leveldb by storing them
// as Datum proto buffers.
// Usage:
//   convert_imageset [FLAGS] ROOTFOLDER/ LISTFILE DB_NAME
//
// where ROOTFOLDER is the root folder that holds all the images, and LISTFILE
// should be a list of files as well as their labels, in the format as
//   subfolder1/file1.JPEG 7
//   ....

#include <algorithm>
#include <fstream>  // NOLINT(readability/streams)
#include <string>
#include <utility>
#include <vector>

#include "boost/scoped_ptr.hpp"
#include "gflags/gflags.h"
#include "glog/logging.h"
#include "leveldb\db.h"

#include "caffe/proto/caffe.pb.h"
#include "caffe/util/io.hpp"
#include "caffe/util/rng.hpp"

#include "opencv2\opencv.hpp"

using namespace caffe;  // NOLINT(build/namespaces)
using std::pair;
using boost::scoped_ptr;

DEFINE_bool(gray, false,
    "When this option is on, treat images as grayscale ones");
DEFINE_bool(shuffle, false,
    "Randomly shuffle the order of images and their labels");
DEFINE_string(backend, "lmdb",
    "The backend {lmdb, leveldb} for storing the result");
DEFINE_int32(resize_width, 0, "Width images are resized to");
DEFINE_int32(resize_height, 0, "Height images are resized to");
DEFINE_bool(check_size, false,
    "When this option is on, check that all the datum have the same size");
DEFINE_bool(encoded, false,
    "When this option is on, the encoded image will be save in datum");
DEFINE_string(encode_type, "",
    "Optional: What type should we encode the image as ('png','jpg',...).");


static bool ReadImageToMemory(const string& FileName, const int Height,
                              const int Width, char *Pixels)
{
    // read image
    cv::Mat OriginImage = cv::imread(FileName, cv::IMREAD_GRAYSCALE);
    CHECK(OriginImage.data) << "Failed to read the image.\n";


    // resize the image
    cv::Mat ResizeImage;
    cv::resize(OriginImage, ResizeImage, cv::Size(Width, Height));
    CHECK(ResizeImage.rows == Height) << "The heighs of Image is no equal to the input height.\n";
    CHECK(ResizeImage.cols == Width) << "The width of Image is no equal to the input width.\n";
    CHECK(ResizeImage.channels() == 1) << "The channel of Image is no equal to one.\n";

    LOG(INFO) << "The height of image is " << ResizeImage.rows << "\n";
    LOG(INFO) << "The width of image is " << ResizeImage.cols << "\n";
    LOG(INFO) << "The channels of image is " << ResizeImage.channels() << "\n";

    // copy the image data to Pixels
    for (int HeightIndex = 0; HeightIndex < Height; ++HeightIndex)
    {
        const uchar* ptr = ResizeImage.ptr<uchar>(HeightIndex);
        int img_index = 0;
        for (int WidthIndex = 0; WidthIndex < Width; ++WidthIndex)
        {
            for (int ChannelIndex = 0; ChannelIndex < ResizeImage.channels(); ++ChannelIndex)
            {
                int datum_index = (ChannelIndex * Height + HeightIndex) * Width + WidthIndex;
                *(Pixels + datum_index) = static_cast<char>(ptr[img_index++]);
            }
        }
    }

    return true;
}


int main(int argc, char** argv)
{
    //::google::InitGoogleLogging(argv[0]);

#ifndef GFLAGS_GFLAGS_H_
    namespace gflags = google;
#endif

    gflags::SetUsageMessage("Convert a set of grey images to the leveldb\n"
        "format used as input for Caffe.\n"
        "Usage:\n"
        "    convert_imageset [FLAGS] ROOTFOLDER/ LISTFILE DB_NAME\n");
    caffe::GlobalInit(&argc, &argv);

    // 輸入引數不足時報錯
    if (argc < 4)
    {
        gflags::ShowUsageWithFlagsRestrict(argv[0], "tools/convert_imageset");
        return 1;
    }


    // 讀取影象名字和標籤
    std::ifstream infile(argv[2]);
    std::vector<std::pair<std::string, int> > lines;
    std::string filename;
    int label;
    while (infile >> filename >> label)
    {
        lines.push_back(std::make_pair(filename, label));
    }

    // 打亂圖片順序
    if (FLAGS_shuffle)
    {
        // randomly shuffle data
        LOG(INFO) << "Shuffling data";
        shuffle(lines.begin(), lines.end());
    }
    LOG(INFO) << "A total of " << lines.size() << " images.";



    // 設定影象的高度和寬度
    int resize_height = std::max<int>(0, FLAGS_resize_height);
    int resize_width = std::max<int>(0, FLAGS_resize_width);


    // 開啟資料庫
    // Open leveldb
    leveldb::DB* db;
    leveldb::Options options;
    options.create_if_missing = true;
    options.error_if_exists = true;
    leveldb::Status status = leveldb::DB::Open(
        options, argv[3], &db);
    CHECK(status.ok()) << "Failed to open leveldb " << argv[3]
        << ". Is it already existing?";


    // 儲存到leveldb
    // Storing to leveldb
    std::string root_folder(argv[1]);
    char* Pixels = new char[2 * resize_height * resize_width];
    const int kMaxKeyLength = 10;
    char key[kMaxKeyLength];
    std::string value;

    caffe::Datum datum;
    datum.set_channels(2);  // one channel for each image in the pair
    datum.set_height(resize_height);
    datum.set_width(resize_width);

    //
    for (int LineIndex = 0; LineIndex < lines.size(); LineIndex++)
    {
        int PairIndex = caffe::caffe_rng_rand() % lines.size();

        char* FirstImagePixel = Pixels;
        ReadImageToMemory(root_folder + lines[LineIndex].first, resize_height, resize_width, FirstImagePixel);

        char *SecondImagePixel = Pixels + resize_width * resize_height;
        ReadImageToMemory(root_folder + lines[PairIndex].first, resize_height, resize_width, SecondImagePixel);

        // set image pair data
        datum.set_data(Pixels, 2 * resize_height * resize_width);

        // set label
        if (lines[LineIndex].second == lines[PairIndex].second)
        {
            datum.set_label(1);
        }
        else
        {
            datum.set_label(0);
        }

        // serialize datum to string
        datum.SerializeToString(&value);
        sprintf_s(key, kMaxKeyLength, "%08d", LineIndex);

        db->Put(leveldb::WriteOptions(), std::string(key), value);
    }

    delete db;
    delete[] Pixels;

    return 0;
}


相關推薦

caffe-圖片化為siamese網路需要資料庫格式

// This program converts a set of gray images to a leveldb by storing them // as Datum proto buffers. // Usage: // convert_imageset [FLAGS] ROOTFOLDER/ L

CAFFE圖片化為lmdb格式指令碼【直接執行版】(內含生成train.txt和test.txt)

標籤: caffe 深度學習 作者:賈金讓 一.指令碼實現的功能 1.將訓練資料集轉化為lmdb格式; 2.將測試資料集轉化為lmdb格式; 3.生成mean.binaryproto檔案。 二.原理簡述 對於使用caffe的人來說,預處

java圖片化為base64和base64轉化為圖片編碼並儲存在本地

直接上程式碼public class Base64Convert {    /**     * @Description: 圖片轉化成base64字串     * @param:    path     * @Return:     */    public static S

CAD化為JPG圖片簡單的方法步驟

  想知道將CAD轉化為JPG圖片簡單的方法步驟今天就來詳情介紹給你們,相信對你們會有用處的,無需下載直接線上轉換,你們是不是聽完很心動呢?迫不及待的想知道究竟如何操作呢?來來來,學習CAD製圖的寶寶們可要認真看下去了這對你們的以後工作會帶來很多方便的,一起接著看下去吧!      CAD轉JPG h

image圖片化為Base64字串

base64工具類:/** * Base64 工具類 */public class Base64Util {    private static final char last2byte = (char) Integer.parseInt("00000011", 2);   

C#照片或圖片化為byte[]存入資料庫,從資料庫中讀照片

publicstaticbyte[] GetBytesByImagePath(string strFile) {byte[] photo_byte =null;using (FileStream fs =new FileStream(strFile, FileMode.Open, FileAcc

php把網路圖片化為base64格式,解決html2canvas圖片跨域問題

一、前言       最近在用html2canvas做網頁截圖功能。這個開源庫使用很簡單,程式碼也很方便,但難點在於跨域問題。比如說,我的一個頁面中有圖片也有文字,圖片是來自於圖片伺服器的網路圖片。此時我們要生成截圖的話,需要有許可權來操作網路圖片,這就出現了

MySQL化為mysqli

har exit etc 語句 mit mman ray 大神 eal <?php/** * Created by PhpStorm. * User: 大神 * Date: 2017/7/24 * Time: 11:29 */header(‘content-type

memo化為JPG輸出,使用Memo1.PaintTo(Bitmap.Canvas)

ali send sig .text ctr ace rap reat bit unit unit1; interface uses Windows, Messages, SysUtils, Graphics, Controls, Forms, StdCtrls,

php http化為https 小程序部署上線

展示 是否 程序 gateway 成員 進入 跟著 狀態 但是 哇,,,,,我都弄了好久呢!!!其實非常非常的簡單呢!!!! 初次接觸,迷茫之中,後來突然地一次嘗試就ok了,,,可以訪問https了,,,,開始報了很多錯,,例如502 Bad Gateway,,,404 N

php 圖片成base64

function gif php pos 內置 獲取 str 路徑 files PHP對Base64的支持非常好,有內置的base64_encode與base64_decode負責圖片的Base64編碼與解碼。 編碼上,只要將圖片流讀取到,而後使用base6

Java 如何String化為Int

tac string ger mat tst valueof eof 轉化 form 在 Java 中要將 String 類型轉化為 int 類型時,需要使用 Integer 類中的 parseInt() 方法或者 valueOf() 方法進行轉換. 例1: 1

SqlDataReader 數據集化為datatbale ,在datatable 化為iList

type HERE tostring exception () tar del from helper 1 public IList GetModelList(string tablename, string where) 2 {

matlab實現一次性實現多個文件夾圖片化為.mat文件

img mage 標簽 rgb end 參考 strcmp microsoft rcm %這裏是主函數:命名為readImg.m; clc;clear; %---read_image; filepath = ‘G:\人臉重建\data\src_all\‘;%圖片路徑可以根

安卓手機怎麽圖片PDF方法

在一起 nag 簡單 頁面 新的 images mark ima sha 手機圖片太多查閱不是很方便,也很占手機的內存,這時我們何不試試將圖片轉換成PDF文件呢,我們將以內的照片放在一起然後轉換成一個PDF文件,這樣查閱起來就方便了不少。 準備工具:安卓手機先去軟件商店下載

javaExcel化為Html

view mas pub str ali alt inpu hashmap align   之前在做移動端頁面的時候,發現iphone不支持預覽excel文檔,於是將excel轉化為html元素然後查看其中的具體信息,在這裏整理下文檔,以便於記憶避免踩坑。   1. 引入相

react標籤屬性dangerouslySetInnerHTML字串化為html(動態渲染)

根據需求,前端頁面有時需要動態展示後端返回的程式碼,但是此時的程式碼是字串型別,直接展示,頁面顯示的只是字串,這時就用到了react標籤屬性dangerouslySetInnerHtml屬性; dangerouslySetInnerHtml用法: dangerouslySetInnerH

POIword化為html

參考資料 1.POI包依賴:https://poi.apache.org/components/index.html 2.包版本問題:https://bbs.csdn.net/topics/392208805 並沒有使用其中的3.9的版本,使用的為3.13 最開始使用的

有什麼圖片文字的方法

      有什麼將圖片轉文字的方法呢?圖片轉文字的問題工作中也是會時常出現的,那麼將圖片轉文字的方法都有什麼呢?下面我們就一起來看一下吧。       其實一般比較常用的方法也就有兩種,一種是通過用手打字進行轉換,一種便是通過藉助一些圖片文字

使用m2e工程化為maven工程後eclipse報Plugin execution not covered by l

分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow 也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!