Raphael Click 및 Mouse Over Event Test

6월 12, 2017 Typescript No comments

Raphael을 사용하여 Circle 그리기

for(var i=0; i<10; i++) 
{ 
    paper = Raphael(0, 0, 500, 500); 
    var circle = paper.circle(50, i*50, width); 
}

출력화면

circle_1

여기서 circle에 click 및 mouse over event 연동 추가


    circle .click(function(this : any){
        this.attr({fill : '#0F0'});
    })

    circle.mouseover(function(this : any){  
        this.attr({fill : '#F00'});
    })

이때, 문제 발생

  1. Mouse Click 및 Over Event가 Random하게 인식되는 현상.
  2. 한번 전체적으로 Mouse Over를 통해 인식된 이후 부터는 정상 인식되는 현상

원인 ㅡㅡ;

최초 circle의 attribute가 없어서 line으로만 인식,,,…..ㅡㅡ;;;

최초 circle 생성시

attr({fill : '#000'})

추가 후 정상적으로 잘 작동 됨

‘this’ implicitly has type ‘any’ because it does not have a type annotation.

6월 12, 2017 Typescript No comments

‘this’ implicitly has type ‘any’ because it does not have a type annotation.

raphael의 element에 click시 event 연동 구현시 위와 같은 error 발생

click시 event 구현 code는 아래 처럼

this.ele.click(function(){
    console.log("test click::x=%d, y=%d", x, y);
    this.attr({fill : '#0F0'});
})

click event 첫번째 parameter로 element를 전달하기에 this를 any로 명시 필요


this.ele.click(function(this : any){
    console.log("test click::x=%d, y=%d", x, y);
    this.attr({fill : '#0F0'});
})

위와 같이 수정 후 해결

Webpack 수행시 ‘Module not found : Error : Can’t resolve …’ error

6월 7, 2017 Typescript No comments

Typesciprt class를 Import시 ‘Module not found : Error…’ 발생 해결

  1. 아래와 같은 DSButton이라는 class를 export
    export class DSButton {
        x : number = 0;
        y : number = 0;
        width : number = 0;
        height : number = 0;
    
        constructor(x:number, y:number, width:number, height:number){
            this.x = x;
            this.y = y;
            this.width = width;
            this.height = height;
        }
    
        ToString() {
            return "x=" + this.x + ", y=" + this.y + ", width=" + this.width + ", height=" + this.height;
        }
    }
    
  2. app.ts에서 DSButton을 사용하는 sample 작성
    import { DSButton } from './DSButton'
    
    let button : DSButton;
    button = new DSButton(0, 0, 100, 200);
    console.log('button.ToString()=' + button.ToString()); 
    
  3. webpack.config.json에 entry를 app.ts로 설정 하고 awesome-typescript-loader를 설정
    module.exports = {
      entry: './app.ts',
      output: {
        path: __dirname + '/build',
        filename: 'bundle.js'
      },
    
      module: {
            loaders: [
                // All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'.
                { test: /\.tsx?$/, loader: "awesome-typescript-loader" },
    
                // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
                { enforce: "pre", test: /\.js$/, loader: "source-map-loader" }
            ]
      }          
    };
    
  4. webpack을 bundle수행시 DSButton module을 찾을 수 없다는 Error 발생webpack_error
  5. webpack.config.json 파일에 resolve : extensions:['.ts'] 추가
    resolve: {
        extensions: ['.ts']
      }
    
  6. 정상 bundle 및 정상 출력 됨

외부 Javascript module 사용

6월 1, 2017 Typescript No comments

Typescript를 시작하고, 처음부터 맨붕이 왔던것은 Javascript에서 module 방식을 지원하지 않다보니, 그에 대한 대체 수단에 대한 개념 잡기가 쉽지 않음

외부 Javascript Module 사용

  1. Raphael JS (http://dmitrybaranovskiy.github.io/raphael) 를 Typescript에서 사용하여 원 그리기 예제 시작
  2. npm을 통해 Raphael JS 설치 하기
    $ npm install --save raphael
    
  3. test_raphael.ts source 상단에 raphael module Import 추가Javascript library를 직접 사용하려고 하기에 npm에서 설치된 경로의 .js 파일을 직접 입력
    import raphael = require('./node_modules/raphael/raphael.js');
    
  4. 간단한 Circle을 그리는 source 추가
    var paper = raphael(0, 0, 200, 200); var circle = paper.circle(100, 100, 50);
    
    circle.attr({
     'fill' : '#00f',
     'stroke':'#000',
     'stroke-width':5
    });
    
  5. 테스트 삼아서 Typescript build 해보자. 안된다.~!!! ㅡㅡ; Build Error!!다행히 친절히 설명해 준다.
    $ tsc -p .
    test_raphael.ts(1,26): error TS6143: Module './node_modules/raphael/raphael.js' was resolved to '/home/ubuntu/workspace/node_modules/raphael/raphael.js', but '--allowJs' is not set.
    

    tsconfig.json 파일에 allowjs : true를 설정 해주고 다시 build시 또 Error!!

    $ tsc -p .
    error TS5055: Cannot write file '/home/ubuntu/workspace/node_modules/raphael/raphael.js' because it would overwrite input file.
    
  6. .ts source 폴더와 output .js 폴더가 동일해서 발생…;; 단지 tsconfig.json에서 "outDir" : "build"로 변경 시 정상 수행 됨
  7. 해당 test_raphael.js source를 index.html에 포함한후 apache server에서 구동시 raphael not define이라는 error가 발생 됨 이는 raphael.js 파일을 Front End단에서는 찾을 수가 없기에 발생
    그렇기에 bundle 형태로 관련 javascript파일을 자동으로 뭉쳐주는 webpack을 사용하여 packaging 해주어야 함.
  8. 당연히 npm을 사용하여 webpack을 설치. 원하는 데이터 형태를 bundle해 줄수 있는 loader를 선택하여 설치 Typescript는 awesome-typescript-loader, source-map-loader를 설치
    $npm install --save webpack awesome-typescript-loader source-map-loader
    
  9. webpack.config.js 파일을 생성 하여 아래 code 추가
    entry : Bundle을 시작할 시작 source file을 설정
    output에 최종 bundle후 export되는 file 설정
    module에 원하는 loader 설정

    module.exports = {
      entry: './test_raphael.ts',
      output: {
        path: __dirname,
        filename: 'bundle.js'
      },
    
      module: {
            rules: [
                // All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'.
                { test: /\.tsx?$/, loader: "awesome-typescript-loader" },
    
                // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
                { enforce: "pre", test: /\.js$/, loader: "source-map-loader" }
            ]
      },
    };
    
  10. webpack을 실행하여 bundle 수행
    $webpack
    

    참고로 webpack –watch 수행시 source가 변경시 자동 build됨

  11. index.html 생성 webpack을 통해 최종 build된 bundle.js를 포함
      &lt;html&gt;
            &lt;head&gt;
            &lt;/head&gt;
    
            &lt;body&gt;
                &lt;script type="text/javascript" src="bundle.js"&gt;
                &lt;/script&gt;
    
                Test raphael.js
            &lt;/body&gt;
        &lt;/html&gt;
    
  12. 결과 화면
    output_raphael

Typescript 환경 구축

5월 31, 2017 Typescript No comments

Typescript 최초 시작

  1. npm을 통해서 typescript설치 (tsd도 같이 설치 : TypeScript Definition Manager)

    c:\Test&gt;npm install -g typescript tsd
    
  2. greeter.ts라는 typescript source file생성

    function greeter(person : string){
        return "Hello, " + person;
    }
    var user = 123;
    document.body.innerHTML = greeter(user);
    
  3. 확장자 ts를 tsc를 이용하여 compile

    c:\test&gt;tsc greeter.ts
    
  4. 최종 js 파일로 결과 출력

npm init을 통한 package 초기화 수행

$npm init
  • 자동으로 package.json 파일 생성 그 이후

    $npm install –save typescript

package.json 샘플

{
  "name": "typescript_test",
  "version": "1.0.0",
  "description": "test",
  "main": "index.html",
  "scripts": {
    "build": "echo build",
    "start": "echo test",
    "test": "echo \"Error: no test specified\" &amp;&amp; exit 1"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/scanhand/TypeScript_Test.git"
  },
  "author": "scanhand",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/scanhand/TypeScript_Test/issues"
  },
  "homepage": "https://github.com/scanhand/TypeScript_Test#readme",
  "dependencies": {
    "raphael": "^2.2.7",
    "tsd": "^0.6.5",
    "typescript": "^2.3.3"
  }
}

위와같이 –save를 설정시 package.json 파일에 자동 저장됨

typescript 초기화

$ tsc --init

수행시 자동으로 tsconfig.json 파일 생성됨

    {
      "compilerOptions": {
        /* Basic Options */                       
        "target": "es5",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'. */
        "module": "commonjs",                     /* Specify module code generation: 'commonjs', 'amd', 'system', 'umd' or 'es2015'. */    
        "allowJs": true,                       /* Allow javascript files to be compiled. */    
        "sourceMap": true,                     /* Generates corresponding '.map' file. */    
        "outDir": "build",                        /* Redirect output structure to the directory. */          
        /* Strict Type-Checking Options */        
        "strict": true                            /* Enable all strict type-checking options. */

      },
      "files" : [
        "test_raphael.ts"
      ]
    }

Typescript 시작

5월 31, 2017 Typescript No comments

항상 web application을 해야지 생각만 했었는데 지금 부터 맨땅에 해딩하기 시작 함. (앞으로 post는 순서 및 내용이 뒤죽박죽 할 예정)

  • AngularJs에서도 사용하고, Microsoft에서도 밀고 있는 Typescript로 접근해 보기 시작.

  • 처음 작업환경은 Local Computer에서 npm을 이용해서 환경 설정하고 작업 하기 시작.

  • 하지만, 작업 computer가 바뀌는 경우, 특히 집과 회사를 오가면서 같은 작업 반복시 github만 가지고는 조금 애매해 지기 시작함

  • 그러다 우연히 찾은 c9(https://c9.io)을 작업 환경으로 사용하기 시작

  • 작업 환경이 SublimeText와 느낌이 비슷하고, linux shell도 제공해주고, 무엇보다 virtual machine을 활용하여, 나만의 작업 환경을 그대로 유지하는게 참 좋음 (특히 무료!!!)

c9_ui

VOI

7월 27, 2016 DICOM No comments

VOI (Values of Interest)

WWL과 같이 Pixel Data를 원하는 LUT를 적용하여 사용자가 좀 더 영상을 다양하게 보는 방법을 제공 합니다.

그중에 최종단의 LUT역활을 하는것이 VOI LUT입니다.

이외에도 Modality LUT, Presentation LUT와 같이 다양하게 적용됩니다. 아래 이미지를 참고해 주세요.

voi_sequence

우선 VOI LUT Modlue Attriutes라고 하여 VOI와 관련된 Group이 있습니다.

Group ID 0028로 여기에 Window Center(0028,1050), Window Width(0028,1051도 포함되어 있습니다.

그리고 VOI LUT Function(0028,1056)에서 WWL Window가 Linear Function인지 Sigmoid Function인지 구분해 줍니다.

Linear Function인 경우DICOM Standard에는

if (x <= c - 0.5 - (w-1) /2), then y = ymin
else if (x > c - 0.5 + (w-1) /2), then y = ymax
else y = ((x - (c - 0.5)) / (w-1) + 0.5) * (ymax- ymin) + ymin

위와 같이 구현 되고,

Sigmoid Function인 경우 아래 식으로 DICOM Standard에 나와 있습니다.

sigmoid_expression

where
IN
is the input value of the LUT (i.e., the output of the (conceptual) Modality LUT).
WC
is the Window Center defined interactively by the user or by using the values provided in (0028,1050).
WW
is the Window Width defined interactively by the user or by using the values provided in (0028,1051).
Output_range
is the maximum output value (see Note below on encoding depth)

아래는 VOI LUT Sequence Group의 DICOM Standard의 내용 입니다.

voi_table

LUT Descriptor(0028,3002)에서 LUT Data(0028,3003)의 형태를 정의하고 실제 Data는 LUT Data(0028,3003)에 저장 되게 됩니다.

LUT Explanation은 그냥 VOI LUT의 Text 설명이 포함 됩니다.

monochrome

7월 27, 2016 DICOM No comments

DICOM Image의 Pixel Data에 실제 Image Raw Data가 저장 됩니다.

이때 저장되는 Raw Data의 Type을 결정해 주는 한가지 element가 Photometric Interpratation (0028,0004) 입니다.

tag (0028, 0004)에 RGB 값인경우 Pixel Data에는 RGB 형태로 저장되어 있다는 것을 명시 합니다.

CR Image에서는 MONOCHROME1 or MONOCHROME2 로 저장 되어 있습니다.

Grayscale Image 라고 생각 하시면 됩니다.

monochrome2

MONOCHROME1MONOCHROME2의 차이점은 MONOCHROME2는 Pixel Data의 가장 큰 값을 흰색으로 표시하고,

MONOCHROME1은 가장 큰 값을 검정색으로 표시합니다. 즉 MONOCHROME1은 기존에 보던 Image의 반전 된 영상이라고 생각하시면 됩니다.

monochrome1

ES ImageSecondary Capture와 같은 DICOM중 PALETTE COLOUR형태도 있습니다. Bitmap의 Pallete 형태와 동일하다고 생각하시면 됩니다.

해당 Palette Table은 Red, Green, Blue Palette Color Lookup Table Descriptor (0028,1101~1103)을 참조 하여 사용 됩니다.

c++ unhanlde exception

7월 25, 2016 C & C++ No comments

c++에서 unhandle exception control 하는 경우

SetUnhandledExceptionFilter() 함수에 LONG WINAPI my_top_level_filter(__in PEXCEPTION_POINTERS pExceptionPointer) 형태의 callback pointer를 전달 합니다.

SetUnhandledExceptionFilter(my_top_level_filter);

callback함수 안에서는 minidump 파일을 생성하여 write 해두면 추후 !analyze -v를 통해 쉽게 stack trace가 가능 합니다.

아래는 간단한 mini dump 예제 입니다.

MINIDUMP_EXCEPTION_INFORMATION MinidumpExceptionInformation;
PEXCEPTION_RECORD pExceptionRecord = pExceptionPointer-&gt;ExceptionRecord;
MinidumpExceptionInformation.ThreadId = ::GetCurrentThreadId();
MinidumpExceptionInformation.ExceptionPointers = pExceptionPointer;
MinidumpExceptionInformation.ClientPointers = FALSE;
HANDLE hDumpFile = ::CreateFileW(dump_filename.c_str(),
    GENERIC_WRITE, 
    FILE_SHARE_WRITE, 
    NULL, 
    CREATE_ALWAYS,
    FILE_ATTRIBUTE_NORMAL, NULL);

MiniDumpWriteDump(GetCurrentProcess(),
    GetCurrentProcessId(),
    hDumpFile,
    MiniDumpNormal,
    &amp;MinidumpExceptionInformation,
    NULL,
    NULL);

::TerminateProcess(::GetCurrentProcess(), 0);

WWL (Sigmoid)

7월 25, 2016 DICOM No comments

WWL Sigmoid

WWL에서 center를 기준으로 좌우가 log 함수처럼 생긴 graph형태를 sigmoid라고 합니다.

DICOM에서도 이런 특이한 형태를 지원합니다. 보통 element안에 lut 형태로 저장하여 사용하게 끔 되어있습니다.

보통 많이 사용하는곳이 MR image나 Mammo영상에서 판독을 좋게 한다고 해서 가끔 사용 합니다.

internet 발췌한 간단한 sigmoid graph 그리기 입니다.

sigmoid

아래 함수를 통해서 구현 합니다.

sigmoid_function

python code로는 아래와 같습니다.

import math

def sigmoid(x):
    a = []
    for item in x:
        a.append(1/(1+math.exp(-item)))
    return a

import matplotlib.pyplot as plt
import numpy as np


x=np.arange(-10, 10, 0.2)
sig = sigmoid(x)
plt.plot(x,sig)
plt.show()

LeadTools library의 document에서도 쉽게 해당 식의 parameter를 참조 하여 구현 할 수 있습니다.

sigmoid_leadtools

아래는 leadtools document에 있는 내용 발췌 입니다.

Y = uStart + (uEnd uStart) * (1./ (1 + exp(2*nFactor/10. * (x-Center))/(uEnd- uStart)) - nFirstValue)/ (nLastValue nFirstValue)
where:

nFirstValue = 1./(1+exp(2.*nFactor/10.*(nStart - Center)/ (uEnd- uStart))).
nLastValue = 1./(1+exp(2.*nFactor/10.*(nEnd - Center)/ (uEnd- uStart))).
Center = (nEnd + nStart)/2.
x = the intensity value of the selected point
uStart = the nLow parameter of this function
uEnd = the nHigh parameter of this function