run_lpo.py

컴퓨터비전/영상처리 2015. 9. 29. 21:02
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
"""
Make sure you have LPO_DIR/src in your python path
"""
 
import lpo
from lpo import *
from util import *
import cv2
import numpy as np
import os
from pylab import *
 
# ------------- filenames -----------------
dataset = "50Salads"
filename = "rgb-01-1.avi"
# ------------- Folder names -----------------
# url_files = os.path.expanduser("~/Desktop/tmp2/".format(dataset))
url_files = os.path.expanduser("~/Data/{}/raw/rgb/".format(dataset))
url_img_save = os.path.expanduser("~/Data/{}/viz/lpo/".format(dataset))
url_bbox_save = os.path.expanduser("~/Data/{}/features/lpo/S1_Cheese_C1/".format(dataset))
# I can only get the library to read images from disk (instead of from video stream)
# So save video file to temporary image and then load...
tmp_filename = os.path.expanduser("~/Desktop/tmp.png")
# ------------- User params -----------------
save_file = [False, True][0]
n_superpixels = 200
rez = (854480)
# I threshold out boxes that are too big or too small
min_box_len = 50
max_box_len = 250
# This list is all available overlap scores.
overlap_score = [.01, .02, .03, .05, .1, .2][-1]
# ---------------------------------------------
 
# Load the ensemble
prop = proposals.LPO()
dir_lpo = os.path.dirname(lpo.__file__).strip("src")
prop.load(dir_lpo+"/models/lpo_VOC_{}.dat".format(overlap_score))
detector = getDetector('mssf')
 
# Check that the save folder exists
if not os.path.exists(url_img_save):
    os.mkdir(url_img_save)
 
vid = cv2.VideoCapture(os.path.expanduser(url_files+filename))
 
# Evaluate on the test set
i=0
while 1:
    ret, im_cv = vid.read()
    if not ret:
        break
    # im_cv = cv2.resize(im, rez)
 
    cv2.imwrite(tmp_filename, im_cv)
    im = imgproc.imread(tmp_filename)
 
    # Extract object proposals from oversegmented regions
    over_segs = segmentation.generateGeodesicKMeans( detector, [im], n_superpixels)
    props = prop.propose(over_segs)[0]
    segs = props[0].s
 
    # Display bounding boxes
    boxes = props[0].toBoxes()
    for b in boxes:
        x1,y1,x2,y2 = b
        if (min_box_len < (x2 - x1) < max_box_len) and \
            (min_box_len < (y2 - y1) < max_box_len):
            cv2.rectangle(im_cv,(x1,y1),(x2,y2),(0,255,0),1)
    cv2.imshow("im", im_cv)
    cv2.waitKey(30)
 
    # # Overlay superpixels onto image to create heatmap
    # im_ = np.zeros_like(im_cv[:,:,2])*1.
    # for o in props[0].p:
    #     for spx in np.nonzero(o)[0]:
    #         im_[segs==spx] += 1
    #
    #     # im_ += (segs == np.nonzero(o)[0][:,None,None]).sum(0)
    #
    # cv2.imshow("heatmap", im_/im_.max())
    # cv2.waitKey(30)
 
    # Save image and bounding box/segmentation to file
    if save_file:
        base_filename = str(i*framerate)+".jpg"
        cv2.imwrite(url_img_save+base_filename, im_cv)
        saveProposalsHDF5( props, url_bbox_save+base_filename+'.hf5', True, True )
 
    i+=1
cs


ApplyColorMap for pseudocoloring

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// ApplyColorMap for pseudocoloring
// using OpenCV 3.0 Version
 
#include <cv.hpp>
 
using namespace cv;
using namespace std;
 
string colormap_name(int id)
{
    switch (id){
    case COLORMAP_AUTUMN:
        return "COLORMAP_AUTUMN";
    case COLORMAP_BONE:
        return "COLORMAP_BONE";
    case COLORMAP_JET:
        return "COLORMAP_JET";
    case COLORMAP_WINTER:
        return "COLORMAP_WINTER";
    case COLORMAP_RAINBOW:
        return "COLORMAP_RAINBOW";
    case COLORMAP_OCEAN:
        return "COLORMAP_OCEAN";
    case COLORMAP_SUMMER:
        return "COLORMAP_SUMMER";
    case COLORMAP_SPRING:
        return "COLORMAP_SPRING";
    case COLORMAP_COOL:
        return "COLORMAP_COOL";
    case COLORMAP_HSV:
        return "COLORMAP_HSV";
    case COLORMAP_PINK:
        return "COLORMAP_PINK";
    case COLORMAP_HOT:
        return "COLORMAP_HOT";
    }
 
    return "NONE";
}
 
int main()
{
    Mat im = imread("img/pluto.jpg", IMREAD_GRAYSCALE);
 
    Mat im_out = Mat::zeros(600800, CV_8UC3);
 
    for (int i = 0; i < 4; i++){
        for (int j = 0; j < 3; j++){
            int k = i + j * 4;
            Mat im_color = im_out(Rect(i * 200, j * 200200200));
            applyColorMap(im, im_color, k);
            putText(im_color, colormap_name(k), Point(30180), 
                CV_FONT_HERSHEY_DUPLEX, 0.5, Scalar::all(255), 1, CV_AA);
        }
    }
 
    imshow("Pseudo Colored", im_out);
    imwrite("img/Pseudo COlored.jpg", im_out);
    waitKey(0);
    
    return 0;
}
cs





Non-Photorealistic Rendering

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// Non-Photorealistic Rendering using OpenCV
// using OpenCV 3.0 Version
 
#include <cv.hpp>
 
using namespace std;
using namespace cv;
 
int main()
{
    Mat im = imread("img/cow.jpg");
    Mat imout, imout_gray;
 
    // Edge preserving filter with two different flags;
    edgePreservingFilter(im, imout, RECURS_FILTER);
    imwrite("img/edge-preserving-recursive-filter.jpg", imout);
 
    edgePreservingFilter(im, imout, NORMCONV_FILTER);
    imwrite("img/edge-preserving-normlized-convolution-filter.jpg", imout);
 
    // Detail enhance filter
    detailEnhance(im, imout);
    imwrite("img/detail-enhance.jpg", imout);
 
    // Pencil sketch filter
    pencilSketch(im, imout_gray, imout);
    imwrite("img/pencil-sketch.jpg", imout_gray);
 
    // stylization filter
    stylization(im, imout);
    imwrite("img/stylization.jpg", imout);
}
cs


Domain Transform for Edge-aware Filtering












OpenCV SeamlessCloning

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// Examples : seamlessClone.cpp
// Using OpenCV 3.0 version
 
#include <cv.hpp>
 
using namespace std;
using namespace cv;
 
int main()
{
    Mat src = imread("img/iloveyouticket.jpg");
    Mat dst = imread("img/wood-texture.jpg");
 
    // create an all white mask
    Mat src_mask = 255 * Mat::ones(src.rows, src.cols, src.depth());
 
    // The location of the center of the src in the dst
    Point center(dst.cols / 2, dst.rows / 2 );
 
    // Seamlessly Clone src into dst and put the result in output
    Mat normal_clone, mixed_clone;
 
    seamlessClone(src, dst, src_mask, center, normal_clone, NORMAL_CLONE);
    seamlessClone(src, dst, src_mask, center, mixed_clone, MIXED_CLONE);
 
    namedWindow("normal_clone");
    imshow("normal_clone", normal_clone);
    namedWindow("mixed_clone");
    imshow("mixed_clone", mixed_clone);
 
    waitKey(0);
 
    return 0;
}
cs





입력 이미지 예1)


  <그림 1 source image>


                  <그림 2 dst image>


                <그림 3 normal clone


               <그림 4 mixed clone




입력 이미지 예2)

         <그림 5 source image


                          <그림 6 dst image


normal clone

                         <그림 7 normal clone


mixed clone

                          <그림 8 mixed clone

High Dynamic Range Imaging(HDR)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// Reference : http://docs.opencv.org/3.0.0/d3/db7/tutorial_hdr_imaging.html
// Examples : High Dynamic Range Imaging(HDR)
 
#include <cv.hpp>
#include <iostream>
#include <fstream>
 
using namespace std;
using namespace cv;
 
void loadExposureSqe(String path, vector<Mat>& images, vector<float>&times)
{
    path = path + std::string("/");
    ifstream list_file((path + "list.txt").c_str());
 
    string name;
    float val;
 
    while (list_file >> name >> val) {
        Mat img = imread(path + name);
        images.push_back(img);
        times.push_back(1 / val);
    }
 
    list_file.close();
}
 
int main()
{
    vector<Mat> images;
    vector<float> times;
    loadExposureSqe("hdr/exposures", images, times);
 
    Mat response;
    Ptr<CalibrateDebevec>  calibrate = createCalibrateDebevec();
    calibrate->process(images, response, times);
 
    Mat hdr;
    Ptr<MergeDebevec> merge_debevec = createMergeDebevec();
    merge_debevec->process(images, hdr, times, response);
 
    Mat ldr;
    Ptr<TonemapDurand> tonemap = createTonemapDurand(2.2f);
    tonemap->process(hdr, ldr);
 
    Mat fusion;
    Ptr<MergeMertens> merge_mertens = createMergeMertens();
    merge_mertens->process(images, fusion);
 
    imwrite("hdr/fusion.png", fusion * 255);
    imwrite("hdr/ldr.png", ldr * 255);
    imwrite("hdr/hdr.hdr", hdr);
    
    return 0;
}
cs






 

    hdr.zip





OpenCV Principal Component Analysis(PCA)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#include <cv.hpp>
#include <iostream>
using namespace std;
using namespace cv;
 
void drawAxis(Mat &img, Point p, Point q, Scalar colour, const float scale = 0.2)
{
    double angle;
    double hypotenuse;
    angle = atan2((double)p.y - q.y, (double)p.x - q.x);
    hypotenuse = sqrt((double)(p.y - q.y) * (p.y - q.y) + (p.x - q.x) * (p.x - q.x));
 
    // Here we lengthen the arrow by a factor of scale
    q.x = (int)(p.x - scale * hypotenuse * cos(angle));
    q.y = (int)(p.y - scale * hypotenuse * sin(angle));
    line(img, p, q, colour, 1, CV_AA);
 
    // create the arrow hooks
    p.x = (int)(q.x + 9 * cos(angle + CV_PI / 4));
    p.y = (int)(q.y + 9 * sin(angle + CV_PI / 4));
    line(img, p, q, colour, 1, CV_AA);
    
    p.x = (int)(q.x + 9 * cos(angle - CV_PI / 4));
    p.y = (int)(q.y + 9 * sin(angle - CV_PI / 4));
    line(img, p, q, colour, 1, CV_AA);
}
 
double getOrientation(const vector<Point> &pts, Mat &img)
{
    // construct a buffer used by the pca analysis
    int sz = static_cast<int>(pts.size());
    Mat data_pts = Mat(sz, 2, CV_64FC1);
 
    for (int i = 0; i < data_pts.rows; ++i)
    {
        data_pts.at<double>(i, 0= pts[i].x;
        data_pts.at<double>(i, 1= pts[i].y;
    }
 
    //Perform PCA analysis
    PCA pca_analysis(data_pts, Mat(), CV_PCA_DATA_AS_ROW);
 
    //Store the center of the object
    Point cntr = Point(static_cast<int>(pca_analysis.mean.at<double>(00)), 
        static_cast<int>(pca_analysis.mean.at<double>(01)));
 
    //Store and eigenvalues and eigenvectors
    vector<Point2d> eigen_vecs(2);
    vector<double> eigen_val(2);
 
    for (int i = 0; i < 2++i)
    {
        eigen_vecs[i] = Point2d(pca_analysis.eigenvectors.at<double>(i, 0),
            pca_analysis.eigenvectors.at<double>(i, 1));
 
        eigen_val[i] = pca_analysis.eigenvalues.at<double>(i, 0);
    }
 
    //Draw the principal components
    circle(img, cntr, 3, Scalar(2550255), 2);
    Point p1 = cntr + 0.02 * Point(static_cast<int>(eigen_vecs[0].x * eigen_val[0]), 
        static_cast<int>(eigen_vecs[0].y * eigen_val[0]));
    Point p2 = cntr - 0.02 * Point(static_cast<int>(eigen_vecs[1].x * eigen_val[1]), 
        static_cast<int>(eigen_vecs[1].y * eigen_val[1]));
    
    drawAxis(img, cntr, p1, Scalar(02550), 1);
    drawAxis(img, cntr, p2, Scalar(2552550), 5);
    
    // orientation in radins
    double angle = atan2(eigen_vecs[0].y, eigen_vecs[0].x);
 
    return angle;
}
 
int main()
{
    Mat src = imread("img/pca_test1.jpg");
 
    if (!src.data || src.empty())
    {
        cout << "can't not load image" << endl;
        return EXIT_FAILURE;
    }
 
    imshow("Src", src);
 
    //Convert Image to grayScale
    Mat gray;
    cvtColor(src, gray, COLOR_BGR2GRAY);
 
    // Convert image to Binary
    Mat bw;
    threshold(gray, bw, 50.255., CV_THRESH_BINARY || CV_THRESH_OTSU);
    
    // Find all the contours in the thresholded image
    vector<Vec4i> hierarchy;
    vector<vector<Point>> contours;
    findContours(bw, contours, hierarchy, CV_RETR_LIST, CV_CHAIN_APPROX_NONE);
 
    for (size_t i = 0; i < contours.size(); ++i)
    {
        // Calculate the area of each contour
        double area = contourArea(contours[i]);
 
        if (area < 1e2 || 1e5 < area)
            continue;
 
        drawContours(src, contours, static_cast<int>(i), Scalar(00255), 28, hierarchy, 0);
        getOrientation(contours[i], src);
    }
 
    imshow("output", src);
    
    waitKey(0);
    return 0;
}
cs





OpenCV Scene Change Detection(장면 전환 검출)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
// http://docs.opencv.org/3.0.0/d5/dc4/tutorial_video_input_psnr_ssim.html
// Base Examples : Video Input with OpenCV and similarity measurement
 
#include <cv.hpp>
#include <string>
#include <iostream>
 
using namespace std;
using namespace cv;
 
double getPSNR(const Mat& I1, const Mat& I2)
{
    Mat s1;
    absdiff(I1, I2, s1);       // |I1 - I2|
    s1.convertTo(s1, CV_32F);  // cannot make a square on 8 bits
    s1 = s1.mul(s1);           // |I1 - I2|^2
    Scalar s = sum(s1);        // sum elements per channel
    double sse = s.val[0+ s.val[1+ s.val[2]; // sum channels
 
    if (sse <= 1e-10// for small values return zero
        return 0;
    
    double mse = sse / (double)(I1.channels() * I1.total());
    double psnr = 10.0*log10((255 * 255/ mse);
    return psnr;
}
 
void merge(const Mat &m1, const Mat &m2, Mat &result)
{
    resize(result, result, Size(m1.cols + m2.cols, m1.rows));
    
    m1.copyTo(result(Rect(00, m1.cols, m1.rows)));
    m2.copyTo(result(Rect(m1.cols, 0, m2.cols, m2.rows)));
 
    putText(result, "Normal Video", cvPoint(3030),
        FONT_HERSHEY_COMPLEX_SMALL, 1.0, cvScalar(200200250), 1, CV_AA);
 
    putText(result, "Scene Change Detection", cvPoint(m1.cols + 3030),
        FONT_HERSHEY_COMPLEX_SMALL, 1.0, cvScalar(200200250), 1, CV_AA);
}
 
int main()
{
    stringstream conv;
    char c;
    int frameNum = -1// Frame counter
    double psnrV, CHANGE_DETECT_RATIO = 15.0;
    string videoPath = "video/Megamind.avi";
 
    VideoCapture cap(videoPath);
        
    // file open
    if (!cap.isOpened()) {
        cout << "Could not open video - " << videoPath << endl;
        return -1;
    }
    Size s = Size((int)cap.get(CAP_PROP_FRAME_WIDTH), (int)cap.get(CAP_PROP_FRAME_HEIGHT));
    Mat prevFrame, currFrame, changeFrame, result(s, CV_8UC3);
    
    namedWindow("Scene Change Detection");
    resizeWindow("Scene Change Detection", s.width * 2, s.height);
    
    while (1)
    {
        ++frameNum;
        cap >> currFrame;
 
        if (frameNum < 1) {
            prevFrame = currFrame.clone();
            changeFrame = currFrame.clone();
            continue;
        }
        
        if (currFrame.rows == 0 && currFrame.cols == 0)
            break;
 
        psnrV = getPSNR(prevFrame, currFrame);
        
        if (psnrV < CHANGE_DETECT_RATIO)
            changeFrame = currFrame.clone();
        
        merge(currFrame, changeFrame, result);
        imshow("Scene Change Detection", result);
 
        if (frameNum % 2 == 0)
            prevFrame = currFrame.clone();
 
        c = (char)waitKey(10);
        
        if (c == 27)
            break;
    }
 
    return 0;
}
cs




Image Segmentation with Distance Transform and Watershed Algorithm


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
#include <cv.hpp>
#include <iostream>
 
using namespace std;
using namespace cv;
 
int DELAY_CAPTION = 1500;
char window_name[] = "Watershed Demo";
Mat src;
 
int display_caption(char *caption, Mat input);
 
int main()
{
    src = imread("img/card2.png");
 
    if (!src.data)
        return -1;
        
    display_caption("source Image", src);
 
    for (int x = 0; x < src.rows; x++) {
        for (int y = 0; y < src.cols; y++) {
            if (src.at<Vec3b>(x, y) == Vec3b(255255255)) {
                src.at<Vec3b>(x, y)[0= 0;
                src.at<Vec3b>(x, y)[1= 0;
                src.at<Vec3b>(x, y)[2= 0;
            }
        }
    }
 
    Mat kernel = (Mat_<float>(3,3<< 111,
                                      1-81,
                                      111);
 
    Mat imgLaplacian;
    Mat sharp = src;
    filter2D(sharp, imgLaplacian, CV_32F, kernel);
    src.convertTo(sharp, CV_32F);
    Mat imgResult = sharp - imgLaplacian;
 
    imgResult.convertTo(imgResult, CV_8UC3);
    imgLaplacian.convertTo(imgLaplacian, CV_8UC3);
 
    display_caption("New Sharped Image", imgResult);
    display_caption("New Sharped Image Laplacian", imgLaplacian);
 
    src = imgResult;
 
    Mat bw;
    cvtColor(src, bw, CV_BGR2GRAY);
    threshold(bw, bw, 40255, CV_THRESH_BINARY | CV_THRESH_OTSU);
 
    Mat dist;
 
    // CV_DIST_L2 = Euclidean distance
    distanceTransform(bw, dist, CV_DIST_L2, 3);
 
    normalize(dist, dist, 01., NORM_MINMAX);
    display_caption("Distance Transform Image", dist);
 
    threshold(dist, dist, .41., CV_THRESH_BINARY);
 
    Mat kernel1 = Mat::ones(33, CV_8UC1);
    dilate(dist, dist, kernel1);
    display_caption("peaks point", dist);
 
    Mat dist_8U;
    dist.convertTo(dist_8U, CV_8U);
    
    vector<vector<Point>> contours;
    findContours(dist_8U, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);
 
    Mat markers = Mat::zeros(dist.size(), CV_32SC1);
 
    for (size_t i = 0; i < contours.size(); i++)
        drawContours(markers, contours, static_cast<int>(i), Scalar::all(static_cast<int>(i)+1));
 
    circle(markers, Point(55), 3, CV_RGB(255255255), -1);
    display_caption("Marker", markers * 10000);
 
    watershed(src, markers);
 
    Mat mark = Mat::zeros(markers.size(), CV_8UC1);
    markers.convertTo(mark, CV_8UC1);
    bitwise_not(mark, mark);
    
    display_caption("Markers_v2", mark);
 
    vector<Vec3b>colors;
 
    for (size_t i = 0; i < contours.size(); i++)
    {
        int b = theRNG().uniform(0255);
        int g = theRNG().uniform(0255);
        int r = theRNG().uniform(0255);
 
        colors.push_back(Vec3b((uchar)b, (uchar)g, (uchar)r));
    }
 
    Mat dst = Mat::zeros(markers.size(), CV_8UC3);
 
    for (int i = 0; i < markers.rows; i++)
    {
        for (int j = 0; j < markers.cols; j++)
        {
            int index = markers.at<int>(i, j);
            if (index > 0 && index <= static_cast<int>(contours.size()))
                dst.at<Vec3b>(i, j) = colors[index - 1];
            else
                dst.at<Vec3b>(i, j) = Vec3b(000);
        }
    }
 
    display_caption("Final", dst);
 
    waitKey(0); 
    
    return 0;
}
 
int display_caption(char *caption, Mat input)
{
    Mat dst;
    dst = Mat::zeros(input.size(), input.type());
    
    putText(dst, caption, Point(src.cols / 4, src.rows / 2), FONT_HERSHEY_COMPLEX, 1, Scalar(255255255));
 
    imshow(window_name, dst);
    int c = waitKey(DELAY_CAPTION);
 
    if (c >= 0)
        return -1;
 
    imshow(window_name, input);
    
    c = waitKey(DELAY_CAPTION);
 
    if (c >= 0)
        return -1;
    return 0;
}
 
cs

 




OpenCV Image Filtering

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
// Reference : http://docs.opencv.org/3.0.0/dc/dd3/tutorial_gausian_median_blur_bilateral_filter.html
// Examples : Smoothing Images
 
#include <iostream>
#include <cv.hpp>
#include <windows.h>
 
using namespace std;
using namespace cv;
 
int DELAY_CAPTION = 1500;
int DELAY_BLUR = 100;
int MAX_KERNEL_LENGTH = 31;
 
int display_caption(char *caption);
int display_dst(int delay);
char window_name[] = "Filter Demo 1";
 
Mat src, dst;
 
int main()
{
    namedWindow(window_name);
    
    Sleep(2000);
 
    src = imread("img/lena.bmp");
 
    if (display_caption("Original Image"!= 0)
        return 0;
 
    dst = src.clone();
    if (display_dst(DELAY_CAPTION) != 0)
        return 0;
    
    
    for (int i = 1; i < MAX_KERNEL_LENGTH; i = i + 2)
    {
        blur(src, dst, Size(i, i), Point(-1-1));
        if (display_dst(DELAY_BLUR) != 0)
            return 0;
 
        if (display_caption("Gaussian Blur"!= 0)
            return 0;
 
        for (int i = 1; i < MAX_KERNEL_LENGTH; i = i + 2)
        {
            GaussianBlur(src, dst, Size(i, i), 00);
            if (display_dst(DELAY_BLUR) != 0)
                return 0;
        }
 
        if (display_caption("Median Blur"!= 0)
            return 0;
 
        for (int i = 1; i < MAX_KERNEL_LENGTH; i = i + 2)
        {
            medianBlur(src, dst, i);
            if (display_dst(DELAY_BLUR) != 0)
                return 0;
        }
 
        if (display_caption("Bilateral Blur"!= 0)
            return 0;
        
        for (int i = 1; i < MAX_KERNEL_LENGTH; i = i + 2)
        {
            bilateralFilter(src, dst, i, i * 2, i / 2);
            if (display_dst(DELAY_BLUR) != 0)
                return 0;
        }
 
        display_caption("End");
 
        waitKey(0);
        return 0;
    }
}
 
int display_caption(char *caption)
{
    dst = Mat::zeros(src.size(), src.type());
    putText(dst, caption, Point(src.cols / 4, src.rows / 2), FONT_HERSHEY_COMPLEX, 1, Scalar(255255255));
 
    imshow(window_name, dst);
    int c = waitKey(DELAY_CAPTION);
    if (c >= 0)
        return -1;
    
    return 0;
}
 
int display_dst(int delay)
{
    imshow(window_name, dst);
    int c = waitKey(delay);
    if (c >= 0)
        return -1;
    
    return 0;
}
cs





CVPR 2015 컴퓨터 비전 및 패턴인식 워크샵

컴퓨터비전/영상처리 2015. 7. 4. 00:28

2015 컴퓨터 비전 및 패턴인식 워크샵이 15년 7월 3일 금요일에 숙명여대에서 젬마홀에서 개최되었습니다.


프로그램은 아래 일정과 같이 진행되었습니다.



전반적인 강의 내용은 자동주행 자동차와 관련된 컴퓨터비전 이론(3D reconstruction, face recognition, 

object tracking etc..)


을 기반으로 강의가 구성되었습니다.



각각의 강의 내용을 간략히 요약하자면 다음과 같습니다.



Tutorial 1. 현대모비스 신광근 박사


 전반적으로 자율주행 기술동향을 여러 나라의 자동차 회사를 기반으로 소개하며 overview해주셨습니다.


2005년, 스텐포드와 카네기 대학에서 자율주행로봇에 관한 연구를 진행하였고, 자동 주행 자동차가 등장하기 시작하였습니다.


2010년, 구글이 자율주행 자동차 산업에 뛰어들며 현재 많은 IT기업들이 자율주행 자동차 산업 발전에 기여하고 있습니다.


또한 최근 Apple 또한 자율주행 자동차 산업에 뛰어 들어 많은 기업들이 시제품 출시를 위해 경쟁하고 있다고 설명해주셨습니다.


자율 주행 자동차 산업의 기반 시스템으로는 cloud computing, 우버(자율주행 taxi), 지도 시스템이 있다고 말씀하셨습니다.



 현재는 보통 주행환경이 단순한 고속도로 부터 자율주행 시스템을 도입할 예정이고 점차 복잡한 시내로 퍼져나갈 것이며


현대자동차는 Highway Driving Assist(고속도로 운전 도움 System)을 현재 자동차에 탑제해 판매중이라고 말씀하셧씁니다.


2020년 까지 고속도로에서 완벽한 자율주행을 목표하고 있다고 말씀하셧습니다.



 물체인식 기반 시스템은 많이 발전하였지만(거의 완성), 자동차가 주행하고 있는 주행공간 인식은 아직 걸음마 단계고 많이


부족하다며 이쪽 분야 연구가 많이 이루어 저야 한다고 하셧습니다.(터널, 가로등, 고가도로, 신호등 등..)


또한 자동주행시 초음파, 레이더, 카메라 종류를 현재 사용하고 있으며 고가의 레이더, 초음파 장비를 사용하면


높은 정확성을 보장할 수 있지만, 가격으로 인해 양산이 불가능 하다며 현재는 보다 값 싼 장비로 최상의 성능을 끌어 올리는


방향으로 연구 중이라고 하셧습니다.



 앞으로 정밀지도(차선위치, 현재위치, 차선좌표, 가로등, 가드레일, 횡단보도)를 개발하여 현재 자동차의 


주행 위치(Localization-도로와 지도를 보고 현재 위치 매칭, 도로 위에 marker를 설정하고 지도에 표시된


정보를 비교해 현재 위치를 파악, Visual SLAM과 유사) 를 기반으로 다양한 어플리케이션(주차 가능 위치 파악 등..)


을 개발중이라고 말씀하셨습니다.




Tutorial 2. 한양대학교 정호기 교수


주제 : stixel기반 장애물 Depth 추정(각각의 객체에 대한 움직임 optical flow추정)


Stixel을 기반으로 추출한 데이터를 기반으로 각각 객체에 대한 object recognition을 수행해 상황 인지 및 판단 연구를 진행


과정을 설명해 주셨습니다.



지도의 feature와 현재 검출된 feature descriptor를 비교해 현재 자동차의 위치를 도출하는 것은 아직 도로 변화 대응에 미숙


하다는 문제가 있습니다. 따라서 변화(날씨, 온도, 눈, 비) 등에 강건한 descriptor 생성은 어려운 문제라고 하셧습니다.


따라서 descriptor를 기반으로 현재 위치를 파악하는 것 보다 도로위에 존재하는 각각의 물체(신호등, 도로 위 화살표, 마커) 등을 


미리 지도에 입력해 두고 자동차에서 카메라로 물체를 detect하게 되면 검출된 물체 위치를 기반으로 물체에 대한 거리를 판단해


현재 위치를 판단하는 방법을 사용중이며 인식률이 좋은 결과를 도출하셧다고 하셧습니다.


현재 자율 주행 자동차의 성능 평가를 위해 데이터 수집의 어려움이 있지만, [KITTI]를 사용하면 데이터 셋을 오픈소스로


제공해 주어 데이터 수집에 관한 어려움이 적어졌다고 하셧고 또한 [Cityscape DataSet] 이 15년도 말에 공개될 것이라고 


하셧습니다.



초청강의1. 아주대학교 허용석 교수


3D reconstruction에 관해 설명하셧습니다. 이론적인 내용이라 따로 정리하지 않겠습니다.


여러장의 사진을 사용할 경우 보통 Epipolar Line을 사용하는 경우가 많고,


parzen filter보다 MRF가 더 좋은 성능을 내는 것을 말씀해 주셨습니다.



초청강의2. 서강대학교 박운상 교수


스마트 카에 관련된 강의를 해 주셨고 앞으로의 발전 방향에 대해 언급하셧습니다.


또한 랩실에서 진행했던 과제와 얼굴 인식과 관련된 정보를 공유해 주셨습니다.



초청강의3. 광주과학기술원 윤국진 교수


자율 주행 자동차를 동적 상황인식을 통해 인지해 가는 방법을 랩실에서 진행하신 방법을 토대로 설명해 주셨습니다.


또한 ADAS 주행환경 인지에 초점을 맞춰 진행중이었습니다.



카메라의 장점으로는 방대한 량과 정보, 풍부한 량의 정보를 기반으로 주변 상황인지가 가능하며 센서들 간의 간섭이 없는


장점이 있으며, 단점으로는 야간, 눈, 비에는 카메라 정보가 많이 외곡되거나 부족한 단점을 설명해 주셨습니다.


동적 상황이란 움직이는 중에 발생하는 문제를 말하며 분야로는 스트레오 비전, 객체 검출 추적, 의미론적 영상 분할(도로, 차)


, 비주얼 오토메트리(자동차 위치 방향) 등의 문제로 세분화 할수 있습니다. 



초청강의4. UNIST 심재영 교수


single object tracking에 대해 강의하셧습니다. 추적 물체에 대해 배경과 물체를 잘 분리해 추적하면 높은 성능을 


낼수 있는 것을 실험적 결과로 보여주셨습니다.(HSV color, 48 histogram bin 사용)


patch안에 유사한 patch를 묶어 연결해서 물체의 bounding을 만듭니다.

(중앙에는 중요한 정보가 있다고 가정하고, 테두리에는 배경 정보가 많은 경우를 기초)


tracking은 Bayesian Tracking를 사용하였습니다. 연구 결과가 tracking에 있어 스케일 변화에 대응하지 못한 점이 아쉬웠습니다.