Conditional Random Field(CRF)

패턴인식 & 기계학습 2015. 10. 8. 00:32

Conditional Random Field(CRF) 란?


 만약에 우리가 어떤 여행지에 가서 여행한 순서에 따라 사진을 찍었다고 가정해보자. 집에 돌아와서 여행중 찍었던 사진을 정리하려고 하니 하나하나 분류하기가 매우 귀찮다. 따라서 분류기를 만들어 행동을 보고 각각의 행동(먹다, 노래부르다.. 등) 기준으로 사진을 분류하고자 한다. 예를 들면 오전 6시는 아침이라 어두우니 자고있다로 분류하고, 자동차 이미지가 있으면 운전하다로 분류, 입에 무엇을 가져다 대면 먹다로 분류하는 기준을 세웠다. 하지만 잘 분류 될것 처럼 보이지만, 엄청난 문제가 존재한다. 만약 아래 사진과 같이 어떤 사람이 입에 가까이 무엇을 대고 있으면 분류기 기준에 따라 먹다로 분류되기도 하고 어떻게 보면 노래하는 것 처럼 보이기도 할 것이다.



이러한 문제를 어떻게 해결할 수 있을까? 한가지 좋은 방법은 사진을 찍었을때의 sequence를 잘 보고 식당에 있고 손으로 입에 무엇을 가져다 대면 먹다로 분류하고, 주위가 어둡고 입에 무엇인가를 가져다 대면 노래하다로 분류하면 위 문제를 어느정도 해결할 수 있지 않을까? 이렇게 하나의 sequence를 보고 판단하는 것이 아니라 사진을 찍었던 순간 이전 혹은 이후를 참조해 지금 상태를 결정하는 것을 Conditional Random Field(CRF)라고 한다.


참조 : http://blog.echen.me/2012/01/03/introduction-to-conditional-random-fields/

Automatically image Description(Auto Caption)

패턴인식 & 기계학습 2015. 10. 6. 20:11

1. Deep Learning의 등장

 2010년대 초반 딥러닝(Deep Learning)의 문제점 및 한계를 극복해 여러 인공지능의 분야에 적용하면서 전체적인 성능 및 인식률이 매우 상승했다. 그 중 가장 획기적인 아이디어 중 하나인 방법으로 사람이 아닌 컴퓨터가 스스로 이미지를 보고 이미지를 표현(representation)하는 것이다. 이 것은 Language translation의 분야중 하나였지만, Deep Learning을 이용하여 이미지의 인식(recognition)성능이 많이 상승하여 이미지와 번역(translation)을 결합하여 컴퓨터 스스로 이미지를 보고 영상을 분석할 수 있게 되었다. 





2. Auto Caption(Automatically Image Description)

 Language Expression이 가능해 진 이후로 Deep Learning과 여러 모델을 결합하여 이미지의 표현(Image Representation)을 정확히 해내는 여러 대회(ImageNet, Microsoft COCO 등..) 에서 어느 모델이 더 이미지를 언어로 표현을 잘 하는지?(이미지를 보고 문장을 만들어 냈을때 오류가 없는)를 측정하여 순위를 매겨 수상하는 대회를 매년 진행하고 있다. 아래 그림은 최근 Microsoft에서 주최하는 Image Caption대회의 결과를 보여준다. 사람의 표현 능력과 각 기업, 연구소, 연구실에서 개발한 모듈 별로 얼마나 표현을 잘 하는지를 나타낸 순위이다. 모든 모델이 어떻게 설계되었고 어떻게 문장(언어)를 표현하는지는 아직 밝혀져 있지는 않지만 여러 논문에서 소개하는 방법을 간단히 설명하고자 한다.


Fig1. Microsoft COCO Captioning Challenge[1]



3. Show and Tell : A Neural Image Caption Generator [2]

 2014년 Google에서 발표한 Show and Tell 이라는 논문에서 소개된 방법은 영상인식을 위해 CNN모듈과 RNN(LSTM)을 결합한 모듈로 Auto Caption하는 방법을 소개한 논문이다. 


Fig2. Show and Tell Auto caption Model[2]


 CNN 모듈로는 GoogLeNet[3]을 기반으로 Batch Normalization을 적용한 모델[4]을 사용하였다. Batch Normalization을 기존 GoogLeNet에 적용하여 Inception Module을 수정하여 기존 에러률(error rate) 6.7%보다 (ImageNet Class Top-5 error 4.9%)을 보인 정확한 이미지 표현이 가능한 모듈(Fig3.Left)을 사용한뒤, Language Presentation모듈로는 LSTM(Long Short Term Memory) Fig3.Right을 적용하여 하였다.


Fig3. (Left) CNN & LSTM 모델 결합, (Right) LSTM [2]



4. From Captions to Visual Concepts and Back [5]

 Multiple Instance Learning을 통하여 Auto Caption 을 수행하는 논문으로 총 3단계의 표현 과정을 거친다. 첫번째로 이미지 내에서 표현 가능한 단어를 각각 추출 한뒤, 각각의 표현된 단어로 문장을 구성한다. 구성된 문장을 re-rank과정을 통해 최종적으로 문장 하나를 선택해 표현하는 순서로 알고리즘이 구성되어 있다.


Fig4. Caption Generate Pipeline[3]


 위 모델의 특징으로는 이미지 부분(region)을 기반으로 각각의 Object에 대한 정보를 추출했을때, Open혹은 Beautiful 같은 형용사의 뜻을 가진 단어는 표현하기 힘든 문제로 이미지 부분이 아닌 전체를 기반으로 Object에 대한 정보를 추출하였고, 기존 CNN들과는 다르게 Convolutional Neural Network 과정에 포함된 Fully Connected Layer(7~8 Layer)에 Image의 region 정보와 word correspond정보, image 정보를 전파 할수 있도록 Layer를 수정하여 이미지 내부에 Logistic Function을 추가하여 이미지 위치 정보와 word를 표현이 동시에 가능하도록 표현하는 모델을 제안하였다. Language Representation 표현된 단어 정보로 caption을 generation하기 위해 Maximum entropy(ME) Language Model(LM)을 이용하여 지금 상태(condition)에서 확률적으로 모든 단어를 계산한 뒤, 높은 likelihood를 detection하여 각각의 단어를 연결하는 방법을 사용하였다.



Reference


[1] http://mscoco.org/dataset/#captions-leaderboard

[2] Vinyals, Oriol, et al. "Show and tell: A neural image caption generator." arXiv preprint arXiv:1411.4555 (2014).

[3] Szegedy, Christian, et al. "Going deeper with convolutions." arXiv preprint arXiv:1409.4842 (2014).

[4] Ioffe, Sergey, and Christian Szegedy. "Batch normalization: Accelerating deep network training by reducing internal covariate shift." arXiv preprint arXiv:1502.03167 (2015).

[5] Fang, Hao, et al. "From captions to visual concepts and back." arXiv preprint arXiv:1411.4952 (2014).

[6] Caffe Model Zoo : https://github.com/BVLC/caffe/wiki/Model-Zoo


'패턴인식 & 기계학습' 카테고리의 다른 글

Conditional Random Field(CRF)  (3) 2015.10.08
Jaccard similarity 계산  (0) 2015.10.02
Deep Learning 두번째 세미나  (0) 2015.09.29
딥러닝 framework Theano 설치  (0) 2015.09.21
에이다부스트(adaboost)  (0) 2015.02.27

Jaccard similarity 계산

패턴인식 & 기계학습 2015. 10. 2. 15:19

Jaccard Semilarity 계산


Jaccard Index는 Paul Jaccard이 제안한 유사성 계산 알고리즘이다.


기본적으로 Jaccard similarity measure방법은 두 데이터 집합의 교집합을 합집합으로 나눈것으로 정의한다.



  



Jaccard Distance는 1에서 Jaccard Similarity를 뺀값으로 계산하거나, 합집합에서 교집합을 뺀 크기를 


합집합의 크기로 나눈 것으로 계산할 수 있다.




Jaccard Distance의 값은 0~1사이의 값을 갖고 A와 B가 empty일 경우 1의 값을 갖는다.


보통 binary attributes의 similarity를 계산할때 많이 사용된다. (위키피디아 참조 - Jaccard_index)



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


Deep Learning 두번째 세미나

패턴인식 & 기계학습 2015. 9. 29. 00:16

'패턴인식 & 기계학습' 카테고리의 다른 글

Automatically image Description(Auto Caption)  (0) 2015.10.06
Jaccard similarity 계산  (0) 2015.10.02
딥러닝 framework Theano 설치  (0) 2015.09.21
에이다부스트(adaboost)  (0) 2015.02.27
k-means clustering  (0) 2015.02.27

딥러닝 framework Theano 설치

패턴인식 & 기계학습 2015. 9. 21. 21:35

reference : http://deeplearning.net/software/theano/install_ubuntu.html#install-ubuntu


For Ubuntu 11.10 through 14.04:

sudo apt-get install python-numpy python-scipy python-dev python-pip python-nose g++ libopenblas-dev git
sudo pip install Theano



If you would like, instead, to install the bleeding edge Theano (from github) such that you can edit and contribute to Theano, replace the pip install Theano command with:

git clone git://github.com/Theano/Theano.git
cd Theano
python setup.py develop --user
cd ..


Updating Theano

If you followed these installation instructions, you can execute this command to update only Theano:

sudo pip install --upgrade --no-deps theano

If you want to also installed NumPy/SciPy with pip instead of the system package, you can run this:

sudo pip install --upgrade theano


'패턴인식 & 기계학습' 카테고리의 다른 글

Jaccard similarity 계산  (0) 2015.10.02
Deep Learning 두번째 세미나  (0) 2015.09.29
에이다부스트(adaboost)  (0) 2015.02.27
k-means clustering  (0) 2015.02.27
딥러닝 Deep Learning  (0) 2015.02.27

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

Image Processing with CUDA

프로그래밍/CUDA 2015. 7. 28. 02:39

  

    Cuda_ex1.zip




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
// main.cpp
 
#include <cv.hpp>
#include "kernel.h"
using namespace cv;
 
int main()
{
    // Open a webcamera
    VideoCapture camera(0);
    Mat frame;
    if (!camera.isOpened()) 
        return -1;
    
    camera >> frame;
 
    // create CPU/GPU shared images - one for the initial and one for the result
    Mat sGray(frame.size(),CV_8U,createImageBuffer(frame.size().width * frame.size().height));
    Mat dGray(frame.size(),CV_8U,createImageBuffer(frame.size().width * frame.size().height));
    Mat eGray(frame.size(),CV_8U,createImageBuffer(frame.size().width * frame.size().height));
    cvtColor(frame, dGray, CV_BGR2GRAY);
    cvtColor(frame, eGray, CV_BGR2GRAY);
 
    // Create the capture windows
    namedWindow("Source");
    namedWindow("Greyscale");
    namedWindow("Blurred");
    namedWindow("Sobel");
    
    char c;
 
    // Loop while capturing images
    while (1)
    {
        // Capture the image and store a gray conversion for the gpu
        camera >> frame;
        cv::cvtColor(frame, sGray, CV_BGR2GRAY);
        
        boxfilter(frame.size().width, frame.size().height, sGray.data, dGray.data, 33);
        //boxfilterCPU(frame.size().width, frame.size().height, sGray.data, dGray.data, 3, 3);
        sobelfilter(frame.size().width, frame.size().height, dGray.data, eGray.data);
 
        // Show the results
        cv::imshow("Source", frame);
        cv::imshow("Greyscale", sGray);
        cv::imshow("Blurred", dGray);
        cv::imshow("Sobel", eGray);
 
        c = cv::waitKey(10);
        
        if (c == 27)
            break;
    }
 
    // Exit
    destroyImageBuffer(sGray.data);
    destroyImageBuffer(dGray.data);
    destroyImageBuffer(eGray.data);
 
    return 0;
}
 
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
// kernel.h
 
#ifndef _KERNEL_H_
#define _KERNEL_H_
 
#include <iostream>
 
void boxfilter(int iw, int ih, unsigned char *source, unsigned char *dest, int bw, int bh);
void boxfilterCPU(int iw, int ih, unsigned char *src, unsigned char *dst, int bw, int bh);
void sobelfilter(int iw, int ih, unsigned char *source, unsigned char *dest);
 
unsigned char* createImageBuffer(unsigned int bytes);
void           destroyImageBuffer(unsigned char* bytes);
#endif
cs

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
#include "cuda_runtime.h"
#include "device_launch_parameters.h"
#include <stdio.h>
#include "kernel.h"
 
void boxfilterCPU(int iw, int ih, unsigned char *src, unsigned char *dst, int bw, int bh)
{
    for (int m = 0; m < ih; m++)
    {
        for (int n = 0; n < iw; n++)
        {
            int count = 0;
            float sum = 0.0;
 
            for (int j = -(bh / 2); j <= (bh / 2); j++)
            {
                for (int i = -(bw / 2); i <= (bw / 2); i++)
                {
                    // Verify that this offset is within the image boundaries
                    if ((n + i) < iw && (n + i) >= 0 && (m + j) < ih && (m + j) >= 0)
                    {
                        sum += (float)src[((m + j) * iw) + (n + i)];
                        count++;
                    }
                }
            }
 
            // Average the sum
            sum /= (float)count;
            dst[(m * iw) + n] = (unsigned char)sum;
        }
    }
}
 
__global__ void boxfilter_kernel(int iw, int ih, unsigned char *source, unsigned char *dest, int bw, int bh)
{
    // Calculate our pixel's location
    int x = (blockIdx.x * blockDim.x) + threadIdx.x;
    int y = (blockIdx.y * blockDim.y) + threadIdx.y;
 
    // Variables to store the sum
    int count = 0;
    float sum = 0.0;
 
    // Do the blur operation by summing the surround pixels
    for (int j = -(bh / 2); j <= (bh / 2); j++)
    {
        for (int i = -(bw / 2); i <= (bw / 2); i++)
        {
            // Verify that this offset is within the image boundaries
            if ((x + i) < iw && (x + i) >= 0 && (y + j) < ih && (y + j) >= 0)
            {
                sum += (float)source[((y + j) * iw) + (x + i)];
                count++;
            }
        }
    }
 
    // Average the sum
    sum /= (float)count;
    dest[(y * iw) + x] = (unsigned char)sum;
}
 
__global__ void sobelfilter_kernel(int iw, int ih, unsigned char *source, unsigned char *dest)
{
    // Calculate our pixel's location
    int x = (blockIdx.x * blockDim.x) + threadIdx.x;
    int y = (blockIdx.y * blockDim.y) + threadIdx.y;
 
    // Operate only if we are in the correct boundaries
    if (x > 0 && x < iw - 1 && y > 0 && y < ih - 1)
    {
        int gx = -source[iw*(y - 1+ (x - 1)] + source[iw*(y - 1+ (x + 1)] +
            -2 * source[iw*(y)+(x - 1)] + 2 * source[iw*(y)+(x + 1)] +
            -source[iw*(y + 1+ (x - 1)] + source[iw*(y + 1+ (x + 1)];
        int gy = -source[iw*(y - 1+ (x - 1)] - 2 * source[iw*(y - 1+ (x)]
            - source[iw*(y - 1+ (x + 1)] +
            source[iw*(y + 1+ (x - 1)] + 2 * source[iw*(y + 1+ (x)] +
            source[iw*(y + 1+ (x + 1)];
        dest[iw*+ x] = (int)sqrt((float)(gx)*(float)(gx)+(float)(gy)*(float)(gy));
    }
}
 
 
 
 
void boxfilter(int iw, int ih, unsigned char *source, unsigned char *dest, int bw, int bh)
{
    // allocate memory for the bitmap in GPU memory
    unsigned char *dev_source, *dev_dest;
    cudaHostGetDevicePointer(&dev_source, source, 0);
    cudaHostGetDevicePointer(&dev_dest, dest, 0);
 
    //cudaOccupancyMaxActiveBlocksPerMultiprocessorWithFlags()
 
    // Run the boxfilter kernel
    dim3 blocks(iw / 16, ih / 16);
    dim3 threads(1616);
    
    // Execute the kernel
    boxfilter_kernel << <blocks, threads >> >(iw, ih, dev_source, dev_dest, bw, bh);
    cudaThreadSynchronize();
}
 
void sobelfilter(int iw, int ih, unsigned char *source, unsigned char *dest)
{
    // allocate memory for the bitmap in GPU memory
    unsigned char *dev_source, *dev_dest;
    cudaHostGetDevicePointer(&dev_source, source, 0);
    cudaHostGetDevicePointer(&dev_dest, dest, 0);
 
    // Run the boxfilter kernel
    dim3 blocks(iw / 16, ih / 16);
    dim3 threads(1616);
 
    // Execute the kernel
    sobelfilter_kernel << <blocks, threads >> >(iw, ih, dev_source, dev_dest);
    cudaThreadSynchronize();
}
 
unsigned char* createImageBuffer(unsigned int bytes)
{
    unsigned char *ptr = NULL;
    cudaSetDeviceFlags(cudaDeviceMapHost);
    cudaHostAlloc(&ptr, bytes, cudaHostAllocMapped);
    return ptr;
}
 
void destroyImageBuffer(unsigned char* bytes)
{
    cudaFreeHost(bytes);
}
cs



'프로그래밍 > CUDA' 카테고리의 다른 글

CUDA 스레드 구조  (0) 2014.12.06
CUDA 기본 문법 정리  (0) 2014.12.06