8/10/2018

opencv perspective test



This is perspective example source code.
Basically, perspective is multiple by H(homography) matrix.
Like this :
B = H*A
In here, B is perspective image, A is original image and H is homography matrix.
For this calculate, we can use opencv function this -> warpPerspective(..)
 easily.
And to find H, we also can use findHomography opencv function as well.

for more detail refer to this page:
http://study.marearts.com/2014/04/video-stabilizing-example-source-code.html
http://study.marearts.com/2011/10/sift-matching-c-source-code-using.html
http://study.marearts.com/2015/03/image-warping-using-opencv.html

and below source code:
code looks a little complicated, but just see getPerspectiveImg function carefully, other codes are just for making random and set value.

github url is here : https://github.com/MareArts/opencv_perspective_test

Thank you.

#include <stdio.h>
#include <opencv2/opencv.hpp> 
#include <string>

#ifdef _DEBUG  
#pragma comment(lib, "opencv_core331d.lib")   
#pragma comment(lib, "opencv_imgproc331d.lib")   //MAT processing  
#pragma comment(lib, "opencv_highgui331d.lib")  
#pragma comment(lib, "opencv_calib3d331d.lib") 
#pragma comment(lib, "opencv_imgcodecs331d.lib")
#else  
#pragma comment(lib, "opencv_core331.lib")  
#pragma comment(lib, "opencv_imgproc331.lib")  
#pragma comment(lib, "opencv_highgui331.lib")
#pragma comment(lib, "opencv_calib3d331.lib")
#pragma comment(lib, "opencv_imgcodecs331.lib")
#endif


//#pragma comment(lib, "opencv_objdetect246.lib")  
//#pragma comment(lib, "opencv_features2d246.lib")  


using namespace std;
using namespace cv;


bool setPt(float x1, float x2, float x3, float x4, float y1, float y2, float y3, float y4, vector< Point2f> &in)
{
 if (in.size() == 4)
 {
  in[0].x = x1;
  in[1].x = x2;
  in[2].x = x3;
  in[3].x = x4;

  in[0].y = y1;
  in[1].y = y2;
  in[2].y = y3;
  in[3].y = y4;
 }
 else {
  return false;
 }

 return true;
}


bool makeRandomPerspectivePoint(const vector< Point2f> &A, vector< Point2f> &B, Size imgSize)
{
 if (A.size() != 4 || B.size() != 4)
 {
  cout << "matrix vector error!" << endl;
  return false;
 }

 if (imgSize.width <= 0 || imgSize.height <= 0)
 {
  cout << "image size error!" << endl;
  return false;
 }

 const float maxRand = 0.4;
 int width = imgSize.width;
 int height = imgSize.height;
 int rndMarginX = width * maxRand;
 int rndMarginY = height * maxRand;

 int rx1 = rand() % rndMarginX;
 int ry1 = rand() % rndMarginY;
 int rM = rand() % 4;

 //minimum value
 if (rx1 == 0)
  rx1 = 1;
 if (ry1 == 0)
  ry1 = 1;

 //4 perspective mode
 if (rM == 0)
 {
  setPt(0, width, width, 0, 0 + ry1, 0, height, height - ry1, B);
 }
 else if (rM == 1)
 {
  setPt(0 + rx1, width - rx1, width, 0, 0, 0, height, height, B);
 }
 else if (rM == 2)
 {
  setPt(0, width, width, 0, 0, 0 + ry1, height - ry1, height, B);
 }
 else {
  setPt(0, width, width - rx1, 0 + rx1, 0, 0, height, height, B);
 }

 return true;
}

bool getPerspectiveImg(const Mat& inImg, Mat& outImg, const vector< Point2f> &A, const vector< Point2f> &B)
{
 if (A.size() != 4 || B.size() != 4)
 {
  cout << "matrix vector error!" << endl;
  return false;
 }

 //B = H*A
 Mat H = findHomography(A, B);
 //perspectiveImg = H * inImg
 warpPerspective(inImg, outImg, H, inImg.size());


 //return
 return true;
}



int main()
{
 
 string fn = "Flag_of_South_Korea.png";
 Mat testImg = imread(fn);
 srand(time(0));
 Size imgSize = testImg.size();
 vector< Point2f > opt(4);
 setPt(0, imgSize.width, imgSize.width, 0, 0, 0, imgSize.height, imgSize.height, opt);
 vector< Point2f > dpt(4);

 while (1)
 {

  if (makeRandomPerspectivePoint(opt, dpt, imgSize) == false)
   break;

  Mat outImg;
  if (getPerspectiveImg(testImg, outImg, opt, dpt)) {
   imshow("origin", testImg);
   imshow("perspective", outImg);
   waitKey(0);
  }
  else {
   cout << "matrix vector error!" << endl;
   break;
  }
 }

}

3D array numpy -> pandas ->csv -> pandas -> 3d array numpy

This article is example source code for
3D array numpy -> pandas -> csv -> pandas -> 3D array numpy

Let's see step by step


Step 1, make example data

import numpy as np
import pandas as pd


#make list
a = [[11, 12, 13, 14, 15], [15, 16, 17, 18, 19]]
b = [[21, 22, 23, 24, 25], [25, 26, 27, 28, 29]]
c = []
c.append(a)
c.append(b)
#make numpy
npa = np.array(c)
print('npa\n',npa)
print('npa shape\n',npa.shape) #2 by 2 by 5


result
npa
 [[[11 12 13 14 15]
  [15 16 17 18 19]]

 [[21 22 23 24 25]
  [25 26 27 28 29]]]
npa shape
 (2, 2, 5)


Step 2, numpy to pandas
#make numpy to panda
m,n,r = npa.shape
#numpy ->group indexing, reshape
out_arr = np.column_stack((np.repeat(np.arange(m),n),npa.reshape(m*n,-1)))
out_df = pd.DataFrame(out_arr, columns=['group','a','b','c','d','e'])
print('pnadas\n',out_df) #pandas

result

group   a   b   c   d   e
0      0  11  12  13  14  15
1      0  15  16  17  18  19
2      1  21  22  23  24  25
3      1  25  26  27  28  29


Step 3, save csv, load csv

#save to csv
out_df.to_csv('test3Dpandas.csv', index=False)
#load csv
df = pd.read_csv('test3Dpandas.csv')


Step 4, pandas to numpy

#pandas to numpy
npb = df.values
npb = npb[:,1:]
npb2 = npb.reshape(m,n,r)
print('numpy\n',npb2)

result

numpy
 [[[11 12 13 14 15]
  [15 16 17 18 19]]

 [[21 22 23 24 25]
  [25 26 27 28 29]]]







7/20/2018

get file list in the folder (example code)

example code


namespace fs = std::experimental::filesystem;

std::vector<std::string> list_files_in_dir(string dirPath)
{
 vector<string> r;
 
 for (auto & p : fs::directory_iterator(dirPath))
 {
  std::cout << p.path().string() << std::endl;
  r.push_back(p.path().string());
 }
 
 return r;
}

7/04/2018

get files list in a directory in ubuntu

refer to below code:

..
std::vector<std::string> list_files_in_dir(const char* dirPath)
        {
    DIR *dir;

    std::vector<std::string> files;

    struct dirent *ent;
    if ((dir = opendir (dirPath)) != NULL)
    {
        /* print all the files and directories within directory */
        while ((ent = readdir (dir)) != NULL)
        {
            if (strcmp(ent->d_name, ".") != 0 && strcmp(ent->d_name, "..") != 0)
            {
                stringstream fullpath;
                fullpath << dirPath << "/" << ent->d_name;
                files.push_back(fullpath.str());
            }
        }
        closedir (dir);
    }
    else
    {
        /* could not open directory */
        perror ("");
        return files;
    }

    return files;
}
..

7/03/2018

opencv install on ubuntu

Simple and easy way

1. install opencv from the official site
sudo apt-get autoremove libopencv-dev python-opencv


2. download sh file
https://github.com/milq/milq/blob/master/scripts/bash/install-opencv.sh

3. run sh file
bash install-opencv.sh
4. test
cd build/bin
./example_cpp_edge ../../samples/data/fruits.jpg


That's all

Thank you.

more detail refer to here :https://milq.github.io/install-opencv-ubuntu-debian/

6/29/2018

Pycharm does not show plot

just use "plt.show()"


for example
...
plt.figure(figsize=IMAGE_SIZE)
plt.imshow(image_np)
plt.show()
...

Thank you.

6/26/2018

Install Hangul(Korean) on Utubu

type this on terminal

..
dpkg -l | grep ibus-hangul
or
sudo apt-get install ibus-hangul
..


Ubuntu CUDA install on Console

Uninstall previous version
..
sudo apt-get purge cuda
sudo apt-get purge libcudnn6
sudo apt-get purge libcudnn6-dev
..


Install cuda 9.0, cuDnn 7.0
..
wget http://developer.download.nvidia.com/compute/cuda/repos/ubuntu1604/x86_64/cuda-repo-ubuntu1604_9.0.176-1_amd64.deb
wget http://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu1604/x86_64/libcudnn7_7.0.5.15-1+cuda9.0_amd64.deb
wget http://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu1604/x86_64/libcudnn7-dev_7.0.5.15-1+cuda9.0_amd64.deb
wget http://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu1604/x86_64/libnccl2_2.1.4-1+cuda9.0_amd64.deb
wget http://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu1604/x86_64/libnccl-dev_2.1.4-1+cuda9.0_amd64.deb
sudo dpkg -i cuda-repo-ubuntu1604_9.0.176-1_amd64.deb
sudo dpkg -i libcudnn7_7.0.5.15-1+cuda9.0_amd64.deb
sudo dpkg -i libcudnn7-dev_7.0.5.15-1+cuda9.0_amd64.deb
sudo dpkg -i libnccl2_2.1.4-1+cuda9.0_amd64.deb
sudo dpkg -i libnccl-dev_2.1.4-1+cuda9.0_amd64.deb
sudo apt-get update
sudo apt-get install cuda=9.0.176-1
sudo apt-get install libcudnn7-dev
sudo apt-get install libnccl-dev
..


Add below code the end of ./bashrc file
..
export PATH=/usr/local/cuda-9.0/bin${PATH:+:${PATH}}
export LD_LIBRARY_PATH=/usr/local/cuda-9.0/lib64${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}}
..

And reboot.


refer to here : https://yangcha.github.io/CUDA90/


Linux wifi driver on Mac device

just input this command


sudo apt-get update
sudo apt-get install firmware-b43-installer

Tip, uninstall virtualbox on ubuntu


find virtualbox s/w

$> dpkg -l | grep virtualbox

the name is depends on your installation name

uninstall virtualbox
$> sudo apt-get remove --purge virtualbox-5.2


Install sublime text 3 on ubuntu using console command

Open terminal (control + alt + T) and follow below command


...
1. run command to install the key
wget -qO - https://download.sublimetext.com/sublimehq-pub.gpg | sudo apt-key add -


2. add the apt repository via command
echo "deb https://download.sublimetext.com/ apt/stable/" | sudo tee /etc/apt/sources.list.d/sublime-text.list


3. install
sudo apt-get update
sudo apt-get install sublime-text


4. uninstall
sudo apt-get remove sublime-text && sudo apt-get autoremove

..

refer to this page : http://tipsonubuntu.com/2017/05/30/install-sublime-text-3-ubuntu-16-04-official-way/


Thank you.

6/23/2018

string = string + int + string, simple source code

^^ memo

...
std::stringstream ss;
ss << "test" << index << ".png";
//stringstream to string
string s = ss.str(); 
...

6/22/2018

eclipse install

before to install
input below command in terminal

$> sudo apt-get install openjdk-8-jdk

and 

click or run "eclipse-inst"

then you can see installer

 

opencv 2.4.9 install on ubuntu


refer to this GitHub page : https://gist.github.com/smithjessk/bde98ec9297b38bad40c

save sh file, for example opencv249.sh
...
# Install OpenCV 2.4.9 for Ubuntu
# Derived from https://github.com/jayrambhia/Install-OpenCV/blob/master/Ubuntu/2.4/opencv2_4_8.sh

# @author Jess Smith <smith.jessk@gmail.com>
# @license MIT

arch=$(uname -m)
if [ "$arch" == "i686" -o "$arch" == "i386" -o "$arch" == "i486" -o "$arch" == "i586" ]; then
flag=1
else
flag=0
fi

echo "Installing OpenCV 2.4.9"
mkdir OpenCV
cd OpenCV

echo "Removing any pre-installed ffmpeg and x264"
sudo apt-get -y remove ffmpeg x264 libx264-dev

echo "Installing Dependenices"
sudo apt-get -y install libopencv-dev
sudo apt-get -y install build-essential checkinstall cmake pkg-config yasm
sudo apt-get -y install libtiff4-dev libjpeg-dev libjasper-dev
sudo apt-get -y install libavcodec-dev libavformat-dev libswscale-dev libdc1394-22-dev libxine-dev libgstreamer0.10-dev libgstreamer-plugins-base0.10-dev libv4l-dev
sudo apt-get -y install python-dev python-numpy
sudo apt-get -y install libtbb-dev
sudo apt-get -y install libqt4-dev libgtk2.0-dev
sudo apt-get -y install libfaac-dev libmp3lame-dev libopencore-amrnb-dev libopencore-amrwb-dev libtheora-dev libvorbis-dev libxvidcore-dev
sudo apt-get -y install x264 v4l-utils ffmpeg
sudo apt-get -y install libgtk2.0-dev

echo "Downloading OpenCV 2.4.9"
wget -O OpenCV-2.4.9.zip http://sourceforge.net/projects/opencvlibrary/files/opencv-unix/2.4.9/opencv-2.4.9.zip/download

echo "Installing OpenCV 2.4.9"
unzip OpenCV-2.4.9.zip
cd opencv-2.4.9
mkdir build
cd build
cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local -D WITH_TBB=ON -D BUILD_NEW_PYTHON_SUPPORT=ON -D WITH_V4L=ON -D INSTALL_C_EXAMPLES=ON -D INSTALL_PYTHON_EXAMPLES=ON -D BUILD_EXAMPLES=ON -D WITH_QT=ON -D WITH_OPENGL=ON ..
make -j4
sudo make install
sudo sh -c 'echo "/usr/local/lib" > /etc/ld.so.conf.d/opencv.conf'
sudo ldconfig

echo "OpenCV 2.4.9 ready to be used"
...

and input command

$> chmod +x opencv249.sh
$> ./opencv249.sh

That's all ^^

Ubuntu C++ OpenCV version Check

version check
 $ pkg-config --modversion opencv

Package check
 $ pkg-config --libs opencv

path check
 $ pkg-config --cflags opencv

for example:
...
19:42 ~ $ pkg-config --modversion opencv                                                                                                 
2.4.9
19:42 ~ $ pkg-config --libs opencv                                                                                                       
/usr/local/lib/libopencv_calib3d.so /usr/local/lib/libopencv_contrib.so /usr/local/lib/libopencv_core.so /usr/local/lib/libopencv_features2d.so /usr/local/lib/libopencv_flann.so /usr/local/lib/libopencv_gpu.so /usr/local/lib/libopencv_highgui.so /usr/local/lib/libopencv_imgproc.so /usr/local/lib/libopencv_legacy.so /usr/local/lib/libopencv_ml.so /usr/local/lib/libopencv_nonfree.so /usr/local/lib/libopencv_objdetect.so /usr/local/lib/libopencv_ocl.so /usr/local/lib/libopencv_photo.so /usr/local/lib/libopencv_stitching.so /usr/local/lib/libopencv_superres.so /usr/local/lib/libopencv_ts.a /usr/local/lib/libopencv_video.so /usr/local/lib/libopencv_videostab.so -ltbb -lrt -lpthread -lm -ldl  
19:42 ~ $ pkg-config --cflags opencv                                                                                                     
-I/usr/local/include/opencv -I/usr/local/include 
...

6/21/2018

String split by delimiter (c++/c)

refer to souce code

...
void CForeAndBack::getStrings(string csvFname, vector<string> eachStr, string delimiter)
{
    //parsing
    size_t pos = 0;
    while ((pos = csvFname.find(delimiter)) != std::string::npos) {
        string token = csvFname.substr(0, pos);
        std::cout << token << std::endl;
        eachStr.push_back(token);
        csvFname.erase(0, pos + delimiter.length());
    }
    std::cout << csvFname << std::endl;
    eachStr.push_back(csvFname);
}
...


6/20/2018

make folder in the c code

simple example code

..
#include <direct.h>

..
string outputFolder = "output";
_mkdir(outputFolder.c_str());
..
..

6/18/2018

TCHAR to string

simple sample code

...
TCHAR buff[1024];
///
///..something to do
///
wstring test(&buff[0]); //convert to wstring
string strFolder(test.begin(), test.end()); //and convert to string.
...

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