MoUT.cpp

Source for Museum of Useful Things (random utility header) - Abe S., 2011-03-28 07:18 pm

Download (2.1 kB)

 
1
/*
2
 * MoUT.cpp
3
 *
4
 *  Created on: Mar 25, 2011
5
 *      Author: ams
6
 *
7
 *  A Museum of Useful Things to work with images using OpenCV. I ended up
8
 *  having to the same file conversions, etc. over and over again.
9
 *
10
 */
11
#include "MoUT.hpp"
12
13
using namespace std;
14
using namespace cv;
15
16
//Unsafe way to get pixel values from http://stackoverflow.com/questions/4747920/opencv-rgb-value-for-cvpoint-in-cvmat
17
RGB& GetRGB(cv::Mat &mat, int x, int y)
18
{
19
  assert((mat.step/mat.cols) == sizeof(RGB));
20
  RGB *data = (RGB*)mat.data;
21
  data += y * mat.cols + x;
22
  return *data;
23
}
24
25
/* Load an image, downsample, and convert to a neural net training vector */
26
string img2NNVect(string imgPath)
27
{
28
        // For downsampling
29
        vector<cv::Mat> smaller;
30
        int levels = 4;
31
32
        //For number to string conversions
33
        char buffer[45];
34
35
        // load file and set up new image
36
        // last parameter forces loading as RGB color
37
        cv::Mat original = imread(imgPath, 1);
38
        cv::buildPyramid(original, smaller, levels);
39
40
        //convert the smallest version into a row
41
        string imgRow = "";
42
        cv::Mat tiny = smaller[levels-1];
43
        for(int xx = 0; xx < tiny.cols; xx++)
44
        {
45
                for(int yy = 0; yy < tiny.rows; yy++)
46
                {
47
                        RGB pixel = GetRGB(tiny, xx, yy);
48
                        sprintf(buffer, "%d", pixel.r);
49
                        imgRow += buffer;
50
                        imgRow += " ";
51
                        sprintf(buffer, "%d", pixel.g);
52
                        imgRow += buffer;
53
                        imgRow += " ";
54
                        sprintf(buffer, "%d", pixel.b);
55
                        imgRow += buffer;
56
                        imgRow += " ";
57
                }
58
        }
59
}
60
61
void Tokenize(const string& str, vector<string>& tokens, const string& delimiters)
62
{
63
    // Skip delimiters at beginning.
64
    string::size_type lastPos = str.find_first_not_of(delimiters, 0);
65
    // Find first "non-delimiter".
66
    string::size_type pos     = str.find_first_of(delimiters, lastPos);
67
68
    while (string::npos != pos || string::npos != lastPos)
69
    {
70
        // Found a token, add it to the vector.
71
        tokens.push_back(str.substr(lastPos, pos - lastPos));
72
        // Skip delimiters.  Note the "not_of"
73
        lastPos = str.find_first_not_of(delimiters, pos);
74
        // Find next "non-delimiter"
75
        pos = str.find_first_of(delimiters, lastPos);
76
    }
77
}