5/30/2018

How to get current directory in window application.

Example source code to get current directory in window application


..
CString CurrentDirectoryToCString()
{
    TCHAR buff[MAX_PATH];
    memset(buff, 0, MAX_PATH);
    ::GetCurrentDirectory(MAX_PATH, buff);
    CString strFolder = buff;

    return strFolder;
}
..

OpenCV, Dash line drawing example source code.

I can know all coordinate from A point to B point using "LineIterator" function in OpenCV.
So this source code is applied by this "LineIterator".


..
Mat DrawDashLine(Mat inMat, Point start, Point end, int gap, Scalar color)
{
    Mat rMat;
    rMat = inMat.clone();
    
    cv::LineIterator it(rMat, start, end, 8);
    vector< pair<cv::Point, cv::Point> > vecPt_pair;
    vector< cv::Point > vecPt;

    Point A, B;
    A = start;
    for (int i = 0, j = 0; i < it.count; i++, it++)
    {
        
        if (i % gap == 0)
        {
            //update end point
            B = it.pos();

            if(j%2)
                line(rMat, A, B, color, 2);

            //update start point
            A = B;
            j++;
        }
    }

    return rMat;
}

int main()
{
    Mat img(500, 500, CV_8UC3);
    img.setTo(0);

    Mat rImg = DrawDashLine(img, Point(20, 20), Point(300, 300), 10, CV_RGB(255, 0, 0));

    namedWindow("test", 0);
    cv::imshow("test", rImg);
    waitKey(0);
    
    return 0;
}

..







5/27/2018

OpenCV Integral Test source code


...
int main(int, char)
{
    
    Mat img = Mat(10, 10, CV_8UC1);
    randu(img, 0, 10);

    cout << "origin" << endl << img << endl;

    //int x=3, y=4, w=4, h=4;
    int x = 1, y = 1, w = 2, h = 2;

    int sum = 0;
    for (int i = 0; i < w; ++i)
    {
        for (int j = 0; j < h; ++j)
        {
            sum = sum + img.at<unsigned char>((y + j), (x + i));
        }
    }

    printf("for loop : sum = %d \n", sum);


    ///////////////////////////////////////////////////////////////////////

    Mat integralImg;
    integral(img, integralImg, CV_64F);

    cout << endl << "integral" << endl << integralImg << endl;

    double p1 = integralImg.at<double>((y), (x));
    double p2 = integralImg.at<double>((y), (x + w));
    double p3 = integralImg.at<double>((y + h), (x));
    double p4 = integralImg.at<double>((y + h), (x + w));

    printf("\n p1:%lf, p2:%lf, p3:%lf, p4:%lf\n", p1, p2, p3, p4);
    printf("integral : sum = %lf \n", (p1 + p4) - (p2 + p3));

    //////////////////////////////////////////////////////////////////////////
    

}



...


result

AdaptiveThreshold test code in opencv


...
#include "opencv2/opencv.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/cudaarithm.hpp"
#include <iostream>
#include <vector>

#ifdef _DEBUG               
#pragma comment(lib, "opencv_core331d.lib")       
#pragma comment(lib, "opencv_highgui331d.lib")    
#pragma comment(lib, "opencv_imgcodecs331d.lib")  
#pragma comment(lib, "opencv_objdetect331d.lib")  
#pragma comment(lib, "opencv_imgproc331d.lib")  
#pragma comment(lib, "opencv_videoio331d.lib")  
#pragma comment(lib, "opencv_cudaarithm331d.lib")  
#else       
#pragma comment(lib, "opencv_core331.lib")       
#pragma comment(lib, "opencv_highgui331.lib")    
#pragma comment(lib, "opencv_imgcodecs331.lib")    
#pragma comment(lib, "opencv_objdetect331.lib")  
#pragma comment(lib, "opencv_imgproc331.lib")  
#pragma comment(lib, "opencv_videoio331.lib")
#pragma comment(lib, "opencv_cudaarithm331.lib")
#endif        


using namespace std;
using namespace cv;



int main(int, char)
{

    namedWindow("img", 0);
    namedWindow("threshold", 0);
    namedWindow("mean_thres", 0);
    namedWindow("gauss_thres", 0);


    Mat img = imread("otzu.jpg");

    Mat gray, binary, binary1, binary2;
    cvtColor(img, gray, CV_RGB2GRAY);

    threshold(gray, binary, 128, 255, CV_THRESH_BINARY);
    adaptiveThreshold(gray, binary1, 255, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, 5, 5);
    adaptiveThreshold(gray, binary2, 255, ADAPTIVE_THRESH_GAUSSIAN_C, THRESH_BINARY, 5, 5);


    imshow("img", img);

    imshow("threshold", binary);
    imshow("mean_thres", binary1);
    imshow("gauss_thres", binary2);


    waitKey(0);

    return 0;
}


...

result

Threshold demo in OpenCV

Threshold test for
0: Binary
1: Binary Inverted
2: Threshold Truncated
3: Threshold to Zero
4: Threshold to Zero Inverted

...
#include "opencv2/opencv.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/cudaarithm.hpp"
#include <iostream>
#include <vector>

#ifdef _DEBUG               
#pragma comment(lib, "opencv_core331d.lib")       
#pragma comment(lib, "opencv_highgui331d.lib")    
#pragma comment(lib, "opencv_imgcodecs331d.lib")  
#pragma comment(lib, "opencv_objdetect331d.lib")  
#pragma comment(lib, "opencv_imgproc331d.lib")  
#pragma comment(lib, "opencv_videoio331d.lib")  
#pragma comment(lib, "opencv_cudaarithm331d.lib")  
#else       
#pragma comment(lib, "opencv_core331.lib")       
#pragma comment(lib, "opencv_highgui331.lib")    
#pragma comment(lib, "opencv_imgcodecs331.lib")    
#pragma comment(lib, "opencv_objdetect331.lib")  
#pragma comment(lib, "opencv_imgproc331.lib")  
#pragma comment(lib, "opencv_videoio331.lib")
#pragma comment(lib, "opencv_cudaarithm331.lib")
#endif        


using namespace std;
using namespace cv;


int threshold_value = 0;
int threshold_type = 3;;
int const max_value = 255;
int const max_type = 4;
int const max_BINARY_value = 255;

Mat src, src_gray, dst;
char* window_name = "Threshold Demo";

char* trackbar_type = "Type: \n 0: Binary \n 1: Binary Inverted \n 2: Truncate \n 3: To Zero \n 4: To Zero Inverted";
char* trackbar_value = "Value";

/// Function headers
void Threshold_Demo(int, void*);



void main()
{
    /// Load an image
    src = imread("blade.jpg", 1);

    /// Convert the image to Gray
    cvtColor(src, src_gray, CV_BGR2GRAY);

    /// Create a window to display results
    namedWindow(window_name, 0);
    resizeWindow(window_name, 500, 500);

    /// Create Trackbar to choose type of Threshold
    printf("%s", trackbar_type);
    createTrackbar(trackbar_type,
        window_name, &threshold_type,
        max_type, Threshold_Demo);

    createTrackbar(trackbar_value,
        window_name, &threshold_value,
        max_value, Threshold_Demo);

    /// Call the function to initialize
    Threshold_Demo(0, 0);

    //origin 
    namedWindow("origin", 0);
    imshow("origin", src);

    /// Wait until user finishes program
    while (true)
    {
        int c;
        c = waitKey(20);
        if ((char)c == 27)
        {
            break;
        }
    }

}


void Threshold_Demo(int, void*)
{
    // 0: Binary
    //1: Binary Inverted
    //2: Threshold Truncated
    //3: Threshold to Zero
    //4: Threshold to Zero Inverted


    threshold(src_gray, dst, threshold_value, max_BINARY_value, threshold_type);

    imshow(window_name, dst);
}

...


Image binary simple example for image & video

OpenCV Binary simple source code for image and video


Image
...
int main(int, char)
{

    namedWindow("img", 0);
    namedWindow("binary", 0);

    Mat img = imread("book.jpg");

    Mat gray, binary;
    cvtColor(img, gray, CV_RGB2GRAY);
    threshold(gray, binary, 128, 200, CV_THRESH_BINARY);


    imshow("img", img);
    imshow("binary", binary);

    waitKey(0);

    return 0;
}
...



Video (threshold and adpativeThreshold)
...
int main(int, char)
{
    VideoCapture stream1(0); //0:note book, 1:usb webcam

    Mat frame; //current frame
    Mat gray, binary_otsu, binary_th, binary_ad_m, binary_ad_g;

    namedWindow("img", 0);
    namedWindow("otsu", 0);
    namedWindow("binary_th", 0);
    namedWindow("binary_adaptive_mean", 0);
    namedWindow("binary_adaptive_gaussian", 0);

    //unconditional loop   
    while (true) {

        if (!(stream1.read(frame))) //get one frame form video   
            break;

        //printf("%d %d \n", frame.cols, frame.rows);
        resize(frame, frame, Size(frame.cols / 2, frame.rows / 2));
        cvtColor(frame, gray, CV_RGB2GRAY);

        threshold(gray, binary_th, 128, 255, CV_THRESH_BINARY);
        adaptiveThreshold(gray, binary_ad_m, 255, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, 9, 5);
        adaptiveThreshold(gray, binary_ad_g, 255, ADAPTIVE_THRESH_GAUSSIAN_C, THRESH_BINARY, 9, 5);
        GaussianBlur(gray, gray, Size(7, 7), 0);
        threshold(gray, binary_otsu, 0, 255, CV_THRESH_BINARY + THRESH_OTSU);


        imshow("img", frame);
        imshow("otsu", binary_otsu);
        imshow("binary_th", binary_th);
        imshow("binary_adaptive_mean", binary_ad_m);
        imshow("binary_adaptive_gaussian", binary_ad_g);

        if (waitKey(10)> 0)
            break;
    }

    return 0;
}

...

OpenCV LUT(look up table) example code

OpenCV LUT example source code


...
int LUTexample()
{

    Mat img = imread("AbyssCGI2.jpg");

    Mat lookUpTable(1, 256, CV_8U);
    uchar* p = lookUpTable.data;
    int factor = 256 / 5;
    for (int i = 0; i < 256; ++i)
    {
        p[i] = factor * (i / factor);
        printf("[%d] = %d \n", i, p[i]);
    }



    Mat reduced;
    LUT(img, lookUpTable, reduced);

    namedWindow("img", 0);
    imshow("img", img);
    namedWindow("reduced", 0);
    imshow("reduced", reduced);


    /*
    //////////////////// gray & color test!!
    Mat img2(1, 1, CV_8UC3);
    img2.setTo(Scalar(0, 128, 255));
    Mat im_color3;
    LUT(img2, lookUpTable, im_color3);
    cout << im_color3 << endl;
    //namedWindow("im_color3", 0);
    //imshow("im_color3", im_color3);

    //different result with color!!
    Mat img2_gray;
    cvtColor(img2, img2_gray, CV_BGR2GRAY);
    Mat im_color4;
    LUT(img2_gray, lookUpTable, im_color4);
    cout << im_color4 << endl;
    //namedWindow("im_color4", 0);
    //imshow("im_color4", im_color4);
    //////////////////////*/


    waitKey(0);


    return 0;

}
...



Video frame difference (frame subtraction), opencv example source code

video frame subtraction example source code using opencv



...
#include "opencv2/opencv.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/cudaarithm.hpp"
#include <iostream>
#include <vector>

#ifdef _DEBUG               
#pragma comment(lib, "opencv_core331d.lib")       
#pragma comment(lib, "opencv_highgui331d.lib")    
#pragma comment(lib, "opencv_imgcodecs331d.lib")  
#pragma comment(lib, "opencv_objdetect331d.lib")  
#pragma comment(lib, "opencv_imgproc331d.lib")  
#pragma comment(lib, "opencv_videoio331d.lib")  
#pragma comment(lib, "opencv_cudaarithm331d.lib")  
#else       
#pragma comment(lib, "opencv_core331.lib")       
#pragma comment(lib, "opencv_highgui331.lib")    
#pragma comment(lib, "opencv_imgcodecs331.lib")    
#pragma comment(lib, "opencv_objdetect331.lib")  
#pragma comment(lib, "opencv_imgproc331.lib")  
#pragma comment(lib, "opencv_videoio331.lib")
#pragma comment(lib, "opencv_cudaarithm331.lib")
#endif        


using namespace std;
using namespace cv;

int main(int, char)
{

    Mat frame;
    Mat old_frame;
    Mat sub_frame;
    //Mat absdiff_frame;
    VideoCapture stream1(0);

    if (!stream1.isOpened()) { //check if video device has been initialised
        cout << "cannot open camera 1";
        return 0;
    }

    while (1)
    {
        if (!(stream1.read(frame))) //get one frame form video   
            break;

        if (old_frame.empty())
        {
            old_frame = frame.clone();
            continue;
        }
        

        subtract(old_frame, frame, sub_frame);
        //absdiff(old_frame, frame, absdiff_frame);

        imshow("frame", frame);
        imshow("sub_frame", sub_frame);
        //imshow("absdiff_frame", absdiff_frame);

        //subtraction every frame
        old_frame = frame.clone(); 
        if (waitKey(5) >= 0)
            break;
    }

    return 0;
}
...

5/26/2018

Find contour example source code


Find Contour example source code


...
#include "opencv2/opencv.hpp"
#include "opencv2/highgui.hpp"
#include <iostream>
#include <vector>

#ifdef _DEBUG               
#pragma comment(lib, "opencv_core331d.lib")       
#pragma comment(lib, "opencv_highgui331d.lib")    
#pragma comment(lib, "opencv_imgcodecs331d.lib")  
#pragma comment(lib, "opencv_objdetect331d.lib")  
#pragma comment(lib, "opencv_imgproc331d.lib")  
#pragma comment(lib, "opencv_videoio331d.lib")    
#else       
#pragma comment(lib, "opencv_core331.lib")       
#pragma comment(lib, "opencv_highgui331.lib")    
#pragma comment(lib, "opencv_imgcodecs331.lib")    
#pragma comment(lib, "opencv_objdetect331.lib")  
#pragma comment(lib, "opencv_imgproc331.lib")  
#pragma comment(lib, "opencv_videoio331.lib")    
#endif        


using namespace std;
using namespace cv;

int main()
{
    Mat img(500, 500, CV_8UC3);
    img.setTo(255);

    cvtColor(img, img, CV_RGB2GRAY);
    img.setTo(0);
    rectangle(img, Rect(10, 10, 200, 200), CV_RGB(255, 255, 255), CV_FILLED);
    imshow("show1", img);

    Mat dst = Mat::zeros(img.rows, img.cols, CV_8UC3);
    vector< vector< Point> > contours;
    vector< Vec4i> hierarchy;

    findContours(img.clone(), contours, hierarchy,
        RETR_CCOMP, CHAIN_APPROX_SIMPLE);

    // iterate through all the top-level contours,
    // draw each connected component with its own random color
    int idx = 0;
    for (; idx >= 0; idx = hierarchy[idx][0])
    {
        Scalar color(rand() & 255, rand() & 255, rand() & 255);
        //drawContours(dst, contours, idx, color, FILLED, 8, hierarchy);
        drawContours(dst, contours, idx, color, 1, 8, hierarchy);
    }

    imshow("show2", dst);

    waitKey(0);

    return 0;
}
...

5/25/2018

example for applyColorMap usage

example for applyColorMap usage

...
#include "opencv2/opencv.hpp"
#include "opencv2/cuda.hpp"
#include "opencv2\cudaarithm.hpp"
#include <iostream>
#include <time.h>

using namespace std;
using namespace cv;

int main()
{
    
    //image show.
    Mat img = imread("AbyssCGI.jpg");
    
    namedWindow("img", 0);
    imshow("img", img);

    /////////////////applyColorMap
    //basic usage
    Mat im_color;
    applyColorMap(img, im_color, COLORMAP_COOL);//COLORMAP_AUTUMN);
    namedWindow("im_color", 0);
    imshow("im_color", im_color);

    //what about gray?
    Mat img_gray;
    cvtColor(img, img_gray, CV_RGB2GRAY);
    Mat im_color2;
    applyColorMap(img_gray, im_color2, COLORMAP_AUTUMN);
    namedWindow("im_color2", 0);
    imshow("im_color2", im_color2);
    /////////////////////////////////////////

    //////////////////// gray & color test!!
    Mat img2(100, 100, CV_8UC3);
    img2.setTo(Scalar(0, 128, 255));
    Mat im_color3;
    applyColorMap(img2, im_color3, COLORMAP_JET);

    namedWindow("im_color3", 0);
    imshow("im_color3", im_color3);

    //same with resutl of color
    Mat img2_gray;
    cvtColor(img2, img2_gray, CV_RGB2GRAY);
    Mat im_color4;
    applyColorMap(img2, im_color4, COLORMAP_JET);
    namedWindow("im_color4", 0);
    imshow("im_color4", im_color4);
    //////////////////////

    waitKey(0);

    return 0;
}
...


Loop & LUT processing time compare

 Loop & LUT processing time compare


...
#include "opencv2/opencv.hpp"
#include "opencv2/cuda.hpp"
#include "opencv2\cudaarithm.hpp"
#include <iostream>
#include <time.h>

using namespace std;
using namespace cv;

int main(int, char)
{
    unsigned long AAtime = 0, BBtime = 0;
    unsigned char O[1000][1000] = { 1, 2, };

    //very slow;
    AAtime = getTickCount();
    for (int i = 0; i < 1000; ++i)
    {
        for (int j = 0; j < 1000; ++j)
        {
            int t = O[i][j] * 1.14;
            t = (t > 255) ? 255 : t;
            O[i][j] = t;
        }
    }
    BBtime = getTickCount();
    printf("just loop %.5lf sec \n", (BBtime - AAtime) / getTickFrequency()); //chec
    
    //fast
    unsigned char LUT[256];
    AAtime = getTickCount();
    for (int i = 0; i < 256; ++i)
    {
        int t = i * 1.14;
        t = (t > 255) ? 255 : t;
        LUT[i] = t;
    }

    for (int i = 0; i < 1000; ++i)
        for (int j = 0; j < 1000; ++j)
            O[i][j] = LUT[O[i][j]];
    
    BBtime = getTickCount();
    printf("using lut %.5lf sec \n", (BBtime - AAtime) / getTickFrequency()); //chec

    return 0;
}
...


print each character in string and some useful functions

This is example source code for how to print and access each character in string.
And using this function, I made some useful functions.
Thank you.


...
void printAndCountAllCh(string str)
{
    int count = 0;
    for (std::string::iterator it = str.begin(); it != str.end(); ++it) {
        std::cout << count << ": " << *it << endl;
        count++;
    }
}

string changeAtoB(string str, char A, char B)
{
    int count = 0;
    for (std::string::iterator it = str.begin(); it != str.end(); ++it) {
        if (string(1, *it) == string(1, A))
        {
            *it = B;
        }
    }

    return str;
}

string deleteA(string str, char A)
{
    string rstr;
    int count = 0;
    for (std::string::iterator it = str.begin(); it != str.end(); ++it) {
        if (string(1, *it) != string(1, A))
        {
            rstr.push_back(*it);
        }
    }

    return rstr;
}


int countNotCH(string str, char CH)
{
    int count = 0;
    for (std::string::iterator it = str.begin(); it != str.end(); ++it) {
        if (string(1, *it) != string(1, CH))
            count++;
    }
    return count;
}

int main()
{

    string str = "A_B CD_EF GH_I";
    int count;

    printAndCountAllCh(str); //print each char and count
    std::cout << endl;

    string abc = changeAtoB(str, ' ', '_'); //A_B CD_EF GH_I -> A_B_CD_EF_GH_I
    std::cout << abc << endl << endl;

    string bbb = deleteA(str, ' '); //A_B CD_EF GH_I -> A_BCD_EFGH_I
    std::cout << bbb << endl << endl;

    count = countNotCH(str, '_'); //A_B CD_EF GH_I -> 11
    std::cout << count << endl << endl;

    return 0;
}
...




5/22/2018

single color value convert from RGB to YUV and YUV to RGB

Simple color convert code for a pixel value

example for :
RGB to YUV ,YUV to RGB


void rgbToyuv(int r, int g, int b, int& y, int& u, int& v)
{
    Mat img_in(1, 1, CV_8UC3);
    img_in.at<Vec3b>(0, 0)[0] = uint(b);
    img_in.at<Vec3b>(0, 0)[1] = uint(g);
    img_in.at<Vec3b>(0, 0)[2] = uint(r);


    Mat img_out;
    cvtColor(img_in, img_out, CV_BGR2YUV);

    y = uint(img_out.at< cv::Vec3b>(0, 0)[0]);
    u = uint(img_out.at< cv::Vec3b>(0, 0)[1]);
    v = uint(img_out.at< cv::Vec3b>(0, 0)[2]);
}

void yuvTorgb(int y, int u, int v, int& r, int& g, int& b)
{
    Mat img_in(1, 1, CV_8UC3);
    img_in.at<Vec3b>(0, 0)[0] = uint(y);
    img_in.at<Vec3b>(0, 0)[1] = uint(u);
    img_in.at<Vec3b>(0, 0)[2] = uint(v);


    Mat img_out;
    cvtColor(img_in, img_out, CV_YUV2BGR);

    b = uint(img_out.at< cv::Vec3b>(0, 0)[0]);
    g = uint(img_out.at< cv::Vec3b>(0, 0)[1]);
    r = uint(img_out.at< cv::Vec3b>(0, 0)[2]);
}


int main()
{

    int ored = 255;
    int ogreen = 0;
    int oblue = 0;
    int y2, u2, v2;
    printf("origin %d %d %d \n", oblue, ogreen, ored);

    rgbToyuv(ored, ogreen, oblue, y2, u2, v2);
    printf("origin -> yuv: %d %d %d \n", y2, u2, v2);

    int r3, g3, b3;
    yuvTorgb(y2, u2, v2, r3, g3, b3);
    printf("yuv -> rgb: %d %d %d \n", r3, g3, b3);
}




5/12/2018

Github command tips

*Init Github
$ git init
Initialized empty Git repository in ~/djangogirls/.git/
$ git config --global user.name "yourname"
$ git config --global user.emai yourname@mail.com

*Making ignore file -> .ignore
*.pyc
*~
__pycache__
myvenv
db.sqlite3
/static
.DS_Store

*Status check
$ git status
On branch master
Initial commit
Untracked files:  (use "git add <file>..." to include in what will be committed)
        .gitignore        blog/        manage.py        mysite/
nothing added to commit but untracked files present (use "git add" to track)

*add and commit
$ git add --all . #git add .
$ git commit -m "My Django Girls app, first commit"
 [...] 13 files changed, 200 insertions(+) create mode 100644 .gitignore [...] create mode 100644 mysite/wsgi.py

*Set remote repository
$ git remote add origin https://github.com/MareArts/CVLecture_djangocms.git
$ git push -u origin master

*Command arrangement
Working computer
$ git status
$ git add --all .
$ git status
$ git commit -m "Changed the HTML for the site."
$ git push

Deploy computer
$ git pull

*tip force pull
https://stackoverflow.com/questions/1125968/how-do-i-force-git-pull-to-overwrite-local-files
$git fetch --all
$git reset --hard origin/master
or
$git reset --hard origin/<branch_name>

*tip to set user/pass don't ask every time
save username / pass
$git config credential.helper store
$git pull

change information
$git config credential.helper store 
$git pull

*tip when .igore file not working
https://stackoverflow.com/questions/11451535/gitignore-is-not-working
git rm -r --cached .
git add .
git commit -m "fixed untracked files"

*delete git
rm -rf .git

*delete specific file ex) some problem file which can't do push because of over than 100mb.
git filter-branch --force --index-filter \
'git rm --cached --ignore-unmatch path_more_than_100mb.file' \
--prune-empty --tag-name-filter cat -- --all

ex)
git filter-branch --force --index-filter \
'git rm --cached --ignore-unmatch checkpoints_/model.ckpt-23000.data-00000-of-00001' \
--prune-empty --tag-name-filter cat -- --all