3/15/2014

OpenCV Study, Write text on the image, cvPutText, putText


cvPutText, IplImage case.
CvFont * font = new CvFont;
cvInitFont(font, CV_FONT_VECTOR0, 0.5f, 1.0f, 0, 1, 8); //rate of width and height is 1:2

char szText[8];
sprintf(szText, "TextOut");  //make string

cvPutText(Image, szText, CenterPoint, font, CV_RGB(255, 255, 255)); //draw text on the IplImage* (Image)




putText, Mat case.
char TestStr[100]; 
sprintf(TestStr,"total time : %lf sec", 0.001 );
putText(OutImg, TestStr, Point(100,250), CV_FONT_NORMAL, 1, Scalar(255,255,255),1,1); //OutImg is Mat class;


...






OpenCV Study, Mat Size Width, Height

int width = frame.size().width;
int height = frame.size().height;

OpenCV Study, IplImage * display to PictureBox on Dialog (MFC), example source code

void DisplayIplImageToPictureBox(IplImage* pImgIpl, CDC* pDC, CRect rect)
{
 BITMAPINFO bitmapInfo;
 bitmapInfo.bmiHeader.biSize=sizeof(BITMAPINFOHEADER);
 bitmapInfo.bmiHeader.biPlanes=1;
 bitmapInfo.bmiHeader.biCompression=BI_RGB;
 bitmapInfo.bmiHeader.biXPelsPerMeter=100;
 bitmapInfo.bmiHeader.biYPelsPerMeter=100;
 bitmapInfo.bmiHeader.biClrUsed=0;
 bitmapInfo.bmiHeader.biClrImportant=0;
 bitmapInfo.bmiHeader.biSizeImage=0;
 bitmapInfo.bmiHeader.biWidth=pImgIpl->width;
 bitmapInfo.bmiHeader.biHeight=-pImgIpl->height;

 IplImage* tempImage=NULL;

 if(pImgIpl->nChannels == 3)
 {
  tempImage = (IplImage*)cvClone(pImgIpl);
  bitmapInfo.bmiHeader.biBitCount=tempImage->depth * tempImage->nChannels;

 }
 else if(pImgIpl->nChannels == 1)
 {
  tempImage =  cvCreateImage(cvGetSize(pImgIpl), IPL_DEPTH_8U, 3);
  cvCvtColor(pImgIpl, tempImage, CV_GRAY2BGR);
  bitmapInfo.bmiHeader.biBitCount=tempImage->depth * tempImage->nChannels;
 }
 if( tempImage != NULL)
 {
  pDC->SetStretchBltMode(COLORONCOLOR);
  ::StretchDIBits(pDC->GetSafeHdc(), rect.left, rect.top, rect.right, rect.bottom, 
   0, 0, tempImage->width, tempImage->height, tempImage->imageData, &bitmapInfo, 
   DIB_RGB_COLORS, SRCCOPY);

  cvReleaseImage(&tempImage);
 }
}


void DrawFunction()
{
     //code is omitted..
     //~~~~
     //~~~~~

     CDC* vDC;
     vDC = m_PicBox.GetDC(); //m_PicBox is PictureBox CStatic variable.
     CRect rect;
     m_PicBox.GetClientRect(&rect);
     DisplayIplImageToPictureBox(img, vDC, rect); //img is IplImage* variable.
     ReleaseDC(vDC);
     //~~~
     //~~~

}



..
Example picture of display(drawing) IplImage * on a dialog


OpenCV Study, Mat to IplImage* convert, simple method


Data Copy
IplImage * img = cvCloneImage( &(IplImage)frame ); //where frame is Mat!!
//~~~
//~~
cvReleaseImge(&img);



Point Copy
IplImage * img = &((IplImage)frame) //where frame is Mat!!

3/13/2014

C,C++, To get a list of files in a directory using CFileFind function, example source code


        CFileFind finder;
 CString strFileName;
 //CStringList list;
 strFiles.Format("C:\\Demo\\*.avi", pszPathname);
 BOOL bWorking = finder.FindFile(strFiles);
 while(bWorking)
 {
  bWorking = finder.FindNextFile();
  //list.AddTail(finder.GetFileName());
  ::AfxMessageBox(finder.GetFileName());
 }


C, C++, To select folder only and get path using SHBrowseForFolder function, example source code

//Get only folder name
 ITEMIDLIST *pidlBrowse;
 WCHAR pszPathname[MAX_PATH];
 
 BROWSEINFO BrInfo;
 BrInfo.hwndOwner = GetSafeHwnd();
 BrInfo.pidlRoot = NULL;
 
 CString str =_T("c:\\"); //initial path
 LPCTSTR lpszDefaultFolder = str;
 memset(&BrInfo, 0, sizeof(BrInfo));
 BrInfo.pszDisplayName=(LPSTR)pszPathname;
 BrInfo.lpszTitle=_T("Select directory");
 BrInfo.ulFlags=BIF_RETURNONLYFSDIRS; //select folder only
 //BrInfo.ulFlags=BIF_BROWSEINCLUDEFILES; //select folder and file
 BrInfo.lParam=(LPARAM)lpszDefaultFolder;
 //BrInfo.lpfn=BrowseCallback;
 
 pidlBrowse = ::SHBrowseForFolder(&BrInfo);

 
 if (pidlBrowse != NULL)
 {
  //Get Path
  SHGetPathFromIDList(pidlBrowse, (LPSTR)pszPathname);
  AfxMessageBox((LPCSTR)pszPathname);
 }


...



C, C++, To select a file and get path and file name using CFileDialog function, example source code

TCHAR szFilter[] = _T("All Files(*.*)|*.*||");
CFileDialog dlg(TRUE, NULL, NULL, OFN_HIDEREADONLY, szFilter);

CString strPathName, m_filename;
if(IDOK == dlg.DoModal()) {
 m_filename=dlg.GetFileName();   //file name
 strPathName = dlg.GetPathName(); //full path info
}

..



C,C++, Get current directory( path ), GetCurrentDirectory function

char reDir[500];
::GetCurrentDirectory(500,reDir);
::AfxMessageBox(reDir);

C, C++, The meaning of LPSTR, LPCSTR, LPTSTR, LPCTSTR, LPWSTR

LP is Long Pointer.
C is constant.
STR is String.

LPSTR = long pointer string = char*
LPCSTR = long pointer constant string = const char*



W means Wide char and unicode.

LPWSTR = long porinter wide string = w_char*
LPCWSTR = long porinter constant wide string = const w_char*


T is ..

LPCTSTR = long pointer constant t_string = const tchar*



3/11/2014

Python Study, Pycharm color setting

Pycharm color setting menu is here..

Preference ->  Editor -> Colors & Fonts.
Pycharm support 5 colors mode. (default, darcula, monokai, twilight, warmneon)
But we can set more various color setting detailed.

Refer to screen captures of color skin.









Python Study, Pycharm first setting

At first, you have to register python compiler,
Setting menu is here ...

Preference -> Project interpreter
or
File -> Default settings... -> project interpreter

And then, Add(+) python interpreter path and click apply or ok button




C,C++, string split example source code (stringstream, getline functions)


#include < iostream >
#include < string >
#include < sstream >

using namespace std;

vector< string> str_split(const string &s, char delim) 
{
    vector< string> elems;
    stringstream ss(s);
    string item;
    
    while (getline(ss, item, delim)) {
        elems.push_back(item);
    }
 
    return elems;
}



int main()
{

 vector< string> str = str_split( "123,456", ',');
 for(int i=0; i< str.size(); ++i)
 {
  printf("%s\n", str[i].c_str() );
 }

}


3/10/2014

Python study, OS modules

__author__ = 'mare'

import os

print( os.getcwd() )
#/Users/mare/PycharmProjects/OS_module

print( os.access('.', os.F_OK ) )
print( os.access('.', os.W_OK | os.X_OK | os.R_OK ) ) #write, exec, read
#True
#True

os.rmdir('test1')
print( os.listdir('.') )
#['.idea', 'osModule.py']
os.mkdir('test1')
print( os.listdir('.' ) )
#['.idea', 'osModule.py', 'test1']

os.removedirs('test2/sub1/sub2/leaf')
os.makedirs('test2/sub1/sub2/leaf')
print( os.listdir('test2/sub1/sub2') )
#['leaf']

print(os.listdir('.'))
os.rename('newfile.txt', 'oldfile.txt')
print(os.listdir('.'))
#['.idea', 'newfile.txt', 'osModule.py', 'test1', 'test2']
#['.idea', 'oldfile.txt', 'osModule.py', 'test1', 'test2']
os.rename('oldfile.txt','newfile.txt')


os.renames('newfile.txt', 'ttt/moved.txt')
print( os.listdir('ttt') )
#['.DS_Store', 'moved.txt']
os.renames('ttt/moved.txt', 'newfile.txt')

print( os.stat('newfile.txt') )
#posix.stat_result(st_mode=33188, st_ino=5325009, st_dev=16777219, st_nlink=1, st_uid=501, st_gid=20, st_size=0, st_atime=1394464185, st_mtime=1394463961, st_ctime=1394463961)


#I made directory like that
# - test_walk
#  +- a
#  +- b
#      +- newfile.txt

for path, dirs, files in os.walk('test_walk'):
 print( path, dirs, files)
#test_walk ['a', 'b'] ['.DS_Store']
#test_walk/a [] []
#test_walk/b [] ['newfile.txt']

for path, dirs, files in os.walk('test_walk', topdown=False):
 print( path, dirs, files)
#test_walk/a [] []
#test_walk/b [] ['newfile.txt']
#test_walk ['a', 'b'] ['.DS_Store']


print( os.pipe() ) #create pipe to communicate between proccess


#file object creation
#r, w = os.pipe()
#rd = os.fdopen(r)

#rp = os.popen('dir' 'r')
#print( p.read() )


print(os.name)
#posix

print( os.environ )
#environ({'__CF_USER_TEXT_ENCODING': '0x1F5:3:51', 'SSH_AUTH_SOCK': '/tmp/launch-XLOLCi/Listeners', 'PYCHARM_HOSTED': '1', 'VERSIONER_PYTHON_PREFER_32_BIT': 'no', 'PYTHONIOENCODING': 'UTF-8', 'PYTHONUNBUFFERED': '1', 'PATH': '/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin', 'LOGNAME': 'mare', 'USER': 'mare', 'HOME': '/Users/mare', 'TMPDIR': '/var/folders/b7/gxpfjkqs0bs33cyyn76q7drw0000gn/T/', 'VERSIONER_PYTHON_VERSION': '2.7', '__CHECKFIX1436934': '1', 'Apple_PubSub_Socket_Render': '/tmp/launch-bHTzXo/Render', 'SHELL': '/bin/bash', '__PYVENV_LAUNCHER__': '/Library/Frameworks/Python.framework/Versions/3.3/bin/python3', 'PYTHONPATH': '/Users/mare/PycharmProjects/OS_module'})
print( os.environ.keys() )
#KeysView(environ({'__CF_USER_TEXT_ENCODING': '0x1F5:3:51', 'SSH_AUTH_SOCK': '/tmp/launch-XLOLCi/Listeners', 'PYTHONPATH': '/Users/mare/PycharmProjects/OS_module', 'LOGNAME': 'mare', 'PATH': '/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin', 'PYCHARM_HOSTED': '1', '__CHECKFIX1436934': '1', 'PYTHONUNBUFFERED': '1', 'SHELL': '/bin/bash', 'Apple_PubSub_Socket_Render': '/tmp/launch-bHTzXo/Render', 'PYTHONIOENCODING': 'UTF-8', 'TMPDIR': '/var/folders/b7/gxpfjkqs0bs33cyyn76q7drw0000gn/T/', 'VERSIONER_PYTHON_PREFER_32_BIT': 'no', 'USER': 'mare', 'VERSIONER_PYTHON_VERSION': '2.7', '__PYVENV_LAUNCHER__': '/Library/Frameworks/Python.framework/Versions/3.3/bin/python3', 'HOME': '/Users/mare'}))

print( os.getpid() )
#10140

os.system('calc')
#os.startfile('LICENSE.txt')





3/09/2014

Python Study, SQLite3

SQLite3 is already included in your python, so you do not need install.

__author__ = 'mare'


import sqlite3

con = sqlite3.connect("test.db")
con2 = sqlite3.connect(":memory:") #create db in memory space, it is faster but all clear after program turn off

#sql excute
cur = con.cursor()
cur.execute("DROP TABLE phoneBook;")
cur.execute("CREATE TABLE PhoneBook(Name text, PhoneNum text);")
cur.execute("INSERT INTO PhoneBook VALUES('Derick', '010-1234-5678');")
cur.execute("INSERT INTO PhoneBook VALUES('Merry', '010-5678-0000');")


name = "SangJung"
phoneNumber = '010-5670-2343'
cur.execute("INSERT INTO PhoneBook VALUES(?, ?);",(name, phoneNumber))



cur.execute("INSERT INTO PhoneBook VALUES(:inputName, :inputNum);",
 {"inputNum":phoneNumber, "inputName":name})



#datalist = (('Tom', '010-543-5432'), ('DSP', '010-123-1234'))
#cur.execute("INSERT INTO PhoneBook VALUES(?, ?);", datalist)


#view reccord
cur.execute("SELECT * FROM PhoneBook;")
for row in cur:
 print(row)
#('Derick', '010-1234-5678')
#('SangJung', '010-5670-2343')
#('SangJung', '010-5670-2343')

cur.execute("SELECT * FROM PhoneBook;")
print( cur.fetchone() )
print( cur.fetchmany(2))
#('Derick', '010-1234-5678')
#[('SangJung', '010-5670-2343'), ('SangJung', '010-5670-2343')]


cur.execute("SELECT * FROM PhoneBook;")
print( cur.fetchone() )
print( cur.fetchall() )
#('Derick', '010-1234-5678')
#[('SangJung', '010-5670-2343'), ('SangJung', '010-5670-2343')]


con.commit()  #you have to run commit function to udpate db contents.
con.isolation_level = None #auto commit mode


#record ordering
cur.execute("SELECT * FROM PhoneBook ORDER By Name")
print( [r for r in cur])
cur.execute("SELECT * FROM PhoneBook ORDER By Name DESC")
print( [r for r in cur])
#[('Derick', '010-1234-5678'), ('Merry', '010-5678-0000'), ('SangJung', '010-5670-2343'), ('SangJung', '010-5670-2343')]
#[('SangJung', '010-5670-2343'), ('SangJung', '010-5670-2343'), ('Merry', '010-5678-0000'), ('Derick', '010-1234-5678')]

cur.execute("INSERT INTO PhoneBook VALUES('apple', '010-369-3639');")
cur.execute("SELECT * FROM PhoneBook ORDER By Name")
print( [r[0] for r in cur] )
#['Derick', 'Merry', 'SangJung', 'SangJung', 'apple']



#user define condition function
def OrderFunc(str1, str2):
 s1 = str1.upper()
 s2 = str2.upper()
 return (s1 > s2 ) - (s1 < s2 )

con.create_collation('myordering', OrderFunc)
cur.execute("SELECT Name FROM PhoneBook ORDER By Name COLLATE myordering")
print( [r[0] for r in cur])
#['apple', 'Derick', 'Merry', 'SangJung', 'SangJung']




#new table creation
cur.execute("DROP TABLE PhoneBook2")
cur.execute("CREATE TABLE PhoneBook2(Name text, Age ineger);")
list = (('Tom', 24), ('Derick',30), ('Peter',53), ('Jane',29))
cur.executemany("INSERT INTO PhoneBook2 VALUES (?,?);", list)
#cur.execute("INSERT INTO PhoneBook2 VALUES(?,?);", list[0])
#cur.execute("INSERT INTO PhoneBook2 VALUES(?,?);", list[1])
#cur.execute("INSERT INTO PhoneBook2 VALUES(?,?);", list[2])

cur.execute("SELECT length(Name), upper(Name), lower(Name) FROM PhoneBook")
print(" == length(), upper(), lower() ==")
print( [r for r in cur] )
#== length(), upper(), lower() ==
#[(6, 'DERICK', 'derick'), (5, 'MERRY', 'merry'), (8, 'SANGJUNG', 'sangjung'), (8, 'SANGJUNG', 'sangjung'), (5, 'APPLE', 'apple')]


#User-defined aggregate functions
class Average:
 def __init__(self):
  self.sum = 0
  self.cnt = 0

 def step(self, value):
  self.sum += value
  self.cnt += 1

 def finalize(self):
  return self.sum / self.cnt

con.create_aggregate("avg", 1, Average)
cur.execute("SELECT avg(Age) FROM PhoneBook2")
print( cur.fetchone() )
#34.0


#Type of variables in SQLite3
#Python -> SQLite3
#None -> NULL
#int -> INTEGER
#float -> REAL
#str, bytes -> TEXT
#buffer -> BLOB

#db dump
for l in con.iterdump():
 print(l)
"""
BEGIN TRANSACTION;
CREATE TABLE PhoneBook(Name text, PhoneNum text);
INSERT INTO "PhoneBook" VALUES('Derick','010-1234-5678');
INSERT INTO "PhoneBook" VALUES('Merry','010-5678-0000');
INSERT INTO "PhoneBook" VALUES('SangJung','010-5670-2343');
INSERT INTO "PhoneBook" VALUES('SangJung','010-5670-2343');
INSERT INTO "PhoneBook" VALUES('apple','010-369-3639');
CREATE TABLE PhoneBook2(Name text, Age ineger);
INSERT INTO "PhoneBook2" VALUES('Tom',24);
INSERT INTO "PhoneBook2" VALUES('Derick',30);
INSERT INTO "PhoneBook2" VALUES('Peter',53);
INSERT INTO "PhoneBook2" VALUES('Jane',29);
COMMIT;
"""


 



python study, Get list item using __getitem__ function

list = (('Tom', 24), ('Derick',30), ('Peter',53), ('Jane',29))
print( list[0] )
print( list[0].__getitem__(0))
print( list[1].__getitem__(1))
#('Tom', 24)
#Tom
#30