• Tistory
    • 태그
    • 위치로그
    • 방명록
    • 관리자
    • 글쓰기
Carousel 01
Carousel 02
Previous Next

'function'에 해당되는 글 14건

  • 2014.03.25 [Function][MFC] 폴더 내 모든파일 삭제하기
  • 2014.03.25 [Function][MFC] 폴더 내 파일 갯수 확인하기
  • 2014.01.27 [Function] HoG Destriptor in OpenCV
  • 2014.01.23 [Function] 영상을 회전 시키기
  • 2014.01.23 [Function][MFC] CFileFind 를 이용하여 폴더내 모든파일 리스트박스에 추가하기 18
  • 2014.01.23 [Function][MFC] CFileDialog 를 이용하여 다중 파일 목록 작성
  • 2014.01.23 [Function][MFC] 폴더 경로 구하기 ( CString에 선택된 폴더의 절대경로를 저장하자 )
  • 2014.01.16 [matlab] mfile을 이용하여 function을 만들어보자.
  • 2013.11.07 [Function] IplImage 에 한글text 삽입하기 1
  • 2013.06.14 CFileDialog 다중파일 선택하기
  • 2013.04.02 [Function] dialog 에 FPS 표시하기
  • 2013.04.02 [Function] FindContour 덩어리 찾기
  • 2013.04.02 [Function] Dialog 창에 IplImage 출력하기
  • 2013.04.02 [Function] Convex Hull 최외곽선 검출하기 3

[Function][MFC] 폴더 내 모든파일 삭제하기

Programming/C, C++, MFC 2014. 3. 25. 14:05





이번에 사용하는 함수는 기본으로 제공되는 API 중에 


DeleteFile / MoveFile / CopyFile 이상 세가지 이다.


파일의 경로를 파라미터로 넣어주면 해당 기능이 동작하는 심플한 API 이다.


아래 예제는 해당 경로 내 모든 파일을 삭제하는 함수이다. 


DeleteFile 의경우 삭제할 파일의 경로를 파라미터로 하나 받고


MoveFile / CopyFile 의 경우에는 소스경로 복사/이동 대상경로를 파라미터로 2개 받는다.



  1. void DeleteAllFiles(CString dirName)
  2. {
  3.         CFileFind finder;
  4.        
  5.         BOOL bWorking = finder.FindFile((CString)dirName + "/*.*");
  6.        
  7.         while(bWorking)
  8.         {
  9.                 bWorking = finder.FindNextFile();
  10.                 if(finder.IsDots())
  11.                 {
  12.                         continue;
  13.                 }
  14.  
  15.                 CString filePath = finder.GetFilePath();
  16.                 DeleteFile(filePath);
  17.          }
  18.         finder.Close();
  19. }


저작자표시 비영리 (새창열림)

'Programming > C, C++, MFC' 카테고리의 다른 글

함수의 파라미터로 포인터를 사용  (0) 2014.07.02
STL List  (0) 2014.06.09
[Function][MFC] 폴더 내 파일 갯수 확인하기  (0) 2014.03.25
프로그램 실행시간을 측정 해 보자!  (0) 2014.02.12
[Function][MFC] CFileFind 를 이용하여 폴더내 모든파일 리스트박스에 추가하기  (18) 2014.01.23
블로그 이미지

매직블럭

작은 지식들 그리고 기억 한조각

,

[Function][MFC] 폴더 내 파일 갯수 확인하기

Programming/C, C++, MFC 2014. 3. 25. 14:01





폴더를 이용할때 해당 폴더 내에 파일이 몇개나 들어있는지 확인 하고 싶은 경우가 종종 있다.


이때 사용 가능한 방법이다.


CFileFind 클래스를 이용하여 파일을 찾고 파일 갯수마다 갯수++ 하는 방식으로 사용한다.


CString 형태로 폴더의 경로를 입력하면 해당 폴더 내 파일 갯수를 리턴 해 준다.


  1. int GetDirFilesNum(CString dirName)
  2. {
  3.         int count = 0;
  4.         CFileFind finder;
  5.        
  6.         BOOL bWorking = finder.FindFile(dirName + "/*.*");
  7.  
  8.         while(bWorking)
  9.         {
  10.                 bWorking = finder.FindNextFile();
  11.                 if(finder.IsDots())
  12.                 {
  13.                         continue;
  14.                 }
  15.                
  16.                 count++;
  17.  
  18.         }
  19.         finder.Close();
  20.  
  21.         return count;
  22. }


저작자표시 비영리 (새창열림)

'Programming > C, C++, MFC' 카테고리의 다른 글

STL List  (0) 2014.06.09
[Function][MFC] 폴더 내 모든파일 삭제하기  (0) 2014.03.25
프로그램 실행시간을 측정 해 보자!  (0) 2014.02.12
[Function][MFC] CFileFind 를 이용하여 폴더내 모든파일 리스트박스에 추가하기  (18) 2014.01.23
[Function][MFC] CFileDialog 를 이용하여 다중 파일 목록 작성  (0) 2014.01.23
블로그 이미지

매직블럭

작은 지식들 그리고 기억 한조각

,

[Function] HoG Destriptor in OpenCV

Programming/OpenCV 2014. 1. 27. 19:58




OpenCV에 포함되어 있는 기본적인 HOG 특징을 뽑아주는 함수이다.


기본 사람검출을 위한 파라미터를 이용해서 간단한 테스트만 해봤다.


나중에 이걸 쓸일이 있을지는 모르겠지만 일단 저장..


아마 다음에 hog를 쓴다면 아마 구현해서 쓰겠지... 


  1. Mat img;
  2.  
  3. img = imread( "C:\\Users\\Administrator\\Pictures\\test.jpg" );
  4.  
  5. HOGDescriptor hog;
  6. hog.setSVMDetector( HOGDescriptor::getDefaultPeopleDetector() );
  7. vector<Rect> detected;
  8.  
  9. double time = double( GetTickCount() );
  10.  
  11. hog.detectMultiScale( img, detected, 0, Size(9,9), Size(26,20), 1.05, 2 );
  12. time = double( GetTickCount() ) - time;
  13.  
  14. int detectedCNT = detected.size();
  15.  
  16. for( int i=0; i<detectedCNT; i++ )
  17. {
  18.         Rect people = detected[i];
  19.         rectangle( img, people, Scalar(0,0,255), 2 );
  20. }
  21.  
  22. imshow( "Result", img )


그래도 별다른 작업없이 기본 파라미터만 이용해서 


사검출 결과가 나오니 간단한 테스트용으로는 사용 할 만 하겠지?


아래사진은 작년 경주에서 찍은 사진.. 옆에 형은 초상권.. 으로인한 모자이크 처리 해드립니다.


성능은 뭐 예상대로 별로다. 어거지로 끼워 맞춘 느낌.. 





아래는 외국사이트에서 본 hog feature 시각화해서 보여주는 소스란다.


아직 확인은 안해봤지만 나중에 참고하도록 하자.

// HOGDescriptor visual_imagealizer
// adapted for arbitrary size of feature sets and training images
Mat get_hogdescriptor_visual_image(Mat& origImg,
                                   vector<float>& descriptorValues,
                                   Size winSize,
                                   Size cellSize,                                   
                                   int scaleFactor,
                                   double viz_factor)
{   
    Mat visual_image;
    resize(origImg, visual_image, Size(origImg.cols*scaleFactor, origImg.rows*scaleFactor));
 
    int gradientBinSize = 9;
    // dividing 180° into 9 bins, how large (in rad) is one bin?
    float radRangeForOneBin = 3.14/(float)gradientBinSize; 
 
    // prepare data structure: 9 orientation / gradient strenghts for each cell
	int cells_in_x_dir = winSize.width / cellSize.width;
    int cells_in_y_dir = winSize.height / cellSize.height;
    int totalnrofcells = cells_in_x_dir * cells_in_y_dir;
    float*** gradientStrengths = new float**[cells_in_y_dir];
    int** cellUpdateCounter   = new int*[cells_in_y_dir];
    for (int y=0; y<cells_in_y_dir; y++)
    {
        gradientStrengths[y] = new float*[cells_in_x_dir];
        cellUpdateCounter[y] = new int[cells_in_x_dir];
        for (int x=0; x<cells_in_x_dir; x++)
        {
            gradientStrengths[y][x] = new float[gradientBinSize];
            cellUpdateCounter[y][x] = 0;
 
            for (int bin=0; bin<gradientBinSize; bin++)
                gradientStrengths[y][x][bin] = 0.0;
        }
    }
 
    // nr of blocks = nr of cells - 1
    // since there is a new block on each cell (overlapping blocks!) but the last one
    int blocks_in_x_dir = cells_in_x_dir - 1;
    int blocks_in_y_dir = cells_in_y_dir - 1;
 
    // compute gradient strengths per cell
    int descriptorDataIdx = 0;
    int cellx = 0;
    int celly = 0;
 
    for (int blockx=0; blockx<blocks_in_x_dir; blockx++)
    {
        for (int blocky=0; blocky<blocks_in_y_dir; blocky++)            
        {
            // 4 cells per block ...
            for (int cellNr=0; cellNr<4; cellNr++)
            {
                // compute corresponding cell nr
                int cellx = blockx;
                int celly = blocky;
                if (cellNr==1) celly++;
                if (cellNr==2) cellx++;
                if (cellNr==3)
                {
                    cellx++;
                    celly++;
                }
 
                for (int bin=0; bin<gradientBinSize; bin++)
                {
                    float gradientStrength = descriptorValues[ descriptorDataIdx ];
                    descriptorDataIdx++;
 
                    gradientStrengths[celly][cellx][bin] += gradientStrength;
 
                } // for (all bins)
 
 
                // note: overlapping blocks lead to multiple updates of this sum!
                // we therefore keep track how often a cell was updated,
                // to compute average gradient strengths
                cellUpdateCounter[celly][cellx]++;
 
            } // for (all cells)
 
 
        } // for (all block x pos)
    } // for (all block y pos)
 
 
    // compute average gradient strengths
    for (int celly=0; celly<cells_in_y_dir; celly++)
    {
        for (int cellx=0; cellx<cells_in_x_dir; cellx++)
        {
 
            float NrUpdatesForThisCell = (float)cellUpdateCounter[celly][cellx];
 
            // compute average gradient strenghts for each gradient bin direction
            for (int bin=0; bin<gradientBinSize; bin++)
            {
                gradientStrengths[celly][cellx][bin] /= NrUpdatesForThisCell;
            }
        }
    }
 
 
    cout << "descriptorDataIdx = " << descriptorDataIdx << endl;
 
    // draw cells
    for (int celly=0; celly<cells_in_y_dir; celly++)
    {
        for (int cellx=0; cellx<cells_in_x_dir; cellx++)
        {
            int drawX = cellx * cellSize.width;
            int drawY = celly * cellSize.height;
 
            int mx = drawX + cellSize.width/2;
            int my = drawY + cellSize.height/2;
 
            rectangle(visual_image,
                      Point(drawX*scaleFactor,drawY*scaleFactor),
                      Point((drawX+cellSize.width)*scaleFactor,
                      (drawY+cellSize.height)*scaleFactor),
                      CV_RGB(100,100,100),
                      1);
 
            // draw in each cell all 9 gradient strengths
            for (int bin=0; bin<gradientBinSize; bin++)
            {
                float currentGradStrength = gradientStrengths[celly][cellx][bin];
 
                // no line to draw?
                if (currentGradStrength==0)
                    continue;
 
                float currRad = bin * radRangeForOneBin + radRangeForOneBin/2;
 
                float dirVecX = cos( currRad );
                float dirVecY = sin( currRad );
                float maxVecLen = cellSize.width/2;
                float scale = viz_factor; // just a visual_imagealization scale,
                                          // to see the lines better
 
                // compute line coordinates
                float x1 = mx - dirVecX * currentGradStrength * maxVecLen * scale;
                float y1 = my - dirVecY * currentGradStrength * maxVecLen * scale;
                float x2 = mx + dirVecX * currentGradStrength * maxVecLen * scale;
                float y2 = my + dirVecY * currentGradStrength * maxVecLen * scale;
 
                // draw gradient visual_imagealization
                line(visual_image,
                     Point(x1*scaleFactor,y1*scaleFactor),
                     Point(x2*scaleFactor,y2*scaleFactor),
                     CV_RGB(0,0,255),
                     1);
 
            } // for (all bins)
 
        } // for (cellx)
    } // for (celly)
 
 
    // don't forget to free memory allocated by helper data structures!
    for (int y=0; y<cells_in_y_dir; y++)
    {
      for (int x=0; x<cells_in_x_dir; x++)
      {
           delete[] gradientStrengths[y][x];            
      }
      delete[] gradientStrengths[y];
      delete[] cellUpdateCounter[y];
    }
    delete[] gradientStrengths;
    delete[] cellUpdateCounter;
 
    return visual_image;
 
}


저작자표시 비영리 (새창열림)

'Programming > OpenCV' 카테고리의 다른 글

jpeg 파일 디코딩하기.  (1) 2015.11.11
unsigned char* 형 버퍼를 IplImage 또는 Mat 으로 변환하기.  (0) 2014.08.18
[Function] 영상을 회전 시키기  (0) 2014.01.23
[Function] IplImage 에 한글text 삽입하기  (1) 2013.11.07
DC -> IplImage로 전환  (0) 2013.08.08
블로그 이미지

매직블럭

작은 지식들 그리고 기억 한조각

,

[Function] 영상을 회전 시키기

Programming/OpenCV 2014. 1. 23. 11:57




영상 처리를 하다보면 영상 회전이 필요할 경우가 많다. 


opencv의 워프어파인 변환 함수를 이용하여 영상을 회전하는 방법이다.


특수각일경우에 대한 추가 처리를 해주면 연산 속도는 조금 더 빨라진다.


이방법이 좋은 방법은 아니지만 간단하게 회전 영상을 구할때 사용하면 괜찮다.




  1. Mat RotateImage(Mat img, int angle, double x, double y)
  2. {
  3.         // 영상 중심기준 회전
  4.         //CvPoint2D32f center = cvPoint2D32f(img.cols/2, img.rows/2);
  5.        
  6.         // 사용자 지정위치 (x,y) 기준 회전
  7.         CvPoint2D32f center = cvPoint2D32f(x, y);
  8.         CvMat* rotation = cvCreateMat(2, 3 , CV_32FC1);
  9.         cv2DRotationMatrix(center, double(angle), 1.0, rotation);
  10.  
  11.         cvWarpAffine(&IplImage(img), &IplImage(img), rotation);
  12.  
  13.         cvReleaseMat(&rotation);
  14.  
  15.         return img;
  16. }


저작자표시 비영리 (새창열림)

'Programming > OpenCV' 카테고리의 다른 글

unsigned char* 형 버퍼를 IplImage 또는 Mat 으로 변환하기.  (0) 2014.08.18
[Function] HoG Destriptor in OpenCV  (0) 2014.01.27
[Function] IplImage 에 한글text 삽입하기  (1) 2013.11.07
DC -> IplImage로 전환  (0) 2013.08.08
cv::Mat Class 사용법  (0) 2013.05.06
블로그 이미지

매직블럭

작은 지식들 그리고 기억 한조각

,

[Function][MFC] CFileFind 를 이용하여 폴더내 모든파일 리스트박스에 추가하기

Programming/C, C++, MFC 2014. 1. 23. 11:45




CFileDialog 를 이용해서 ListBox 에 추가하는건 저번에 봤다.

[공부할것../C / C++ / MFC] - CFileDialog 를 이용하여 다중 파일 목록 작성

 

근데 이건 매번 파일을 선택해줘야 해서 귀찮다.

매번 폴더내에 존재하는 모든파일을 다 선택하고싶다던가 그런경우 사용가능한 방법

 

 

  1. CString tpath = _T("폴더 경로/*.*");
  2.        
  3. //검색 클래스
  4. CFileFind finder;
  5.        
  6. //CFileFind는 파일, 디렉터리가 존재하면 TRUE 를 반환함
  7. BOOL bWorking = finder.FindFile(tpath); //
  8.        
  9. CString fileName;
  10. CString DirName;
  11.        
  12. while (bWorking)
  13. {
  14.         //다음 파일 / 폴더 가 존재하면다면 TRUE 반환
  15.         bWorking = finder.FindNextFile();
  16.         //파일 일때
  17.         if (finder.IsArchived())
  18.         {
  19.                 //파일의 이름
  20.                 CString _fileName =  finder.GetFileName();
  21.  
  22.                 // 현재폴더 상위폴더 썸네일파일은 제외
  23.                 if( _fileName == _T(".") || 
                        _fileName == _T("..")|| 
                        _fileName == _T("Thumbs.db") ) continue;
  24.  
  25.                 fileName =  finder.GetFileTitle();
  26.                 m_ListBox.AddString(fileName);          
                    //읽어온 파일 이름을 리스트박스에 넣음
  27.         }
  28.         // 디렉터리 일때
  29.         //if (finder.IsDirectory())
  30.         //{
  31.                 // 필요하면 여기서 처리
  32.         //DirName = finder.GetFileName();
  33.         //}
  34. }
  35. return TRUE;

 

 

// 21.06.18. 수정

// 검색할 경로 및 파일
// 특정 확장자를 갖는 파일을 검색하고 싶으면 '경로/*.jpg' 등으로 사용
CString tpath = _T("폴더 경로/*.*");
       
// 검색 클래스
CFileFind finder;
       
// CFileFind는 파일, 디렉터리가 존재하면 TRUE 를 반환함
BOOL bWorking = finder.FindFile(tpath); //
       
CString fileName;
CString DirName;
       
while (bWorking)
{
        //다음 파일 or 폴더 가 존재하면다면 TRUE 반환
        bWorking = finder.FindNextFile();
        
		// folder 일 경우는 continue
		if (finder.IsDirectory() || finder.IsDot())
			continue;
			
		// 파일 일때
        
		//파일의 이름
		CString _fileName =  finder.GetFileName();

		// 현재폴더 상위폴더 썸네일파일은 제외
		if(_fileName == _T("Thumbs.db") ) continue;

		fileName =  finder.GetFileTitle();
		m_ListBox.AddString(fileName);          
		//읽어온 파일 이름을 리스트박스에 넣음
}

return TRUE;

 

저작자표시 비영리 (새창열림)

'Programming > C, C++, MFC' 카테고리의 다른 글

[Function][MFC] 폴더 내 파일 갯수 확인하기  (0) 2014.03.25
프로그램 실행시간을 측정 해 보자!  (0) 2014.02.12
[Function][MFC] CFileDialog 를 이용하여 다중 파일 목록 작성  (0) 2014.01.23
[Function][MFC] 폴더 경로 구하기 ( CString에 선택된 폴더의 절대경로를 저장하자 )  (0) 2014.01.23
프로그램 구동 속도 를 줄이는 방법!  (0) 2013.11.20
블로그 이미지

매직블럭

작은 지식들 그리고 기억 한조각

,

[Function][MFC] CFileDialog 를 이용하여 다중 파일 목록 작성

Programming/C, C++, MFC 2014. 1. 23. 09:43




CFileDialog 를 이용하여 파일의 확장자를 제외한 파일명만 가져오는 방법.


다양한 방법으로 수정 가능.



  1.         CString str = _T("All Files(*.*)|*.*|");        // 선택할 파일 종류
  2.         CString File, filem, strre;
  3.         CString strFileList;
  4.  
  5.         CFileDialog dlg(TRUE, NULL, NULL, OFN_ALLOWMULTISELECT, str, this);
  6.  
  7.         const int c_cMaxFiles = 20000 /*선택할 파일 숫자*/ ;     
                                    // 메모리 부족현상으로 확장 안해주면 몇개 못씀
  8.         const int c_cbBuffSize = (c_cMaxFiles * (MAX_PATH + 1)) + 1;
  9.         dlg.GetOFN().lpstrFile = strFileList.GetBuffer(c_cbBuffSize);
  10.         dlg.GetOFN().nMaxFile = c_cbBuffSize;
  11.  
  12.         if( dlg.DoModal() == IDOK)
  13.         {
  14.                 for(POSITION pos=dlg.GetStartPosition(); pos != NULL;)
  15.                 {
  16.                         // 전체삭제는 ResetContent
  17.                         File = dlg.GetNextPathName(pos);
  18.  
  19.                         filem = File.Right( File.GetLength()-File.ReverseFind( _T('\\') )-1 );
  20.                         // 경로를 제외한 파일명       
  21.                        
  22.                         filem = filem.Left( filem.GetLength() - 4 );
  23.                         // 확장자 제거 ( ex - .jpg )
  24.  
  25.                         m_ListBox.AddString( filem );
  26.                 }
  27.  
  28.  
  29.         }
  30.  
  31.         m_nFileCnt = m_ListBox.GetCount();
  32.         strre.Format( _T("%dea load"), m_nFileCnt );
  33.         AfxMessageBox( strre );


저작자표시 비영리 (새창열림)

'Programming > C, C++, MFC' 카테고리의 다른 글

프로그램 실행시간을 측정 해 보자!  (0) 2014.02.12
[Function][MFC] CFileFind 를 이용하여 폴더내 모든파일 리스트박스에 추가하기  (18) 2014.01.23
[Function][MFC] 폴더 경로 구하기 ( CString에 선택된 폴더의 절대경로를 저장하자 )  (0) 2014.01.23
프로그램 구동 속도 를 줄이는 방법!  (0) 2013.11.20
LPCSTR / LPCTSTR / const char* / CString 등등 문자열 형  (0) 2013.11.11
블로그 이미지

매직블럭

작은 지식들 그리고 기억 한조각

,

[Function][MFC] 폴더 경로 구하기 ( CString에 선택된 폴더의 절대경로를 저장하자 )

Programming/C, C++, MFC 2014. 1. 23. 09:37




폴더브라우저를 띄워 선택된 폴더의 절대경로를 반환 받는 방법.





  1.         ITEMIDLIST  *pidlBrowse;
  2.         TCHAR        pszPathname[MAX_PATH];
  3.         BROWSEINFO  BrInfo;
  4.  
  5.         BrInfo.hwndOwner = GetSafeHwnd();
  6.         BrInfo.pidlRoot = NULL;
  7.         memset( &BrInfo, 0, sizeof(BrInfo) );
  8.  
  9.         BrInfo.pszDisplayName = (LPWSTR)pszPathname;
  10.  
  11.         BrInfo.lpszTitle = L"폴더를 선택해 주십시오.";
  12.         BrInfo.ulFlags = BIF_RETURNONLYFSDIRS;
  13.  
  14.         // 다이얼로그 띄우기
  15.         pidlBrowse = SHBrowseForFolder(&BrInfo);
  16.  
  17.         if( pidlBrowse != NULL)
  18.         {
  19.                 // 선택한 폴더경로를 얻어옴
  20.                 BOOL bSuccess = ::SHGetPathFromIDListW(pidlBrowse, pszPathname);
  21.  
  22.                 if ( bSuccess )
  23.                 {
  24.                         m_SelectedFolder = pszPathname;   //<-- 여기서 값을 입력
  25.                         UpdateData(FALSE);
  26.                 }
  27.                 else
  28.                 {
  29.                         MessageBox(L"잘못된 폴더명입니다.", L"", MB_OKCANCEL|MB_ICONASTERISK );
  30.                 }
  31.         }


저작자표시 비영리 (새창열림)

'Programming > C, C++, MFC' 카테고리의 다른 글

[Function][MFC] CFileFind 를 이용하여 폴더내 모든파일 리스트박스에 추가하기  (18) 2014.01.23
[Function][MFC] CFileDialog 를 이용하여 다중 파일 목록 작성  (0) 2014.01.23
프로그램 구동 속도 를 줄이는 방법!  (0) 2013.11.20
LPCSTR / LPCTSTR / const char* / CString 등등 문자열 형  (0) 2013.11.11
UpdateData() 함수에 대한것들  (0) 2013.11.11
블로그 이미지

매직블럭

작은 지식들 그리고 기억 한조각

,

[matlab] mfile을 이용하여 function을 만들어보자.

Programming/Matlab 2014. 1. 16. 17:30





프로그래밍의 기초가 되는 함수를 작성하는 방법이다.


matlab의 함수나 프로그램들은 전부다 mfile 이란 것을 이용하여 작성되고 불려져서 사용된다.


새로운 mfile을 만들기 위해 좌측 상단의 New Script 버튼을 누르면 새로운 스크립트를 작성할 수 있는


빈 창이 뜬다.


이제부터 함수나 프로그램의 flow는 이 스크립트 창에서 작성되고 저장되어 진다.





워낙 간단한 기초만 설명하고 있어서 위의 사진 한장으로 모든것이 이해 되겠지만 살짝 집고 가자.


matlab 에서 함수의 선언은 아래와 같은 형태로 한다.


function [출력변수] = 함수이름(입력변수)


주의할점은 출력변수는 대괄호사이에 작성하고 입력변수는 소괄호 사이에 작성한다는 점이다.


함수선언 위에 삽입되는 annotation은 help명령어로 해당 함수를 불렀을때 출력되는 


해당 함수에 대한 요약문이다.


이 글을 작성하다 새로 알게된 사실인데 함수선언 위에 설명문이 여러 문단으로 작성 될 경우


가장 첫번째 문단만이 출력된다.


함수의 내용은 각자 필요에 따라 작성하되 내부에서 입력변수 를 이용하여 출력변수에 대입만 해주면 된다.


위에서는 간단하게 숫자 두개를 입력받아서 더한 결과를 출력해 주는 함수를 작성하였다.


입력값에 대한 예외처리는 생략하기로 한다.


함수를 다 작성한후 저장을 누르면 파일명은 함수명이 Default로 설정 된다.



이렇게 작성된 함수는 다른 mfile 이나 Command Window 에서 사용이 가능하다 .


사용법은 C 에서 사용하던것과 동일하다.



A 와 B 에 각각 3과 4를 입력받아 함수에 대입하고 결과값으로 7을 return 받은 모습을 확인할 수 있다.


저작자표시 비영리 (새창열림)

'Programming > Matlab' 카테고리의 다른 글

plot 관련 명령어 모음.  (0) 2014.04.13
Matlab을 이용한 영상처리 / 영상처리를 위한 Matlab Function  (2) 2014.01.08
Matlab 에서 사용되는 주요 함수 모음.  (0) 2013.12.31
블로그 이미지

매직블럭

작은 지식들 그리고 기억 한조각

,

[Function] IplImage 에 한글text 삽입하기

Programming/OpenCV 2013. 11. 7. 20:50




//========= header 에 추가 =========================


void setPutText( IplImage* src_image, IplImage* dst_image, char* text, CvPoint textPos, CvScalar color);

HBITMAP setTextToBitmap( char* text, CvScalar color);

IplImage* setBitmapToIplImage( HBITMAP hBitmap );



//========== 소스코드 ===============================



void CbrailleDlg::setPutText(IplImage* src_image, IplImage* dst_image, char* text, CvPoint textPos, CvScalar color)

{

// 명암도 영상에 대한 처리는 안함 칼라만 처리 일단..


if( src_image->nChannels != 1 )

cvCopy( src_image, dst_image );


int width = src_image->width;

int height = src_image->height;


if( (textPos.y > src_image->height) || (textPos.x > src_image->width) )

{

cvCopy( src_image, dst_image );

}


CvScalar var = {0,0,0,0};

HBITMAP hBitmap = setTextToBitmap(text, color);

IplImage* text_image = setBitmapToIplImage( hBitmap );


for( int nRow = textPos.y; nRow<(textPos.y + text_image->height); nRow++)

{

for( int nCol = textPos.x; nCol<(textPos.x + text_image->width); nCol++)

{

if( nRow >= height || nCol >= width) continue;

var = cvGet2D(text_image, nRow-textPos.y, nCol-textPos.x);


if( var.val[0] == color.val[0] && var.val[1] == color.val[1] && var.val[2] == color.val[2] )

cvSet2D(dst_image, nRow, nCol, var);

}

}


free(text_image->imageData);

cvReleaseImage( &text_image );

DeleteObject( hBitmap );

}



HBITMAP CbrailleDlg::setTextToBitmap( char* text, CvScalar color)

{

int textLength = (int)strlen(text);


if( textLength <= 0 ) return NULL;


HDC hTextDC = CreateCompatibleDC(NULL);


HFONT hOldFont = (HFONT)SelectObject( hTextDC, (HFONT)GetStockObject(SYSTEM_FONT) );

HBITMAP hDstBMP = NULL;


RECT textArea = {0, 0, 0, 0};


DrawText(hTextDC, (LPCTSTR)text, textLength, &textArea, DT_CALCRECT);


if( (textArea.right > textArea.left) && (textArea.bottom > textArea.top) )

{

BITMAPINFOHEADER bitmapInfoHeader;


memset( &bitmapInfoHeader, 0x0, sizeof(BITMAPINFOHEADER) );


void* lpvBits = NULL;


bitmapInfoHeader.biSize = sizeof(bitmapInfoHeader);

bitmapInfoHeader.biWidth = textArea.right-textArea.left;

bitmapInfoHeader.biHeight = textArea.bottom-textArea.top;

bitmapInfoHeader.biPlanes = 1;

bitmapInfoHeader.biBitCount = 32;

bitmapInfoHeader.biCompression = BI_RGB;


hDstBMP = CreateDIBSection( hTextDC, (LPBITMAPINFO)&bitmapInfoHeader, 0, (LPVOID*)&lpvBits, NULL, 0 );


HBITMAP hOldBMP = (HBITMAP)SelectObject( hTextDC, hDstBMP );


if( hOldBMP != NULL)

{

int TEXT_RED = (int)color.val[2];

int TEXT_GREEN = (int)color.val[1];

int TEXT_BLUE = (int)color.val[0];


SetTextColor( hTextDC, RGB(TEXT_RED, TEXT_GREEN, TEXT_BLUE) ); //text color


SetBkColor( hTextDC, 0x00EFFEFF ); //Background color


SetBkMode( hTextDC, OPAQUE ); // 투명


DrawText( hTextDC, (LPCTSTR)text, textLength, &textArea, DT_NOCLIP);

}

::SelectObject( hTextDC, hOldBMP );

}

::SelectObject( hTextDC, hOldFont );


if( hTextDC) { ::DeleteDC( hTextDC ); }

if( hOldFont) { ::DeleteObject( hOldFont ); }


return hDstBMP;

}



IplImage* CbrailleDlg::setBitmapToIplImage( HBITMAP hBitmap )

{

BITMAP bitmap;


GetObject( hBitmap, sizeof( BITMAP ), (LPSTR)&bitmap );


int nChannels = (bitmap.bmBitsPixel == 1)? 1: bitmap.bmBitsPixel*0.125;

int depth = (bitmap.bmBitsPixel == 1)? IPL_DEPTH_1U : IPL_DEPTH_8U;


IplImage* mImage = cvCreateImageHeader( cvSize(bitmap.bmWidth, bitmap.bmHeight), depth, nChannels );


mImage->imageData = (char*)malloc(bitmap.bmHeight * bitmap.bmWidth * nChannels * sizeof(char) );


memcpy(mImage->imageData, (char*)(bitmap.bmBits), bitmap.bmHeight * bitmap.bmWidth * nChannels );


cvFlip( mImage, mImage, 0 );


return mImage;

}


//================사용 예 ==========================

CString str;

str.Format( _T("한글") );

setPutText( &IplImage(m_Image), &IplImage(m_Image), (LPSTR)(LPCTSTR)str, cvPoint(10,10), CV_RGB(255,255,100) ); 

저작자표시 비영리 (새창열림)

'Programming > OpenCV' 카테고리의 다른 글

[Function] HoG Destriptor in OpenCV  (0) 2014.01.27
[Function] 영상을 회전 시키기  (0) 2014.01.23
DC -> IplImage로 전환  (0) 2013.08.08
cv::Mat Class 사용법  (0) 2013.05.06
OpenCV 주요함수  (0) 2013.04.29
블로그 이미지

매직블럭

작은 지식들 그리고 기억 한조각

,

CFileDialog 다중파일 선택하기

Programming/C, C++, MFC 2013. 6. 14. 10:57








CFileDialog를 이용하여 다중 파일을 선택하는 방법..

다중파일 선택하는 방법만 많이 나와있지 여러개 선택할때 14개 이상 선택이 안되던 내 버그에 대한글을

찾는것은 쉽지 않았다.. 


결론은 메모리문제.. 메모리문제를 해결하기위한 코드를 추가한 방법이다.

선택된 파일을 리스트박스에 추가해준다.


-----------------------------------------------------------------------------------------------


CString str = _T("JPEG(*.jpg)|*.jpg|"); // 선택할 파일 종류

CString File;

CString strFileList; 


CFileDialog dlg(TRUE, NULL, NULL, OFN_ALLOWMULTISELECT, str, this);


const int c_cMaxFiles = 400 /*선택할 파일 숫자*/ ; // 메모리 부족현상으로 확장 안해주면 몇개 못씀

const int c_cbBuffSize = (c_cMaxFiles * (MAX_PATH + 1)) + 1;

dlg.GetOFN().lpstrFile = strFileList.GetBuffer(c_cbBuffSize);

dlg.GetOFN().nMaxFile = c_cbBuffSize;


if( dlg.DoModal() == IDOK)

{

for(POSITION pos=dlg.GetStartPosition(); pos != NULL;)

{

// 전체삭제는 ResetContent

File = dlg.GetNextPathName(pos);

m_TrainingList.AddString(File);

}

}




저작자표시 (새창열림)

'Programming > C, C++, MFC' 카테고리의 다른 글

GetDlgItem() 함수를 이용하기  (0) 2013.07.03
Memory Leaks 어디서 누수가 일어나는지 잡아보자..  (0) 2013.07.01
#define 에 관한 내용  (0) 2013.06.07
MFC TabControl 사용법  (2) 2013.04.30
MFC Picture Control 에 BMP 파일 출력하기  (1) 2013.04.02
블로그 이미지

매직블럭

작은 지식들 그리고 기억 한조각

,

[Function] dialog 에 FPS 표시하기

Programming/C, C++, MFC 2013. 4. 2. 19:22




1초마다 fps 가 갱신되게 할것인지 매 프레임마다 갱신되게 할 것인지는

if문을 약간만 바꾸면 가능하다

 

//헤더파일에 선언되어야 할 멤버변수

DWORD m_dwFrames;
DWORD m_dwCurrentTime;
DWORD m_dwLastUpdateTime;
DWORD m_dwElapsedTime;
DWORD m_dwSpeechTime;
TCHAR m_szFPS[32];

 

 

//cpp파일에서 실행할 부분
m_dwCurrentTime = GetTickCount(); // Even better to use timeGetTime()
m_dwElapsedTime = m_dwCurrentTime - m_dwLastUpdateTime;
m_dwFrames++;

if(m_dwElapsedTime >= 1000){
 wsprintf(m_szFPS, _T("FPS = %u"), (UINT)(m_dwFrames * 1000.0 / m_dwElapsedTime));
 m_dwFrames = 0;
 m_dwLastUpdateTime = m_dwCurrentTime;
}
  
m_ctrlFps.SetWindowTextA(m_szFPS);
UpdateData(FALSE);

'Programming > C, C++, MFC' 카테고리의 다른 글

#define 에 관한 내용  (0) 2013.06.07
MFC TabControl 사용법  (2) 2013.04.30
MFC Picture Control 에 BMP 파일 출력하기  (1) 2013.04.02
MFC 에서 wav 파일 재생하기  (1) 2013.04.02
Debug 용 Console 창 생성하기  (0) 2013.04.02
블로그 이미지

매직블럭

작은 지식들 그리고 기억 한조각

,

[Function] FindContour 덩어리 찾기

Programming/OpenCV 2013. 4. 2. 19:21




contour 를 찾는 함수..

여기에 seq 와 storage 의 개념이 아직 부족하다.. 다시 한번 봐야되는데.

 

 CvMemStorage* storage_con = cvCreateMemStorage(0);
 CvSeq* seq = NULL;
 CvSeq* seq_dp = NULL;
 int number_of_contour = cvFindContours(gray, storage_con, &seq, sizeof(CvContour), 2, 2);
  if(number_of_contour !=0)
  {
   cvDrawContours(image, seq_dp, color_ex1, color_in, CV_FILLED, 3);
  }

'Programming > OpenCV' 카테고리의 다른 글

OpenCV 를 이용하여 동영상 재생하기.  (0) 2013.04.26
Haar Face Detection  (0) 2013.04.02
Duglas Puecker 외곽선 근사화  (0) 2013.04.02
[Function] Dialog 창에 IplImage 출력하기  (0) 2013.04.02
[Function] Convex Hull 최외곽선 검출하기  (3) 2013.04.02
블로그 이미지

매직블럭

작은 지식들 그리고 기억 한조각

,

[Function] Dialog 창에 IplImage 출력하기

Programming/OpenCV 2013. 4. 2. 19:15




전에 어느분 블로그에서 받은 소스인데 간단하게 위치만 수정해서 사용중이다

void C프로젝트명Dlg::displayIplImage(IplImage* pimageIpl, int ww, int hh)
{
 int w,h;
 int nWidth= pimageIpl->width;
 int nHeight = pimageIpl->height;

 BYTE* pSrcBits = (BYTE*)pimageIpl->imageData;
 BYTE* pBmpBits = (BYTE*)calloc(sizeof(BYTE), nWidth*nHeight*4);

 CClientDC dc(this);
 CDC memDC;
 CBitmap newBmp, *pOldBmp;

 for(h=0; h<nHeight; h++)
 {
  BYTE* pSrc = pSrcBits + pimageIpl->widthStep * h;
  BYTE* pDst = pBmpBits + nWidth * 4 * h;
  for(w=0; w<nWidth; w++)
  {
   *(pDst++) = *(pSrc++);
   *(pDst++) = *(pSrc++);
   *(pDst++) = *(pSrc++);
   *(pDst++) = 0;
  }
 }
 memDC.CreateCompatibleDC(&dc);
 newBmp.CreateCompatibleBitmap(&dc, nWidth, nHeight);
 newBmp.SetBitmapBits(nWidth*nHeight*4, pBmpBits);

 pOldBmp = memDC.SelectObject(&newBmp);
 dc.BitBlt(ww,hh,nWidth, nHeight, &memDC, 0, 0, SRCCOPY);
 memDC.SelectObject(pOldBmp);

 free(pBmpBits);
 memDC.DeleteDC();
 newBmp.DeleteObject();
 
}

'Programming > OpenCV' 카테고리의 다른 글

OpenCV 를 이용하여 동영상 재생하기.  (0) 2013.04.26
Haar Face Detection  (0) 2013.04.02
[Function] FindContour 덩어리 찾기  (0) 2013.04.02
Duglas Puecker 외곽선 근사화  (0) 2013.04.02
[Function] Convex Hull 최외곽선 검출하기  (3) 2013.04.02
블로그 이미지

매직블럭

작은 지식들 그리고 기억 한조각

,

[Function] Convex Hull 최외곽선 검출하기

Programming/OpenCV 2013. 4. 2. 19:12




 

convex hull 이란?

여러개의 점들중에 최외곽의 점들을 이어놓은 집합? 연결된 선? 공간? 을 의미한다

convexhull 영역 내부에 모든 점이 존재하고 외부에는 점이 존재하지 않아야 한다.

 

 

  1. CvMemStorage* storage_hull = cvCreateMemStorage(0);
  2.  
  3. IplImage* cnt_img = cvCreateImage(cvGetSize(image), IPL_DEPTH_8U, 1);
  4. cvZero( cnt_img );
  5.  
  6. CvPoint pt0;
  7. CvSeq* ptseq = cvCreateSeq(CV_SEQ_KIND_GENERIC|CV_32SC2,sizeof(CvContour),sizeof(CvPoint), storage_hull);
  8. CvSeq* hull;
  9. int         hullcount = 0;
  10. int         count_ = 0;
  11.  
  12. for(int i=0; i<image->height; i++)
  13. {
  14.         for(int j=0; j<image->width; j++)
  15.         {
  16.                 if((unsigned char)image->imageData[i*image->widthStep+j*3]==255)
  17.                 {
  18.                         pt0.x = j;
  19.                         pt0.y = i;
  20.                         cvSeqPush(ptseq, &pt0);
  21.                 }
  22.         }
  23. }
  24.  
  25. if(ptseq->total != 0)
  26. {
  27.         hull = cvConvexHull2(ptseq, 0, CV_COUNTER_CLOCKWISE, 0);
  28.         hullcount = hull->total;
  29.         cvZero(cnt_img);
  30.  
  31.         pt0 = **CV_GET_SEQ_ELEM(CvPoint*, hull, hullcount - 1);
  32.         for(int i=0; i<hullcount; i++)
  33.         {
  34.                 CvPoint pt = **CV_GET_SEQ_ELEM(CvPoint*, hull, i);
  35.                 cvLine(image, pt0, pt, CV_RGB(0, 255, 0));
  36.                 //cvLine(image, CvPoint(cvPoint(center_x,center_y)), pt, CV_RGB(255, 0, 0));
  37.                 pt0 = pt;
  38.         }
  39.  
  40. }


소스코드 보기좋게 수정하였습니다. ( 14.04.08 )

'Programming > OpenCV' 카테고리의 다른 글

OpenCV 를 이용하여 동영상 재생하기.  (0) 2013.04.26
Haar Face Detection  (0) 2013.04.02
[Function] FindContour 덩어리 찾기  (0) 2013.04.02
Duglas Puecker 외곽선 근사화  (0) 2013.04.02
[Function] Dialog 창에 IplImage 출력하기  (0) 2013.04.02
블로그 이미지

매직블럭

작은 지식들 그리고 기억 한조각

,
  • «
  • 1
  • »

카테고리

  • 살다보니.. (449)
    • 주절거림 (3)
    • 취미생활 (36)
      • 지식과 지혜 (3)
      • 풍경이 되어 (4)
      • Memories (17)
      • 엥겔지수를 높여라 (2)
    • mathematics (6)
      • Matrix Computation (2)
      • RandomProcesses (3)
    • English.. (8)
    • Programming (147)
      • C, C++, MFC (51)
      • C# (1)
      • OpenCV (17)
      • Python (58)
      • Git, Docker (3)
      • Matlab (4)
      • Windows (3)
      • Kinect V2 (2)
      • 기타 etc. (8)
    • 전공관련 (80)
      • Algorithm (6)
      • Deep Learning (54)
      • 실습 프로그램 (4)
      • 주워들은 용어정리 (8)
      • 기타 etc. (8)
    • Computer (118)
      • Utility (21)
      • Windows (31)
      • Mac (4)
      • Ubuntu, Linux (58)
      • NAS (2)
      • Embedded, Mobile (2)
    • IT, Device (41)
      • 제품 사용기, 개봉기 (14)
      • 스마트 체험단 신청 (27)
    • Wish List (3)
    • TISTORY TIP (5)
    • 미분류. 수정중 (1)

태그목록

  • DeepLearning
  • 매트랩
  • 후쿠오카
  • 포르투갈
  • 딥러닝
  • Computer Tip
  • LIBSVM
  • 에누리닷컴
  • 일본
  • 큐슈
  • 스마트체험단
  • portugal
  • 크롬
  • DSLR
  • 매트랩 함수
  • CStdioFile
  • random variable
  • matlab function
  • 오봉자싸롱
  • SVM
  • Deep Learning
  • review
  • Convolutional Neural Networks
  • 갤럭시노트3
  • ColorMeRad
  • matlab
  • ReadString
  • utility
  • 칼로리 대폭발
  • function

달력

«   2025/06   »
일 월 화 수 목 금 토
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
06-11 07:21

LATEST FROM OUR BLOG

RSS 구독하기

BLOG VISITORS

  • Total :
  • Today :
  • Yesterday :

Copyright © 2015 Socialdev. All Rights Reserved.

티스토리툴바