【Pyinstaller】Python file to EXE file (파이썬 파일 실행 파일로 만들기)

Python file to EXE file 파이썬 파일 실행 파일로 만들기

참고 동영상 : https://www.youtube.com/watch?v=UZX5kH72Yx4

$ pip install pyinstaller

$ pyinstaller --onefile -w <file_name.py>
  1. 옵션

    –onefile : 깔끔하게 exe 파일 하나만 만들어 줌

    -w : console을 열지 않음. 만약 터미널 창의 결과가 보이거나 터미널 창에 값을 입력할 console이 보여야 한다면, -w 옵선 설정하지 말기

  2. 실행 결과

    • 2개의 폴더 생성 build, dist
    • build는 지워버림 필요없음
    • dist에 .EXE 파일이 존재할 것임
    • 그거 그냥 실행하면 됨.
  • 주의할점!! 의존성이 있는 경우 : EXE파일을 dist내부에서 실행하지 말고, (아마 “$ cd ../” 위치) 바로 아래 디렉토리 위치에 EXE파일을 옮겨놓고 파일 실행하기.
    • from .ssd.modeling import detector
    • 이와 같은 문장을 python 파일에 적어놨다면, 파일의 위치가 일치해야 하므로.
  1. NSIS 라는 프로그램 이용하기
    • 이 프로그램을 이용하면, 위와 같은 의존성 문제 고려 안해도 된다.
    • 위의 방법은 패키지 내부의 .py 파일 하나만을 exe파일로 변경하는 것이 었다.
    • 패키지 전체를 하나의 installer 파일로 만들고 싶다면 이 프로그램을 이용해라.
    • drawing
    • Donwload link
    • 프로그램 사용방법은 맨 위 유투브 링크의, 6:30~8:30에 있음. 생각보다 매우 쉬우니 필요하면 해보기. -

【Attention】Attention Mechanism Overveiw

Attention and Transformer is salient mechanism in deep learning nowadays. I remain my note which I learn from reference.

0. reference

  1. a-brief-overview-of-attention-mechanism
  2. Attention mechanism with schematic
  3. the development of the attention mechanism
  4. How Transformers work in deep learning and NLP: an intuitive introduction

1. a-brief-overview-of-attention-mechanism

이 게시물 댓글이 말하길, “이 게시물은 쓰레기다.” 라고 적혀 있다. 딱 아래의 내용만 알자.

  1. What is Attention?
    • hundreds of words -압축-> several words : 정보 손실 발생.
    • 이 문제를 해소해주는 방법이 attention. : Attention allow translator focus on local or global feature(문장에 대한 zoom in or out의 역할을 해준다.)
  2. Why Attention?
    • Vanilla RNN : 비 실용적이다. Input의 길이와 Output의 길이가 꼭 같아야 한다. Gradient Vanishing/Exploding가 자주 일어난다. when sentences are long (more 4 words).
      • drawing
      • 한 단어씩 차례로 들어가 enbedding 작업을 거쳐서 encoder block에 저장된다, 각 block에는 각각 hidden vector가 존재하고 있다. 4번째 단어가 들어가서 마지막 encoder vertor(hidden vector inside)가 만들어 진다. 그것으로 Decoder가 generate words sequentially.
      • Issue : one hidden state really enough?

2. Attention mechanism

이해하기 아주 좋은 게시물 이었다.

  1. visual attention
    • many animals focus on specific parts
    • we should select the most pertinent piece of information, rather than using all available information. (전체 이미지 No, 이미지의 일부 Yes)
    • Attention 개념은 많은 곳에서 사용된다. 예를 들어서, speech recognition, translation, and visual identification of objects 에서 다 쓰인다.
  2. Attention for Image Captioning
    • Basic 이미지 캠셔닝은 아래의 방법을 사용한다. Image를 CNN을 통해서 encoder해서 feature를 얻는데 그게 Hidden state h 가 된다. 이 h를 가지고, 맨 위부터 LSTM를 통해서 첫번째 단어와 h1을 얻고, h와 h1을 LSTM에 넣어서 2번째 단어를 얻는다.
    • drawing
    • 나오는 각각의 단어는 이미지의 한 부분만 본다.따라서 이미지 전체를 압축한 h를, 일정 부분만을 보고 결과를 추출해야하는 LSTM에, 넣는 것은 비효율적이다. 이래서 attention mechanism이 필요하다.
    • attention mechanism 전체 그림
      • drawing
  3. What is an attention model? 위의 이미지에서 Attention Model의 내부는 무엇일까?
    • drawing
    • attention Model에는 n개의 input이 들어간다. 위의 예시에서 y1 ~ yn이 되겠다.
    • 출력되는 z는 모든 y의 summary 이자, 옆으로 들어가는 c와도 연관된 information이다.
    • 각 변수의 의미
      • C : context, beginning.
      • Yi : the representations of the parts of the image. (예를 들어서 이미지 Final feature map의 Channel=n개라면, 1개 Channel을 Yi에 부여한다.)
      • Z : 다음 단어 예측을 위한 Image filter 값.
    • attention model 분석하기 (저게 최대 화질 이미지..)
      1. tanh를 통해서 m1,…mn이 만들어 진다. mi는 다른 yj와는 관계없이 생성된다는 것이 중요한 Point이다.
      2. softmax를 사용해서 각 yi를 얼마나 비중있게 봐야 하는가?에 대한 s1,s2…sn값이 나온다. argmax가 hard, softmax를 soft의 개념이라고 한다.
      3. 최종 Z는 y1 ,y2 …yn를 s1 ,s2 … sn를 사용해서 the weighted arithmetic mean을 한 것이다.
        image
    • 위 전체 과정을 아래와 같이 수정하는 방법도 있다.
      • tanh를 dot product로 바꾸기 : any other network, arithmetic(Ex.a dot product) 으로 수정될 수 있다. a dot product 는 두 백터의 연관성을 찾는 것이니, 좀 더 이해하기 쉽다.
      • hard attention
        1. 지금까지 본 것은 “Soft attention (differentiable deterministic mechanism)” 이다. hard attention은 a stochastic process이다. 확률값은 si값을 사용해서 랜덤으로 yi를 선택한다. (the gradient by Monte Carlo sampling)
        2. drawing
        3. 하지만 gradient 계산이 직관적인 Soft Attention를 대부분 사용한다.
    • 이 이후에, Z를 사용하는LSTM은, i번째 단어를 예측하고 다음에 집중해야하는 영역에 대한 정보를 담은 h_i+1을 return한다.
  4. Learning to Align in Machine Translation (언어 모델에서도 사용해보자)
    • Image와 다른 점은 attention model에 들어가는 y1,y2 … yi 값은, 문자열이 LSTM을 거쳐나오는 연속적인 hidden layer의 값이라는 것이다.
    • drawing
    • Attention model을 들여다 보면, 신기하게도 하나의 input당 하나의 output으로 matcing된다. 이것은 translation 과제에서 장점이자, 단점이 될 수 있다.

3. the development of the attention mechanism

drawing

  • 핵심 paper
    1. Seq2Seq, or RNN Encoder-Decoder (Cho et al. (2014), Sutskever et al. (2014))
    2. Alignment models (Bahdanau et al. (2015), Luong et al. (2015))
    3. Visual attention (Xu et al. (2015))
    4. Hierarchical attention (Yang et al. (2016))
    5. Transformer (Vaswani et al. (2017))
  1. Sequence to sequence (Seq2Seq) architecture for machine translation
    • two recurrent neural networks (RNN), namely encoder and decoder.
    • drawing
    • RNN,LSTM,GRU’s hidden state (from the encoder)를 the decoder에 source information 보낸다.
    • a fixed-length vector, only last one Hidden state 만을 이용해서 Decoding을 하는 것은 Long sentences issue가 발생할 수 있다.
    • RNN으로는 Gradient exploding, Gradient vanishing 문제가 크게 일어난다.
  2. Align & Translate
    • RNN을 한 방향으로만 하지말고, 양방향으로 한다. 이를 통해 얻은 at1, at2… atT를 사용해서, X1..XT 중 어떤것에 더 attetion할지에 대한 정보를 담을 수 있다.
    • 아래의 형태 말고도, 논문에는 더 많은 형태의 모델을 제시해놓았다.
    • drawing
  3. Visual attention
    • the image captioning problem 에서 input image와 oput word를 align 하기를 시도 했다.
    • CNN으로 feature를 뽑고, 그 정보를 RNN with attention 사용하였다. 위의 #2내용 다시 참조.
    • translation 보다 다른 많은 문제에서 attention을 쉽게 적용한 사례중 하나이다.
    • drawing
  4. Hierarchical Attention
    • effectively used on various levels
    • attention mechanism 이 classification problem에서도 쓰일 수 있다는 것을 보였다.
    • 내가 그림만 보고 이해하기로는 아래와 같은 분석을 할 수 있었다.
    • 2개의 Encoder를 사용했다. (word and sentence encoders)
    • drawing
  5. Transformer and BERT
    1. paper
    2. multi-head self-attention : 시간 효율적, representation을 하는데 매우 효율적이다. Convolution, recursive operation을 삭제하기 때문이다. 이 모듈에 대해서는 나중에 공부해볼 예정이다.
    3. BERT 는 pretrains bi-directional representations with the improved Transformer architecture. 그리고 XLNet, RoBERTa, GPT-2, and ALBERT 와 같은 논문들이 나오는데에 큰 도움을 주었다.
  6. Vision Transformer
    1. Transformer virtually replaces(대체해 버렸다) convolutional layers rather than complementing(보완하는게 아니라) them
    2. CNN’s golden age. Transformer에 의해서 RNN, LSTM 등이 종말을 마지한 것처럼.
  7. Conclusion

4. How Transformers work intuitively

  • The famous paper “Attention is all you need” in 2017 changed the way we were thinking about attention
  • Transformer의 기본 block은 self-attention이다.
  1. Representing the input sentence (sequential 한 데이터를 포현(함축)하는 방법)
    • transformer 의 탄생 배경 : “entire input sequence를 넣어주는거는 어떨까? 단어 단위로 잘라서 (tokenization) sequential 하게 넣어주지 말고!” (RNN과 LSTM과는 다르다. 그들은 sequentially 하게 일을 처리한다.)
    • tokenization를 해서 하나의 set을 만든다. 여기에는 단어가 들어가고, 단어간의 order는 중요하지 않다. (irrelevant)
    • 집합 내부 단어들을, (대체, 정사하다) project, (words를) in a distributed geometrical space로, 해야한다. (= word embeddings)
    • (1) Word Embeddings
      1. character <- word <- sentence와 같이 distributed low-dimensional space로 표현하는 것.
      2. 단어들은 각각의 의미만 가지고 있는게 아니라, 서로간의 상관관계를 가지기 때문에 3차원 공간상에 word set을 뿌려놓으면 비슷한 단어는 비슷한 위치에 존재하게 된다. visualize word Embeddings using t-SNE
      3. 단어 임배딩이 무엇이고 어떻게 구현하는가 : 특정 단어를 4차원 백터로 표현하는 방법
      4. drawing
      5. “이런게 있구나” 정도로만 이해했다. 어차피 내가 NLP 할 것은 아니니까.
    • (2) Positional encodings
      1. drawing
      2. 위에서는 단어의 order를 무시한다고 했다. 하지만 order (in a set) 을 모델에게 알려주는 것은 매우 중요하다.
      3. positional encoding : word embedding vector에 추가해주는 set of small constants(작은 상수) 이다.
        • sinusoidal function (sin함수) 를 positional encoding 함수로 사용한다.
        • sin함수에서 주파수(y=sin(fx), Cycle=2pi/f)와 the position in the sentence를 연관시킬 것이다.
        • 예를 들어보자. (위의 특정 단어를 4차원 백터로 표현한 그림 참고)
        • 만약 32개의 단어가 있고, 각각 1개의 단어는 512개의 백터로 표현가능하다.
        • 아래와 같이 1개 단어에 대한 512개의 sin(짝수번쨰단어),cos(홀수번째단어)함수 결과값을 512개의 백터 값으로 표현해주면 되는 것이다.
        • drawing
        • 이런 식으로 단어를 나타내는 자체 백터에 에 순서에 대한 정보를 넣어줄 수 있다.
        • 예를 들어, 영어사전 안에 3000개의 단어가 있다면 3000개의 단어를 각각 2048개의 백터로 표현해 놓는다. 프랑스어사전 안에서 그에 상응하는 3000개의 단어를 추출하고, 단어 각각 2048개의 백터로 임배딩 해놓는다. 그리고 아래의 작업을 한다고 상상해라.
  2. Encoder of the Transformer
    • Self-attention & key, value query
      • drawing
      • 매우 추천 동영상, Attention 2: Keys, Values, Queries : 위의 Attention Mechanism을 다시 설명해 주면서, key values, Query를 추가적으로 설명해준다.
      • 위의 ‘What is an attention model’ 내용에 weight 개념을 추가해준다. C,yi,si 부분에 각각 Query, key, Value라는 이름의 weight를 추가해준다.
      • NER = Named Entity Recognition : 이름을 보고, 어떤 유형인지 예측하는 test. Ex.아름->사람, 2018년->시간, 파리->나라
      • 직관적으로 이해해보자. ‘Hello I love you’라는 문장이 있다고 치자. Love는 hello보다는 I와 yout에 더 관련성이 깊을 것이다. 이러한 관련성, 각 단어에 대한 집중 정도를 표현해 주는 것이, 이게 바로 weight를 추가해주는 개념이 되겠다. 아래의 그림은 각 단어와 다른 단어와의 관련성 정도를 나타내주는 확률 표 이다.
      • drawing
    • Multi Head Attention
      • 참고 동영상, Attention 3: Multi Head Attention
      • I gave my dog Charlie some food. 라는 문장이 있다고 치자. 여기서 gave는 I, dog Charlie, food 모두와 관련 깊은데, 이게 위에서 처럼 weight 개념을 추가해 준다고 바로 해결 될까?? No 아니다. 따라서 우리는 extra attention 개념을 반복해야 한다.
      • drawing
    • Short residual skip connections
      • 블로그의 필자는, 아래의 Skip Connection구조를 직관적으로 이렇게 설명한다.
      • 인간은 top-down influences (our expectations) 구조를 사용한다. 즉 과거의 기대와 생각이 미래에 본 사물에 대한 판단에 영향을 끼지는 것을 말한다.
    • Layer Normalization, The linear layer 을 추가적으로 배치해서 Encoder의 성능을 높힌다.
    • drawing
  3. Decoder of the Transformer
    • DETR 와 Vit 논문안에 있는 내용 참조
  4. Attention 4 - Transformers
    • Multi-head attention is a mechanism to add context that’s not based on RNN
    • drawing
    • 아래 사진은 그냥 기본적인 내용의 설명 그림.
    • drawing
    • Input에는 문장이 들어가고, Multi-head Attention에서 각 단어에 대한 중요성을 softmax(si)로 계산 후, 그것을 가중치 wi로 두고, 원래 단어와 곱해놓는다. (What is an attention model?의 사진 참조)
    • Multi-head Attention doesn’t care about position. But Positional Enxoding push to care more about position.
  5. Why Multi-head Attention can be replaced RNN
    • drawing

【Domain-Adaptation】Deep Domain Adaptation Basics

Deep Domain Adaptation Basics

  • 2021.02.16 전체 복습 후 느낀점 : 정말 이 분야를 제대로 하고 싶다면, 아래의 내용들은 느낌만 알아가는데에 좋다. 더 자세한 내용들은 결국 논문을 찾아서 읽어야 한다.

Reference (Study order)

  1. https://towardsdatascience.com/deep-domain-adaptation-in-computer-vision-8da398d3167f
  2. http://www.eecs.umich.edu/eecs/pdfs/events/4142.pdf
  3. https://sudonull.com/post/9686-Overview-of-Deep-Domain-Adaptation-Basic-Methods-Part-1

1. Deep Domain Adaptation In Computer Vision

  • 이 Reference가 좋은 자료 인지 모르겠다. 애매모호 하기만 하다.

1. introduction

  • 특정 신겨망 모델을 NYC dataset로 학습시키고, Manhattan에서는 잘 동작하지만 Paris에서 사용하니 문제 발생!
  • images from different viewing angles / different lighting conditions
    • source distribution = source dataset : Pre-train을 위해서 사용했던 데이터셋(의 분포, 분야)
    • targer distribution = source dataset : domain changed 된, dataset.
  • 일반적으로, damain adaptation은 한개 혹은 그 이상의 데이터셋을 사용한다.

2. Domain Adaptation Categories

  • 참고 논문
    1. Deep Visual Domain Adaptation: A Survey (2018)
    2. A Survey of Unsupervised Deep Domain Adaptation (2019)
    3. 과제의 복잡성은 labeled/unlabeld data의 양, source/target의 차이 정도로 분류 가능하다.
  • domain adaptation : the task space is the same(해야하는 과제는 같다. maybe Ex. obejct detection, segment. , kinds of labels) But input domain is divergent.
  • 크게 분류
    • homogeneous (동족의) = source : target = 1 : 1 데이터셋
    • heterogeneous (여러 종류,종족의) = compound = source : target = 1 : 3 데이터셋
  • target data에 따라서
    • supervised : target data is labeled
    • semi-supervised : labeled and unlabeled
    • self-supervised : No labeled data

3. Task Relatedness(상관성, 유사성)

  • task relatedness : source가 task이 얼마나 유사한가?
  • Task Relatedness를 정의(수치화)하는 방법
    1. how close their parameter vectors.
    2. how same features
  • 그럼에도 불구하고, domain adaptation을 사용할 수 있는지 없는지 판단하는 방법은, 직접 학습시키고 테스트 해봐야한다.

4. One-Step Domain Adaptation

3가지 basic techniques

  1. divergence-based domain adapatation.
  2. adversarial-based domain adaptation using GAN, domain-confusion loss.
  3. reconstruction using stacked autoencoders.

하나씩 알아가보자.

4-1 Divergence-based Domain Adaptation

  • some divergence criterion (핵심 차이점 기준?) 을 최소화하고, domain-invariant feature representation 을 찾아내는 것(achieve) (domain 변화에도 변하지 않는 feature extractor Ex. 어떤 신호등 모양이든 같은 신호등feature가 나오도록)
  • 아래에 3가지 방법이 나오는데, 느낌만 가져가기. 뭔 개소리인지 정확히 모르겠다.
  • (1) MMD - Maximum Mean Discrepancy
    • drawing
    • two-stream architecture는 파라메터 공유하지 않음.
    • Soft-max, Regularization(Domain-discrepancy) loss를 사용해서, two-architecture가 similar feature representation(=extractor)가 되도록 만든다.
  • (2) CORAL - Correlation Alignment
    • drawing
    • (b)처럼 distribution만 맞춘다고 해서 해결되지 못한다. (c)처럼 soure에 target correlation값을 추가함으로써 align시켜준다.
    • align the second-order statistics (correlations) instead of the means
    • 좋은 논문 : Using a differentiable CORAL loss.
  • (3) CCD - Contrastive Domain Discrepancy
    • label distributions 을 사용한다. (라벨별 확률 분포) by looking at conditional distributions(조건적인 P(확률분포|특정라벨))
    • 두 데이터의 각 라벨에 대해, 교집합 domain feature를 찾는다.
    • minimizes(최소화 한다) the intra-class discrepancy, maximizing(최대화 한다) the inter-class discrepancy.
    • 좋은논문 : target labels are found by clustering. CCD is minimized.
  • 이런 방법으로
    1. 이런 방법을 optimal transport 라고 한다.
    2. 두 데이터 간의 feature and label distributions 가 서로 비슷해지게 만들거나,
    3. 두 architecture(extractor, representation) 간의 차이가 줄어들게 만든다.

4-2 adversarial-based domain adaptation

  • source domain에 관련된 인위적인 target data를 만들고, 이 데이터를 사용해서 target network를 학습시킨다. 그리고 진짜 target data를 network에 넣어서 결과를 확인해 본다.
  • (1) CoGAN - source와 연관성 있는 target data 생성
    • drawing
    • 일부 weight sharing 하는 layer는 domain-invariant feature space extractor로 변해간다.
  • (2) source/target converter network - source와 연관성 있는 target data 생성
    • Pixel-Level Domain Transfer (2016 - citation 232)
    • drawing
    • 2개의 discriminator를 사용한다.
    • 첫번째 discriminator는 source에 의해 생성된 target data가 그럴듯 한지 확인하고.
    • 두번째 discriminator는 생성된 target data와 source의 상관성이 있는지 확인한다.
    • 특히 이 방법은 unlabeled data in the target domain 상황에서 사용하기 좋다.
  • (3) Get rid of generators - 어떤 domain에서도 invariable-feature를 추출하는 extractor 제작
    • Unsupervised Domain Adaptation by Backpropagation (2015 - citation 2000)
    • domain confusion loss in addition to the domain classification loss : classificator가 어떤 domain의 data인지 예측하지 못하게 한다.
    • drawing
    • gradient reversal layer는 the feature distributions를 일치시키기 위해 존재한다.(두 데이터 간의 특징 분포를 일치시키기 위해)
      • 파랑색 부분은 class label를 잘 찾으려고 노력하고
      • 초록색 부분은 domain classifier가 틀리도록 학습되면서(input이미지에 대해서 어떤 domain에서도 invariable-feature를 추출하는 extractor를 만든다), class label을 잘 맞추려고 학습된다.
      • 빨간색은 그대로 domain label을 옳게 classify하도록 학습된다.
      • Generator & discriminator 구조가 아닌듯, 맞는듯한 신기한 구조를 가지고 있다.

4-3. Reconstruction-based Domain Adaptation

  • (1) DRCN
    • Deep Reconstruction-Classification Networks for Unsupervised Domain Adaptation (2016 - citation 435)
    • drawing
    • (i) classification of the source data (ii) reconstruction of the unlabeled target data
    • (i) 나중에 input에 target을 넣어도 잘 classifying 하게 만듬. (ii) reconstruction된 data가 task data와 유사하도록 학습된다. 따라서 초반 layer도 task data에 대한 정보를 함축하도록 만들어 진다.
    • 논문에서는, 위 신경망의 Input=Source Reconstruction=Target을 넣고 먼저 학습시킨다. 그리고 반대로 Input=Target Reconstruction=Source가 되도록 다시 학습시켰다고 한다.
    • 아래와 같은 학습 방법도 가능하다.
    • drawing
  • (2) cycle GANs
  • (3) conditional GANs
    • encoder-decoder GAN
    • conditional GANs are used to translate images from one domain to anothe
    • Pix2Pix GAN이 대표적이다.
    • reference를 주면, 그것을 이용해 ouput을 만드는 GAN을 말한다.
    • drawing

5. Conclusion

  • Deep domain adaptation/ enables us to get closer/ to human-level performance/ in terms of the amount of training data. (원하는 task data (to be relative real-scene)가 적을 때 유용하게 사용할 수 있는 방법이다.)
  • drawing


2. Domain adaptation - Boston Universiry

  • Domain Adaptation에 대한 설명을 그림으로 아주 재미있게 표현해놓은 좋은 자료.
  • 하지만 아래 내용은 참고만 할 것. 논문을 찾아 읽어봐야 한다.
  • Applications to different types of domain shift
    1. From dataset to dataset
    2. From simulated to real control
    3. From RGB to depth
    4. From 3D-CAD models to real images
  • models adapted without labels (NO labels in target domain)
    • adversarial alignment
    • correlation alignment
  • D = distributions/ xi, zj = Image/ yi = Label :
    drawing

(1) From dataset to dataset, From RGB to depth

  • DRCN와 유사하지만 좀 더 복잡한 형태의 confusion-loss 사용하는 논문
    • Simultaneous Deep Transfer Across Domains and Tasks - citation 889
    • drawing
    • domain classifier loss : Domain이 source인지 target인지 판단한다. 잘못 판단하면 Loss가 커지므로, 잘 판단될 수 있도록 학습 된다.
    • domain confusion loss : Domain이 source인지 target인지 잘못 판단하게 만든다.
    • 한번은 classifier loss로, 다른 한번은 confusion loss로 학습시키므로써, Network가 Source에서만 잘 동작하게 만드는게 아니라, Target에서도 잘 동작하게 만든다.
    • 지금의 feature extractor는 너무 source중심으로 domain loss통해서 target에 대한 정보도 feature extractor가 학습하게 만드는 것이다.
    • Target으로 Test해봤을 때, 그냥 Source만으로 학습된 Network를 사용하는 것보다 이 과정을 통해서 학습된 Network에서 더 좋은 Accuracy 결과가 나왔다.
  • ADDA

(2) From simulated to real control

(3) From 3D-CAD models to real images

drawing

【mmdetection】 mmdetection Tutorial and Overview

0. Readme 정리

  1. mmdetection/docs/model zoo 정리

    • mmdetection/configs : ‘다양한 종류의 신경망’ 모델 설계를 위한, model_config.py 파일이 존재한다.

    • 각 ‘신경망 모델’이름의 폴더에 들어가면, readme.md가 따로 있고, 그곳에 backbone, **style(pytorch/caffe 두가지 framework 사용됨)**, lr-schd, memory, fps, boxAP, cong, Download(model/log) 가 적혀 있어서 참고하면 된다.

  2. installation(mmdetection/docs/get_started.md)

    • Prerequisites
      • PyTorch 1.3 to 1.6
      • MMCV
    • installation
      • install mmcv : 이미 빌드가 된 버전 다운로드 & Git을 다운받아 setup을 실행해 직접 빌드하거나.
      • install mmdetection : Only Github download + 직접 setup & build
      • note - 코드 수정은 reinstall이 필요없이, 바로 적용될 것 이다.
      • 혹시 docker를 사용하고 싶다면, dockerfile도 사용해보기
  3. Getting Started (아래의 내용들 빠르게 공부하자)

    1. mmdetection/demo/MMDet_Tutorial.ipynb
    2. mmdetection/docs/with existing dataset
    3. mmdetection/docs/with new dataset
    4. mmdetection/demo/webcam_demo.py for beginners
    5. mmdetection official documetation : 여기에도 좋은 내용이 많다. 3번까지 공부하고 5번의 내용과 이 documentation의 내용 중 더 맘에 드는 내용을 공부해보자.
    6. (여기부터는 필요하면 공부하자. 내가 나중에 어떤 패키지를 가져와서 코드를 수정할지 모르니..)There are also tutorials for finetuning models, adding new dataset, designing data pipeline, customizing models, customizing runtime settings and useful tools.
  4. 느낀점 ⭐⭐

    • 생각보다, 거의 Torch, Torchvision 와 같은 큰~모듈 처럼, 내부를 모르는 채로 원하는 함수를 구글링, Official Document 검색으로 찾아서 해야할 만큼 큰 모듈이다. 내가 원하는 모델을 분석하기 위해서 이 패키지를 사용한다는 것은… 멍청한 행동인 것 같다. 그만큼 사소한거 하나하나가 모두 구현되어 있는 큰~모듈이다.
    • 만약 내가 어떤 신경망 모델의 내부 코드가 궁금하다면, Github에서 그 신경망 모델의 이름을 검색하고, 그 신경망만을 위한 코드를 보는것이 낫겠다.
    • 이전에는 이런 생각을 했다. “만약 SSD를 공부하고 싶다면, SSD 패키지를 Github에서 검색해서 사용하는 것 보다는, mmdetection에서 SSD가 어떻게 구현되어 있는지, 어떤 모듈을 사용하는지 찾아보는게 더 좋지 않나? 그게 더 안정화된 코드고 빠른 코드 아닐까? 그래야 내가 혹시 필요한 모듈을 그대로 가져와서 쓸 수 있지 않을까??” 라고 생각했다. 물론 맞는 말이다….
    • 하지만 지금 시간이 급하니.. 정말 필요할 때, ‘2. docs/with existing dataset.md’ 에서 나온 방법을 이용해서, test.py와 train.py를 디버깅하고 어떤 흐름으로, 어떤 함수와 클래스를 이용하며 학습이 되고, 테스트가 되는지 찾아보는 시간을 가지는 것도 좋을 듯 하다.
    • 그럼에도 불구하고, 만약 내가 BlendMask 라는 함수를 수정해서 , 선배님처럼 The Devil Boundary Mask 모델을 만들고 싶다면 mmdetection이나, detectron2를 사용하지 않아도 될 수 있다. 하지만 그래도!! Developer for practice로서, mmdetection과 detectrion2 사용법과 코드가 돌아가는 내부 흐름은 알아두어야 한다고 생각한다.
    • 따라서 개인 컴퓨터가 생기면 디버깅을 하면서, 직접 내부 흐름을 살펴보는 시간도 가져보자.

0. colab 전용 환경 설정

아래에 코드에 간단한, 에러해결의 고민이 적혀있다. 참고해도 좋지만, 새로운 환경에서 mmcv와 mmdetection을 설치하기 위해서, 그냥 주어진 mmcv와 mmdetection의 [github, official_document] 자료를 다시 읽어보고 공부해보는게 더 좋을 듯하다.

from google.colab import drive
drive.mount('/content/drive')
%cd /content/drive/MyDrive/GCPcode/torch_package
!ls

# !pip install torch==1.6.0 torchvision==0.7.0 # -> 오류 발생 이거 때문인지는 모름.
!pip install -U torch==1.5.1+cu101 torchvision==0.6.1+cu101 -f https://download.pytorch.org/whl/torch_stable.html
import torch ; torch.__version__
# Colab : 아래 나오는 Restart runtime 눌러야 버전 변경 됨.

import torch ; import torchvision
torch.__version__, torchvision.__version__

# Check nvcc version
!nvcc -V
# Check GCC version
!gcc --version

# colab error defence
!pip install addict==2.2.1
!pip install yapf==0.28.0
!pip install Pillow==7.0.0
from addict import Dict
from yapf.yapflib.yapf_api import FormatCode

"""
# 이렇게 설치해서 그런지 에러가 나는데..? GCC, GUDA 버전문제라고? torch, GUDA 버전문제라고?
#!git clone https://github.com/open-mmlab/mmcv.git
%cd /content/drive/MyDrive/GCPcode/torch_package/mmcv
!MMCV_WITH_OPS=1 python setup.py develop
# Finished processing dependencies for mmcv-full==1.2.5
# 에러 이름 : linux-gnu.so: undefined symbol 
# 해결 : mmcv.__version : 1.2.5 말고 1.2.6으로 설치하게 두니 설치 완료.
# git으로 설치해서 직접 빌드하는 거는 왜... 1.2.5로 다운받아지는 거지? 모르겠다.
"""
# mmcv Readmd.md 처럼 위의 셀로, 쿠타, 토치 버전을 알고 mmcv를 정확하게 설치하는 것도 좋은 방법이다.
# pip install mmcv-full -f https://download.openmmlab.com/mmcv/dist/{cu_version}/{torch_version}/index.html
!pip install mmcv-full # colab-tuto에는 그냥 이렇게만 설치하니까 나도 일단 이렇게 설치.
# mmcv.__version__ : 1.2.6

import mmcv
mmcv.__version__

%cd /content/drive/MyDrive/GCPcode/torch_package
#!git clone https://github.com/open-mmlab/mmdetection.git
%cd /content/drive/MyDrive/GCPcode/torch_package/mmdetection

!pip install -r requirements/build.txt
!pip install -v -e .  # or "python setup.py develop"

import mmdet 
mmdet.__version__
# mmdet 2.8.0

!python mmdet/utils/collect_env.py # truble shooting

# Check mmcv installation
from mmcv.ops import get_compiling_cuda_version, get_compiler_version
print(get_compiling_cuda_version())
print(get_compiler_version())

# Check installation
# Check Pytorch installation
import torch, torchvision
print(torch.__version__, torch.cuda.is_available())
# Check MMDetection installation
import mmdet
print(mmdet.__version__)
# Check mmcv installation
from mmcv.ops import get_compiling_cuda_version, get_compiler_version
print(get_compiling_cuda_version())
print(get_compiler_version())

0.0 colab코렙에서 간단한 debugging디버깅 방법

  • def func1(a, b):
        return a / b
      
    def func2(x):
        a = x
        b = x - 1
        return func1(a, b)
      
    #########
      
    func2(1)
      
    #########
      
    %debug
    
  • 마지막 셀에 아래를 치면 바로 위에서 일어났던 에러 직전의 변수들을 직접 검색해서 찾아볼 수 있다.

  • %xmode Plain
    %pdb on
    func2(1)
    
  • 이와 같이 먼저 위에 실행해 놓으면, 에러가 발생한 후 바로 interact모드로 들어간다.

  • interact모드에서 사용할 수 있는 약어는 다음과 같은 것들이 있다.

    image-20210128202827731

  • 혹은 파이썬 코드에 import pdb; pdb.set_trace() 을 넣어둠으로써, break point를 설정할 수 있다. (근데 이렇게까지 할 거면, editor를 어떻게든 이용하는 편이 낫겠다. docker든 ssh든 다양한 방법이 있으니까)

1. demo/MMDet_Tutorial.ipynb

1.1 only inference using pretrained_model

%cd /content/drive/MyDrive/GCPcode/torch_package/mmdetection

!mkdir checkpoints
!wget -c http://download.openmmlab.com/mmdetection/v2.0/mask_rcnn/mask_rcnn_r50_caffe_fpn_mstrain-poly_3x_coco/mask_rcnn_r50_caffe_fpn_mstrain-poly_3x_coco_bbox_mAP-0.408__segm_mAP-0.37_20200504_163245-42aa3d00.pth \
      -O checkpoints/mask_rcnn_r50_caffe_fpn_mstrain-poly_3x_coco_bbox_mAP-0.408__segm_mAP-0.37_20200504_163245-42aa3d00.pth

from mmdet.apis import inference_detector, init_detector, show_result_pyplot

Choose to use a config and initialize the detector

config = 'configs/mask_rcnn/mask_rcnn_r50_caffe_fpn_mstrain-poly_3x_coco.py'

checkpoint = 'checkpoints/mask_rcnn_r50_caffe_fpn_mstrain-poly_3x_coco_bbox_mAP-0.408__segm_mAP-0.37_20200504_163245-42aa3d00.pth'

model = init_detector(config, checkpoint, device='cuda:0')

img = 'demo/demo.jpg'

result = inference_detector(model, img)

show_result_pyplot(model, img, result, score_thr=0.3)

# ** What is 'result'? **
"""
type(result) -> tuple
len(result)  -> 2
type(result[0]), type(result[1])  -> (list, list)
len(result[0]), len(result[1]) -> (80,80)
print(result[0]) # [confidence 값, bountding_box_position]
print(result[1]) # 80개 객체에 대한 w * h * channel(80) 의 bool type의 mask 정보
"""
  • 원하는 모델 Inference 하는 마법같은 방법 (mmdetection/mmddet/apis/inference)
    1. 핵심 모듈 2개만 import한다. inference_detector, init_detector, show_result_pyplot
    2. config파일은 mmdetection/config 에서 골라서 가져오기, pth파일은 미리 다운받아 놓기.
    3. init_detector으로 model 생성하기
    4. inference_detector으로 원하는 이미지 추론
    5. show_result_pyplot으로 result 시각화

1.2 Train a detector on customized dataset

  1. Modify cfg

    • mmdetection에서는 config 파일을 .py 파일을 사용한다.

      • 이 파일은 꼭 from mmcv.Config import fromfile파일과 함께 사용된다.

      • mmcv.Config.fromfile path -> 그냥 쉽게 생각하며 dictionary이다!

      • fast_rcnn_r50_caffe_fpn_1x_coco.py 기에 들어가봐도, dict이라는 dictionary생성자를 이용해서 config파일을 생성한다.

      • from mmcv import Config
        cfg = Config.fromfile('./configs/faster_rcnn/faster_rcnn_r50_caffe_fpn_mstrain_1x_coco.py')
        
      • cfg.data 를 보면 아래와 같은 Key, Value가 있는 것을 확인할 수 있다.

      • type(cfg) # cv.utils.config.Config
        type(cfg.data) # mmcv.utils.config.ConfigDict
        cfg.data 
        """
        {'samples_per_gpu': 2,
         'test': {'ann_file': 'data/coco/annotations/instances_val2017.json',
          'img_prefix': 'data/coco/val2017/',
          'pipeline': [{'type': 'LoadImageFromFile'},
           {'flip': False,
            'img_scale': (1333, 800),
            'transforms': [{'keep_ratio': True, 'type': 'Resize'},
             {'type': 'RandomFlip'},
             {'mean': [103.53, 116.28, 123.675],
              'std': [1.0, 1.0, 1.0],
              'to_rgb': False,
              'type': 'Normalize'},
             {'size_divisor': 32, 'type': 'Pad'},
             {'keys': ['img'], 'type': 'ImageToTensor'},
             {'keys': ['img'], 'type': 'Collect'}],
            'type': 'MultiScaleFlipAug'}],
          'type': 'CocoDataset'},
         ....
         ....
        
      • 위에서 확인한 Key를 아래와 같이 수정할 수 있다. . (dot) 을 이용해서 수정이 가능하다.

      •    cfg.dataset_type = 'KittiTinyDataset'
           cfg.data_root = 'kitti_tiny/'
                  
           cfg.data.test.type = 'KittiTinyDataset'
           cfg.data.test.data_root = 'kitti_tiny/'
           cfg.data.test.ann_file = 'train.txt'
           cfg.data.test.img_prefix = 'training/image_2'
                  
           ... (mmdetection/demo/MMDet_Tutorial.ipynb 파일 참조)
                  
           # The original learning rate (LR) is set for 8-GPU training.
           # We divide it by 8 since we only use one GPU.
           cfg.optimizer.lr = 0.02 / 8
           cfg.lr_config.warmup = None
           cfg.log_config.interval = 10
                  
           # Change the evaluation metric since we use customized dataset.
           cfg.evaluation.metric = 'mAP'
           # We can set the evaluation interval to reduce the evaluation times
           cfg.evaluation.interval = 12
           # We can set the checkpoint saving interval to reduce the storage cost
           cfg.checkpoint_config.interval = 12
                  
           # print(cfg)를 이쁘게 보는 방법
           print(f'Config:\n{cfg.pretty_text}')
        
      • 여기서 핵심은, cfg.data.test/train/val.type = '내가 아래에 만들 새로운 dataset' 을 집어 넣는 것이다.
  2. Regist Out Dataset

    • 데이터 셋을 다운로드 한후, 우리는 데이터 셋을 COCO format, middle format으로 바꿔줘야 한다.

    • 여기서는 아래이 과정을 수행한다.

      1. from mmdet.datasets.custom import CustomDataset
      2. CustomDataset 을 상속하는 클래스를 만들고 def load_annotations 해주기
    • middle format MMDetection 은 아래와 같은 format이다. 1. cocodata format arrangement, 2. coco format official과 비슷하다.

      • [
            {
                'filename': 'a.jpg',
                'width': 1280,
                'height': 720,
                'ann': {
                    'bboxes': <np.ndarray> (n, 4),
                    'labels': <np.ndarray> (n, ),
                    'bboxes_ignore': <np.ndarray> (k, 4), (optional field)
                    'labels_ignore': <np.ndarray> (k, 4) (optional field)
                }
            },
            ...
        ]
        
    • load_annotations를 정의하는 과정과 코드는 아래와 같다

      • 코드 요약 :

        1. 아래의 load_annotations에 들어가는 매개변수로, ann_file(type : str)에는 여기서 지정한 파일이 들어간다. cfg.data.test.ann_file = 'train.txt'
        2. train.txt파일의 첫줄을 살펴보면 아래와 같다. Pedestrian 0.00 0 -0.20 712.40 143.00 810.73 307.92 1.89 0.48 1.20 1.84 1.47 8.41 0.01
        3. data_infos는 dict들을 저장해놓은 list이다. In detail, data_infos에는 [ 1장에 이미지에 있는 객체들의 정보를 저장해둔, data_info=dictionary]들이 원소 하나하나로 들어간다.
        4. data_info의 key는 filename, width, height, ann 이다. 특히 ann의 key는 bboxes, labels 등이 있다.
        5. (self.img_prefix 와 같은 CustomDataset 클래스의 맴버변수가 쓰여서 디버깅 못함)
      • 코드 :

        • import copy
          import os.path as osp
                   
          import mmcv
          import numpy as np
                   
          from mmdet.datasets.builder import DATASETS
          from mmdet.datasets.custom import CustomDataset
                   
          @DATASETS.register_module()
          class KittiTinyDataset(CustomDataset):
                   
              CLASSES = ('Car', 'Pedestrian', 'Cyclist')
                   
              def load_annotations(self, ann_file):
                  cat2label = {k: i for i, k in enumerate(self.CLASSES)}
                  # load image list from file
                  image_list = mmcv.list_from_file(self.ann_file)
                       
                  data_infos = []
                  # convert annotations to middle format
                  for image_id in image_list:
                      filename = f'{self.img_prefix}/{image_id}.jpeg'
                      image = mmcv.imread(filename)
                      height, width = image.shape[:2]
                       
                      data_info = dict(filename=f'{image_id}.jpeg', width=width, height=height)
                       
                      # load annotations
                      label_prefix = self.img_prefix.replace('image_2', 'label_2')
                      lines = mmcv.list_from_file(osp.join(label_prefix, f'{image_id}.txt'))
                       
                      content = [line.strip().split(' ') for line in lines]
                      bbox_names = [x[0] for x in content]
                      bboxes = [[float(info) for info in x[4:8]] for x in content]
                       
                      # 진짜 필요한 변수
                  	gt_bboxes = []
                      gt_labels = []
                      # 사용하지 않은 변수
                      gt_bboxes_ignore = []
                      gt_labels_ignore = []
                       
                      # filter 'DontCare'
                      for bbox_name, bbox in zip(bbox_names, bboxes):
                          if bbox_name in cat2label:
                              gt_labels.append(cat2label[bbox_name])
                              gt_bboxes.append(bbox)
                          else:
                              gt_labels_ignore.append(-1)
                              gt_bboxes_ignore.append(bbox)
                   
                      data_anno = dict(
                          bboxes=np.array(gt_bboxes, dtype=np.float32).reshape(-1, 4),
                          labels=np.array(gt_labels, dtype=np.long),
                          bboxes_ignore=np.array(gt_bboxes_ignore,
                                                 dtype=np.float32).reshape(-1, 4),
                          labels_ignore=np.array(gt_labels_ignore, dtype=np.long))
                   
                      data_info.update(ann=data_anno)
                      data_infos.append(data_info)
                   
                  return data_infos
          
  3. Train Our Model

  • from mmdet.datasets import build_dataset
    from mmdet.models import build_detector
    from mmdet.apis import train_detector
    
  • 위의 핵심 모듈을 사용해서, 우리가 정의한 dataset을 학습시켜보자

  • # Build dataset
    datasets = [build_dataset(cfg.data.train)]
         
    # Build the detector
    model = build_detector(cfg.model, train_cfg=cfg.train_cfg, test_cfg=cfg.test_cfg)
    # Add an attribute for visualization convenience
    model.CLASSES = datasets[0].CLASSES
         
    # Create work_dir
    mmcv.mkdir_or_exist(osp.abspath(cfg.work_dir))
    train_detector(model, datasets, cfg, distributed=False, validate=True)
    
  • 실행하면, 우리가 설정한 epoch=12로 12번 학습된다.
  1. Inference with Out Model

    • img = mmcv.imread('kitti_tiny/training/image_2/000068.jpeg')
           
      model.cfg = cfg
      result = inference_detector(model, img)
      show_result_pyplot(model, img, result)
      

2. docs/with existing dataset.md

  1. 위와 똑같은 Just Inference 하는 방법
  2. Asynchronous interface
    • Inference를 동시에, 다른 input으로, 혹은 다른 model을 사용하여 돌릴 수 있는 방법이다,
    • import asyncio 라는 모듈을 사용해서 thread와 CPU, GPU의 적절한 사용을 이뤄낸다.
    • (아직 내가 사용할 방법은 아닌 것 같음)
  3. Test existing models on standard datasets
    • public datasets including COCO, Pascal VOC, CityScapes, and more dataset 종류 를 사용하는 방법. 그리고 이 dataset을 어떤 Path에다가 위치시켜야 하는지.
    • tools/test.py 등을 이용해 test를 진행한다.
    • 다양한 상황에 대해서, argparse를 어떻게 집어넣어줘야 하는지 있으니 참고
  4. Train predefined models on standard datasets
    • tools/train.py 등을 이용해 train를 진행한다. 많은 예시들이 추가되어 있으니 참고
    • 다양한 상황에 대해서, argparse를 어떻게 집어넣어줘야 하는지 있으니 참고

3. Train with customized datasets

  1. detectron2에서 봤던것 처럼, ballon dataset 을 사용해서 공부한다,

  2. STEP

    1. Prepare the customized dataset
    2. Prepare a config
    3. Train, test, inference models on the customized dataset.
  3. (1) Prepare the customized dataset

    • coco format으로 (1. cocodata format arrangement, 2. coco format official) data format을 바꿔줘야 한다.
    • coco_json_file 에 image의 path와 image의 annotation정보가 모두 있기 때문에, 사실 우리의 python 코드는 json 하나만 보면 된다!!
    • 따라서 CSV이든 XML이든 어떤 파일 형식으로 annotation된 데이터가 있다면, coco 즉 json포멧으로 annotation을 바꾸는 코드가 분명 있을거야. github에도 있을거고, 나의 블로그 Post에 【Tensorflow】, 【Keras】파일에도 이에 대한 내용이 잇었으니까 참고하도록 하자.
    • mmdetection에서도 mmcv를 이용해서 어떤 파일형식이든, coco format형식으로 바꿔주는, def convert_balloon_to_coco(ann_file, out_file, image_prefix): 함수를 예시로 주어주었다. 가능하다면 이것을 사용해도 좋은 듯 하다.
  4. (2) Prepare a config

    • ballon dataset을 사용하기 위해, 어떻게 mask_rcnn_r50_caffe_fpn_mstrain-poly_1x_balloon.py 파일을 만들었는지 나와 있으니 참고하도록 하자. (config.py 링크)
    • 위의 KittiTiny는 from mmdet.datasets.custom import CustomDataset 를 상속받아서 dataset을 만들어서 그런지, the number of class에 대한 고려는 안했지만, 여기서는 json파일을 직접 만들었기 때문에 #class를 고려를 해줬다.
  5. (3) Train, test, inference models on the customized dataset.

    • $ python tools/train.py configs/ballon/mask_rcnn_r50_caffe_fpn_mstrain-poly_1x_balloon.py
      $ python tools/test.py configs/ballon/mask_rcnn_r50_caffe_fpn_mstrain-poly_1x_balloon.py work_dirs/mask_rcnn_r50_caffe_fpn_mstrain-poly_1x_balloon.py/latest.pth --eval bbox segm
      
    • 더 다양한 case에 대한 agupare 적용방법은, 2. docs/with existing dataset.md 파일 참조

4. webcam_demo.py

  •  model = init_detector(args.config, args.checkpoint, device=device)
        
    camera = cv2.VideoCapture(args.camera_id)
      
    print('Press "Esc", "q" or "Q" to exit.')
    while True:
        ret_val, img = camera.read()
        result = inference_detector(model, img)
        ch = cv2.waitKey(1)
        if ch == 27 or ch == ord('q') or ch == ord('Q'):
            break
        model.show_result( img, result, score_thr=args.score_thr, wait_time=1, show=True)
    
  • 매우 간단.

5. mmdetection for SSD

【Self-Supervise】 Self-Supervised-Learning Basics

Self-Supervised-Learning Basics

Self-Supervised-Learning Basics on webs

  • 데이터의 사람이 만든 ‘annotation Label’이 없어도, Feature Extractor(Pre-trained Model)을 만들 수 있는 몇가지 방법들에 대해 기초만 알아보자.

0. reference

  1. https://project.inria.fr/paiss/files/2018/07/zisserman-self-supervised.pdf
  2. https://lilianweng.github.io/lil-log/2019/11/10/self-supervised-learning.html
  3. https://www.fast.ai/2020/01/13/self_supervised/

1. zisserman-self-supervised - 2018.07

  1. 모델에 대한 상세한 설명은 없다. 하지만 전체적은 윤각선을 만들기 위해 먼저 빠르게 보기로 했다.
  2. Supervise-learning : With a large-scale dataset labelled / Can Specify a training loss / Easy to Train the network
  3. why self-supervision : high Expense of dataset / supervision-starved / vast numbers of unlabelled images/videos
  4. how infants may learn : The Development of Embodied Cognition
  5. What is Self-Supervision?

    • Self-Supervision을 통해서 Feature Extrator를 생성하고, 그렇게 얻은 (self를 해서 얻은) FeatureExtractor를 가지고, 적은 데이터 만을 가지고 (supervision 처럼) Classifier를 학습시키기 위함.
  6. Three parts
    • From Images
    • From videos
    • From videos with sound

2.Part (1) - Images

  • image
  • (2014) relative positioning : Origin Image만으로도 학습이 가능하다. 이걸로 Pretrained를 시키고 나중에 supervise로 refine 학습을 진행한다.
  • (2014) colourization
  • (2014) exemplar networks : Perturb/distort image crops, Train to classify as same class
  • 학습 절차
    • backbone에 self-supervised training을 먼저 수행한다. using 위의 다양한 방법들.
    • backbone freeze!
    • 그리고 train classifier.
    • 아래와 같이 supervised를 사용한 것 보다는 낮은 성능이지만, 그래도 성능이 좋아지고 있다. 그리고 아래 오른쪽에 새로운 Self-Supervised 방법들을 그림으로 추가해 놓았다. (참고만 하자)
    • image-20210115124531206
  • (2018) Image Transformation : Unsupervised representation learning by predicting image rotations
    • image-20210115134434239
    • Rotaion으로 학습한 AlexNet Architecture 모델에서 좋은 성능이 나왔다. then Relative Position, Colourization.

2.Part (2) - Videos

  • Video의 어떤 정보를 이용해서 Self-Supervised할 수 있을까?
    1. Temporal order of the frames => 1. Video sequence orde
    2. Nearby (in time) frames => 2. Video direction
    3. Motion of objects => 3. Video tracking
  • 1. Video sequence order 를 이용하는 방법

    • 예를 들어, 3개의 동영상 frame이 있다고 가정했을 때, frames order [1 -> 2 -> 3]를 예측하게 하는 방법
    • (a) Shuffle and Learn
      • Using ‘high motion window‘(동영상 중에서도 핵심적인 Action 부분 3장) of Dataset (Action Reognition) that is imformative(유용한) training tutples
      • Input : 이미지 튜플(3장의 프레임) -> Return : 각 프레임의 순서 예측
      • image-20210115135553374
      • 위와 같이, Sequence order를 이용해서 학습시킨다. 3개의 모델은 파라메터를 공유한다. 이 모델을 사용해 [Action Label 예측 모델’/’Human Pose Estimation] 데이터셋을 이용해 fine-tuning한다.
    • (b) Odd-One-Out Networks
      • image-20210115135851163
    • Summary
      • Important to select informative data in training : 중요한 정보를 선택해서 그것으로 학습을 시켜야 한다. 예를 들어 회전, 동영상 순서 등은 data에서 매우 중요한 정보라고 할 수 있다.
      • 직접적으로 의도하지는 않았지만, (a) shuffle and learn 과정을 통해서 모델은 ‘Human Pose Estimation’ 문제에서 필요한 feature extractor를 만들어 냈을 것 이다
  • 2. Video direction(방향) 를 이용하는 방법

    • video playing forwards or backwards, 정방향 재생중인가? 뒤로 거꾸로 재생중인가?
    • gravity, entropy, friction, causality 와 같은 물리적 법칙들에 대한 feature extractor를 생성할 것이다.
    • (a) T-CAM Model
      • Input: optical flow in two chunks(10 frame 동영상 뭉치)
      • image-20210115141419097
      • 동영상 전체에서, 핵심 장면을 이용한다.
      • 위의 pre-train network를 이용해서, Fine tune & test 한다. UCF101 (human action classification) 데이터를 사용해서. 그래서 Network는 the best performance ever를 얻었다.
  • 3. Video tracking 를 이용하는 방법

    • (a) Tracking Emerges by Colorizing Videos (2018)
      • image-20210115142442479
      • color 와 object tracking에는 분명한 관계가 있다!! 위의 그림처럼 같은 색을 tracking 한다면, Tracing 과제에서 절반이상은 성공이다.
      • Input : reference Frame (Color 존재), Input Frame(monochrome 흑백)
      • image-20210115143259887
        • A는 공간유사도(내적은 두 백터가 유사할 수록 큰 값이 나오므로.)
        • C_i는 참고하는 부분의 color
        • ∑Ac는 참고 공간(f_i)을 전체 훓어 봤을때, 가장 적절한 공간(f_j)의 색깔이 (다른 공간 색과 적절히 융합(∑)되어) 계산되어 나오겠다. 정답값인 C_j와 비교해서 loss 도출.
      • image-20210115143836240
      • 괜찮은 colorization 성능 도출 되었다.
      • 이렇게 학습시킨 모델을 사용해서, 아래의 문제에서도 좋은 결과를 얻을 수 있었다. 아래의 문제에서 Reference Frame은 각각 previous frame’s Instance color, previous frame’s pose은 항상 제공된다.
      • image-20210115144026487

2.Part (3) - Videos with Sound

  • Key : Sound and Frames are Semantically consistent and Synchronized. (일관적인 관계가 있다.)
  • Objective(목적): use vision and sound to learn from each other (서로서로를 예측하기 위해 서로를 사용한다.)
  • (a) Audio-Visual Embedding (AVE-Net)
    • image-20210115144930147
    • output : Positive or Negative.
    • Results Audio features extracor들을 Sound Classification (ESC-50 dataset) 에서 사용하면 아주 좋은 성능을 얻어냄.
    • Results Visual features extracor들을 ImageNet images에서 사용해서도 좋은 성능을 얻는다.
  • (b) AVOL-Net
    • 사진의 어디서 소리가 나는지 예측하는 모델. 아래의 그림만으로 이해가 한정적이니, 논문 보기.
    • image-20210115150920684
    • input: audio and video frame
    • Output: localization heatmap on frame
  • Other papers.. : (c) Ambient sound provides supervision for visual learning / Visually indicated sounds
  • DataSet : AudioSet from Youtube
  • 지금까지 소리와 이미지의 상관성(correspondence)를 파악하고자 노력했다. 이제는 이미지와 소리와의 synchronization을 파악하는 노력을 해보자.
    • 우리는 입모양으로 그 사람이 뭐라고 말하는지 유추가 가능하다. 시각장애인들은 더더욱.
    • image-20210115151120063
    • image-20210115151510905
    • 위와 같은 방식으로 모델을 학습시킨다. 그렇게 얻은 모델을 가지고 Lip Synchronization, Active speaker detection의 과제를 수행했을때 좋은 성능을 얻을 수 있었다.

2.3 - Summary

  1. Self-supervised learning from images/video
    • without explicit supervision, 학습이 가능하다. (Pre-train모델을 만들 수 있었다.)
    • we can Learn visual representations = 적절한 Visual Feature Extractor들을 뽑을 수 있었다.
  2. Self-Supervised Learning from videos with sound
    1. Intra- and cross-modal retrieval(회복) - 서로의 데이터를 가지고, 상호 학습이 가능했다.
    2. Learn to localize sounds (어디서 소리가 나는지 예측하는 모델)
    3. 영상+소리를 pair로 사용하는 것처럼, 다른 domain pair에는 무엇이 있을까??
      • face(not lip) - voice
      • Infrared(적외선) - visible
      • RGB - Depth
      • Stereo streams - visible

2번 3번 Reference는 나중에 필요하면 공부하자.

【Paper】 Deep Learning for Generic Object Detection, A Survey - Summary

Deep Learning for Generic Object Detection, A Survey 논문 리뷰 및 정리

Deep Learning for Generic Object Detection: A Survey

My Conclusion after I read the paper.

0. Abstract

  1. a comprehensive survey of the recent achievements
  2. More than 300 research contributions
  3. frameworks/ representation/ proposal generation/ context modeling/ training strategies/ evaluation metrics
  4. promising directions for future research

1. introduction

  • Deep Convolutional Neural Network (DCNN) called AlexNet in 2012
  • Over the past 5 years, this article attempts to track in order to gain a clearer picture
  • popular datasets/ evaluation metrics/ context modeling/ detection proposal methods.

  • many object detection previous surveys (refer to reference this paper later)
    • pedestrian detection
    • face detection
    • vehicle detection
    • traffic sign detection
    • generic object detection
  • we have limited our focus to top journal and conference papers. and limited picture detection not Video.
  • follows
    1. 20-years are summarized
    2. A brief introduction to deep learning
    3. Popular datasets and evaluation criteria
    4. the milestone object detection frameworks
    5. state-of-the- art performance
    6. future research directions

2. Generic Object Detection

2.1 The Problem

  • future challenges will move to the pixel level object detection.

2.2 Challenges

  • Accuracy Related Challenges
    • intra-class variations : color, texture, material, shape, size, poses, clothes
    • Imaging condition variations : lighting, physical location, weather, backgrounds
    • 20, 200, 91 object classes / VOC, ILSVRC, COCO is much smaller than can be recognized by humans.
  • Efficiency and Scalability Related Challenges
    • mobile/wearable devices have limited computational capabilities and storage space
    • A further challenge is that of scalability : unseen objects, unknown situations, it may become impossible to annotate them manually, forcing a reliance on weakly supervised strategies.

2.3 Progress in the Past 2 Decades

  • image-20210114173125275
  • accurate annotations are labor intensive to obtain
  • Ability to detect many object categories matches that of humans(인간 같은) 3000~3000 categories is undoubtedly an unresolved problem so far.

3. A Brief Introduction to Deep Learning

  • pass

4.1 Dataset

  • PASCAL VOC
  • ImageNet
  • MS COCO
  • Places
  • Open Images

4.2 Evaluation Criteria

  • Frames Per Second (FPS)
  • precision, and recall.
  • Average Precision (AP) -> over all object categories, the mean AP (mAP)

5. Basic Frameworks

  • image-20210114192428720
  • image-20210114201752611

【Paper】 convolutional Block Attention Module - Paper Summary

CBAM : Convolutional Block Attention Module

0. Abstract

  1. our module sequentially infers attention maps along two separate dimensions
  2. the attention maps are multiplied to the input feature map for adaptive feature refinement (향상되어 정제된 feature)
  3. lightweight and general module, it can be integrated into any CNN architectures

1. introduction

  1. Recent Detectors
    1. recent researches have mainly investigated depth, width(#channel), and cardinality(같은 형태의 빌딩 블록의 갯수).
    2. VGGNet, ResNet, GoogLeNet has become deeper for rich representation(중요한 특징 표현력).
    3. GoogLeNet and Wide ResNet(2016), width must be another important factor.
    4. Xception and ResNeXt, increase the cardinality of a network . the cardinality saves the total number of parameters and make results powerful than depth and width.
    5. significant visual attention papers
      • [16] A recurrent neural network for image generation
      • [17] Spatial transformer networks
  2. Emphasize meaningful features / along those two principal dimensions / channel(depth) and spatial axes(x,y). -> channel and spatial attention modules -> learning which information to emphasize or suppress.
    • image-20210114212858200
  3. Contribution
    1. Can be widely applied to boost representation power of CNNs
    2. Extensive ablation studies
    3. Performance of various networks is greatly improved

2. Related Work

  1. Network engineering

    1. ResNet / ResNeXt / Inception-ResNet
    2. WideResNet : a larger number of convolutional filters and reduced depth
      • image-20210114214240109
    3. PyramidNet : a strict generalization of WideResNet and the width increases.
      • image-20210114214431894
    4. ResNeXt : use grouped convolutions and vertify cardinality effect
      • image-20210114214135397
    5. DenseNet : Concatenates the input features with the output features
      • image-20210114214036592
  2. Attention

    • (2017) Residual attention network for image classification
      • image-20210114215737540
      • encoderdecoder style attention module
      • By refining the feature maps, performance good, robust to noisy inputs
      • more computational and parameter
    • (2017) Squeeze-and-excitation networks
      • image-20210114220217634
      • Exploit the inter-channel relationship
      • global average-pooled features to compute channel-wise attention. (‘what’ to focus) -> we suggest to use max-pooled features.
      • miss the spatial attention deciding ‘where’ to focus.
    • (2019) Spatial and channel-wise attention in convolutional networks for image captioning

3. Convolutional Block Attention Module

image-20210114223009703

  • ⊗ : element-wise multiplication
  • channel attention values are broadcasted along the spatial dimension

  • Channel attention module

    • In the past, make model learn the extent of the target object or compute spatial statistics.[33] [28]
    • exploiting the inter-channel relationship of features.
    • each channel is considered as a a feature detector.
    • ‘what’ is meaningful
    • average pooling and max-pooling -> two different spatial context (F^c_avg and F^c_max)
    • image-20210114224244736
    • W1, W0 are shared for both inputs and the ReLU activation function is followed by W0. r = reduction ratio.
  • Spatial attention module

    • The design philosophy is symmetric with the channel attention branch.
    • [34] Paying more attention to attention, pooling along channel axis can be effective in highlighting informative regions.
    • concatenated feature (both descriptor)
    • image-20210114225054378 : encodes where to emphasize or suppress.
    • image-20210114225827305
    • σ : the sigmoid function, the filter size of 7 × 7
  • Arrangement of attention modules

    • the sequential arrangement gives a better result than a parallel arrangement. (첫번째 그림처럼. 직렬로. width하게 병렬로 NO)
    • our experimental result.

4. Experiments

  • We apply CBAM on the convolution outputs in each block
  • image-20210114230937883
  • top-5 error, top-1 error : 감소해야 좋음
  • FLOPS = FLoating point Operations Per Second
    GFLOPS = GPU FLoating point Operations Per Second
    (그래픽카드의 소요 정도)
  • we empirically show the effectiveness of our design choice.
    • FLOPS = FLoating point Operations Per Second
      GFLOPS = GPU FLoating point Operations Per Second
      (그래픽카드의 소요 정도)
    • Channel attention
      • a shared MLP
      • using both poolings
      • r = the reduction ratio to 16.
    • Spatial attention
      • channelpooling
      • convolution layer with a large kernel size
    • Arrangement

4.2 Image Classification on ImageNet-1K

4.3 Network Visualization with Grad-CAM

  • Grad-CAM is a recently proposed visualization method.
  • Grad-CAM uses gradients in order to calculate the importance of the spatial locations.
  • image-20210114233249882

5. conclusion

  • we observed that our module induces the network to focus on target object properly.
  • We hope CBAM become an important component of various network architectures.

모르는 내용

【CV】Computer Vision at FastCampus1, chap1~6

FastCampus 사이트의 Computer vision 강의 내용 정리

  1. FastCampus 사이트의 Computer vision 강의 내용을 정리해 두었다.
  2. 수학적이고, 심도적인 내용은 윤성민교수님의 컴퓨터 비전 수업을 통해 배울 수 있었다. 강의 필기 자료는 다음에 업로드할 예정.
  3. 심도적인 증명보다는, OpenCV를 사용해서 실습에 바로 적용할 수 있도록 하는데 중점을 주는 좋은 강의 였다.
  4. 몇가지 중요한 부분만 정리해 놓는다. 만약 다음에 공부할 필요가 느껴지면 그때 다시 사이트에 들어가서 공부하면 된다.
  5. FastCampus - Computer vision Lecture

목차

  • 아래의 목차에서 정말 듣고 싶은 것만 듣자.
  • 어차피 학교 수업에서도 배울 내용이고, 너무 오래전 기술이라 몰라도 되는 것도 많다.
  • 따라서 목차를 보고 ‘이런 내용이 있구나’하고 나중에 필요하면, 와서 듣자. 지금은 진짜 궁금한것만 듣자.
  •   OpenCV-Python 시작하기
      Ch 01. OpenCV-Python 시작하기 - 01. 전체 코스와 컴퓨터 비전 소개
      Ch 01. OpenCV-Python 시작하기 - 02. 영상의 구조와 표현
      Ch 01. OpenCV-Python 시작하기 - 03. OpenCV 소개와 설치
      Ch 01. OpenCV-Python 시작하기 - 04. VS Code 설치와 개발 환경 설정
      Ch 01. OpenCV-Python 시작하기 - 05. 영상 파일 불러와서 출력하기
      Ch 01. OpenCV-Python 시작하기 - 06. OpenCV 주요 함수 설명
      Ch 01. OpenCV-Python 시작하기 - 07. Matplotlib 사용하여 영상 출력하기
      Ch 01. OpenCV-Python 시작하기 - 08. 실전 코딩 - 이미지 슬라이드쇼
      OpenCV-Python 기초 사용법
      Ch 02. OpenCV-Python 기초 사용법 - 01. 영상의 속성과 픽셀 값 처리
      Ch 02. OpenCV-Python 기초 사용법 - 02. 영상의 생성, 복사, 부분 영상 추출
      Ch 02. OpenCV-Python 기초 사용법 - 03. 마스크 연산과 ROI
      Ch 02. OpenCV-Python 기초 사용법 - 04. OpenCV 그리기 함수
      Ch 02. OpenCV-Python 기초 사용법 - 05. 카메라와 동영상 처리하기 1
      Ch 02. OpenCV-Python 기초 사용법 - 06. 카메라와 동영상 처리하기 2
      Ch 02. OpenCV-Python 기초 사용법 - 07. 키보드 이벤트 처리하기
      Ch 02. OpenCV-Python 기초 사용법 - 08. 마우스 이벤트 처리하기
      Ch 02. OpenCV-Python 기초 사용법 - 09. 트랙바 사용하기
      Ch 02. OpenCV-Python 기초 사용법 - 10. 연산 시간 측정 방법
      Ch 02. OpenCV-Python 기초 사용법 - 11. 실전 코딩 - 동영상 전환 이펙트
      기본적인 영상 처리 기법
      Ch 03. 기본적인 영상 처리 기법 - 01. 영상의 밝기 조절
      Ch 03. 기본적인 영상 처리 기법 - 02. 영상의 산술 및 논리 연산
      Ch 03. 기본적인 영상 처리 기법 - 03. 컬러 영상 처리와 색 공간
      Ch 03. 기본적인 영상 처리 기법 - 04. 히스토그램 분석
      Ch 03. 기본적인 영상 처리 기법 - 05. 영상의 명암비 조절
      Ch 03. 기본적인 영상 처리 기법 - 06. 히스토그램 평활화
      Ch 03. 기본적인 영상 처리 기법 - 07. 특정 색상 영역 추출하기
      Ch 03. 기본적인 영상 처리 기법 - 08. 히스토그램 역투영
      Ch 03. 기본적인 영상 처리 기법 - 09. 실전 코딩 - 크로마키 합성
      필터링
      Ch 04. 필터링 - 01. 필터링 이해하기
      Ch 04. 필터링 - 02. 블러링 (1) - 평균값 필터
      Ch 04. 필터링 - 03. 블러링 (2) - 가우시안 필터
      Ch 04. 필터링 - 04. 샤프닝 - 언샤프 마스크 필터
      Ch 04. 필터링 - 05. 잡음 제거 (1) - 미디언 필터
      Ch 04. 필터링 - 06. 잡음 제거 (2) - 양방향 필터
      Ch 04. 필터링 - 07. 실전 코딩 - 카툰 필터 카메라
      기하학적 변환
      Ch 05. 기하학적 변환 - 01. 영상의 이동 변환과 전단 변환
      Ch 05. 기하학적 변환 - 02. 영상의 확대와 축소
      Ch 05. 기하학적 변환 - 03. 이미지 피라미드
      Ch 05. 기하학적 변환 - 04. 영상의 회전
      Ch 05. 기하학적 변환 - 05. 어파인 변환과 투시 변환
      Ch 05. 기하학적 변환 - 06. 리매핑
      Ch 05. 기하학적 변환 - 07. 실전 코딩 - 문서 스캐너
      영상의 특징 추출
      CH 06. 영상의 특징 추출 - 01. 영상의 미분과 소베 필터
      CH 06. 영상의 특징 추출 - 02. 그래디언트와 에지 검출
      CH 06. 영상의 특징 추출 - 03. 캐니 에지 검출
      CH 06. 영상의 특징 추출 - 04. 허프 변환 직선 검출
      CH 06. 영상의 특징 추출 - 05. 허프 원 변환 원 검출
      CH 06. 영상의 특징 추출 - 06. 실전 코딩 동전 카운터
      이진 영상 처리
      CH 07. 이진 영상 처리 - 01. 영상의 이진화
      CH 07. 이진 영상 처리 - 02. 자동 이진화 Otsu 방법
      CH 07. 이진 영상 처리 - 03. 지역 이진화
      CH 07. 이진 영상 처리 - 04. 모폴로지 (1) 침식과 팽창
      CH 07. 이진 영상 처리 - 05. 모폴로지 (2) 열기와 닫기
      CH 07. 이진 영상 처리 - 06. 레이블링
      CH 07. 이진 영상 처리 - 07. 외곽선 검출
      CH 07. 이진 영상 처리 - 08. 다양한 외곽선 함수
      CH 07. 이진 영상 처리 - 09. 실전 코딩 명함 인식 프로그램
      영상 분할과 객체 검출
      CH 08. 영상 분할과 객체 검출 - 01. 그랩컷
      CH 08. 영상 분할과 객체 검출 - 02. 모멘트 기반 객체 검출
      CH 08. 영상 분할과 객체 검출 - 03. 템플릿 매칭 (1) 이해하기
      CH 08. 영상 분할과 객체 검출 - 04. 템플릿 매칭 (2) 인쇄체 숫자 인식
      CH 08. 영상 분할과 객체 검출 - 05. 캐스케이드 분류기 - 얼굴 검출
      CH 08. 영상 분할과 객체 검출 - 06. HOG 보행자 검출
      CH 08. 영상 분할과 객체 검출 - 07. 실전 코딩 간단 스노우 앱
      특징점 검출과 매칭
      CH 09. 특징점 검출과 매칭 - 01. 코너 검출
      CH 09. 특징점 검출과 매칭 - 02. 특징점 검출
      CH 09. 특징점 검출과 매칭 - 03. 특징점 기술
      CH 09. 특징점 검출과 매칭 - 04. 특징점 매칭
      CH 09. 특징점 검출과 매칭 - 05. 좋은 매칭 선별
      CH 09. 특징점 검출과 매칭 - 06. 호모그래피와 영상 매칭
      CH 09. 특징점 검출과 매칭 - 07. 이미지 스티칭
      CH 09. 특징점 검출과 매칭 - 08. 실전 코딩 - AR 비디오 플레이어
      객체 추적과 모션 벡터
      CH 10. 객체 추적과 모션 벡터 - 01. 배경 차분 정적 배경 차분
      CH 10. 객체 추적과 모션 벡터 - 02. 배경 차분 이동 평균 배경
      CH 10. 객체 추적과 모션 벡터 - 03. 배경 차분 MOG 배경 모델
      CH 10. 객체 추적과 모션 벡터 - 04. 평균 이동 알고리즘
      CH 10. 객체 추적과 모션 벡터 - 05. 캠시프트 알고리즘
      CH 10. 객체 추적과 모션 벡터 - 06. 루카스 - 카나데 옵티컬플로우
      CH 10. 객체 추적과 모션 벡터 - 07. 밀집 옵티컬플로우
      CH 10. 객체 추적과 모션 벡터 - 08. OpenCV 트래커
      CH 10. 객체 추적과 모션 벡터 - 09. 실전 코딩 - 핸드 모션 리모컨
      머신러닝
      CH 11. 머신 러닝 - 01. 머신 러닝 이해하기
      CH 11. 머신 러닝 - 02. OpenCV 머신 러닝 클래스
      CH 11. 머신 러닝 - 03. k최근접 이웃 알고리즘
      CH 11. 머신 러닝 - 04. KNN 필기체 숫자 인식
      CH 11. 머신러닝 - 05. SVM 알고리즘
      CH 11. 머신러닝 - 06. OpenCV SVM 사용하기
      CH 11. 머신러닝 - 07. HOG SVM 필기체 숫자 인식
      CH 11. 머신러닝 - 08. 숫자 영상 정규화
      CH 11. 머신러닝 - 09. k-평균 알고리즘
      CH 11. 머신러닝 - 10. 실전 코딩 문서 필기체 숫자 인식
      딥러닝 이해와 영상 인식
      CH 12. 딥러닝 이해와 영상 인식 - 01. 딥러닝 이해하기
      CH 12. 딥러닝 이해와 영상 인식 - 02. CNN 이해하기
      CH 12. 딥러닝 이해와 영상 인식 - 03. 딥러닝 학습과 모델 파일 저장
      CH 12. 딥러닝 이해와 영상 인식 - 04. OpenCV DNN 모듈
      CH 12. 딥러닝 이해와 영상 인식 - 05. MNIST 학습 모델 사용하기
      CH 12. 딥러닝 이해와 영상 인식 - 06. GoogLeNet 영상 인식
      CH 12. 딥러닝 이해와 영상 인식 - 07. 실전 코딩 한글 손글씨 인식
      딥러닝 활용 : 객체 검출, 포즈 인식
      CH 13. 딥러닝 활용 객체 검출 - 01. OpenCV DNN 얼굴 검출
      CH 13. 딥러닝 활용 객체 검출 - 02. YOLOv3 객체 검출
      CH 13. 딥러닝 활용 객체 검출 - 03. Mask-RCNN 영역 분할
      CH 13. 딥러닝 활용 객체 검출 - 04. OpenPose 포즈 인식
      CH 13. 딥러닝 활용 객체 검출 - 05. EAST 문자 영역 검출
      CH 13. 딥러닝 활용 객체 검출 - 06. 실전 코딩 얼굴 인식
    

Chap 1 - OpenCV basics

1강

2강

  • Gray (Black) 0~255 (White)
  • 프로그래밍 언어의 1Byte
    • unsigned char
    • numpy.uint8
  • 색의 성분 (의 삼원색)
    • 0 : 색의 성분이 전혀 없는 상태 = 검정
    • 255 : 색의 성분이 가득 있는 상태 = 흰색
  • 영상의 좌표계
    • 행렬을 읽듯이 읽어야 한다.
    • 우리가 아는 2차원 좌표계를 사용해서 읽지 말고. 따라서 y축은 아래를 향한다.
  • 영상의 파일 형식의 특징
    • JPG는 원본 이미지 데이터가 약간 손실됨. 인간은 못 느끼는 정도
    • GIF는 움짤용. 영상 처리에서 사용 안함
    • PNG 영상처리에서 가장 많이 사용
    • image-20210111224950317

3강

  • BSD license : Free for academic & commercial use
  • OpenCV 구성

4강 기본 코드

import sys
import cv2
print(cv2.__version__)

img = cv2.imread('cat.bmp')

if img is None:
    print('Image load failed!')
    sys.exit()

cv2.namedWindow('image')
cv2.imshow('image', img)
cv2.waitKey() # 아무키나 누르면 window 종료
cv2.destroyAllWindows()

5강 OpenCV 기본 명령어

  • OpenCV 도움말: http://docs.opencv.org/ -> 버전 선택
  • cv2.imread(filename, flags = ‘cv2.IMREAD_COLOR ‘) -> BGR 순서
  • 이미지 저장 : cv2.imwrite(filename, img : numpy.ndarray, params=None)
  • 새 창 띄우기(imshow위해 꼭 안해도 됨) : cv2.namedWindow(winname : str, flags=None) -> None
  • 새 창 모두 닫기 : cv2.destroyWindow(winname : str)
  • cv2.moveWindow(winname, x, y) , cv2.resizeWindow(winname, width, height)
  • cv2.imshow(winname, mat : ndarray_dtype_8uint)
  • cv2.waitKey(delay=’0’)
    • dalay = ms 단위의 대기 시간. If delay = 0, 무한히 기다림
    • return 값은 눌린 키 값.
    • 사용법
      while True:
      	if cv2.waitKey() == ord('q'):
      		break
      # 27(ESC), 13(ENTER), 9(TAB)
      

6강 Matplotlib 기본 명령어

  • BGR 순서 -> cv2.cvtColor() , GRAY -> cmap=’gray’

    import matplotlib.pyplot as plt
    import cv2
      
    # 컬러 영상 출력
    imgBGR = cv2.imread('cat.bmp')
    imgRGB = cv2.cvtColor(imgBGR, cv2.COLOR_BGR2RGB) # cv2.IMREAD_GRAYSCALE
      
    plt.axis('off')
    plt.imshow(imgRGB) #  cmap='gray'
    plt.show()
      
    # subplot
    plt.subplot(121), plt.axis('off'), plt.imshow(imgRGB)
    plt.subplot(122), plt.axis('off'), plt.imshow(imgGray, cmap='gray')
    plt.show()
    

8강 - 이미지 슬라이드쇼 프로그램

  • 폴더에서 파일 list 가져오기
    import os
    file_list = os.listdir('.\\images')
    img_files = [file for file in file_list if file.endswith('.jpg')]
    # 혹은
    import glob
    img_files = glob.glob('.\\images\\*.jpg') 
    
  • 전체 화면 영상 출력

    cv2.namedWindow('image', cv2.WINDOW_NORMAL) # normal 이여야 window 창 변경 가능.
    cv2.setWindowProperty('image', cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN)
    
  • 반복적으로, 이미지 출력
    cnt = len(img_files)
    idx = 0
    while True:
        img = cv2.imread(img_files[idx])
        if img is None:
            print('Image load failed!')
            break
        cv2.imshow('image', img)
        if cv2.waitKey(1000) >= 27: # 1초 지나면 False, ESC누루면 True
            break # while 종료
        # cv2.waitKey(1000) -> 1
        # cv2.waitKey(1000) >= 0: 아무키나 누르면 0 초과의 수 return
        idx += 1
        if idx >= cnt:
        	idx = 0
    

chap2 - Basic image processing technique

1장

  • cv2.imread(‘cat.bmp’, cv2.IMREAD_COLOR) -> numpy.ndarray [행, 열, depth, 몇장]
  • for y in range(h):
        for x in range(w):
            img1[y, x] = 255
            img2[y, x] = [0, 0, 255]
    
  • 이런 식으로 이미지, 픽셀값을 For로 바꾸면 엄청느리다.
  • 함수를 찾아 보거나, img[:,:,:] = [0,255,255] 이런식으로 사용해야 한다.

2장

  • 이미지(=영상) 새로 생성하기

    • numpy.empty / numpy.zeros / numpy.ones / numpy.full
  • 이미지 복사

    •   img1 = cv2.imread('HappyFish.jpg')
        img2 = img1 -> 같은 메모리 공유
        img3 = img1.copy() 
      
    • img3 = img1.copy() -> 새로운 메모리에 이미지 정보 다시 할당 array안의 array도 다시 할당한다. 여기서는 deepcopy랑 같다. ](https://junha1125.github.io/docker-git-pytorch/2021-01-07-torch_module_research/#21-copydeepcopy)
    • numpy에서는 deepcopy랑 copy가 같다. 라고 외우자

2-3강 - 마스크 연산과 ROI

  • 마스크 영상으로는 0 또는 255로 구성된 이진 영상(binary image), Gray Scale
  • cv2.copyTo(src, mask, dst=None) -> dst
    •   src = cv2.imread('airplane.bmp', cv2.IMREAD_COLOR)
        mask = cv2.imread('mask_plane.bmp', cv2.IMREAD_GRAYSCALE)
        dst = cv2.imread('field.bmp', cv2.IMREAD_COLOR)
        cv2.copyTo(src, mask, dst1)
        dst2 = cv2.copyTo(src, mask)
              
        # 하지만 아래와 같은 슬라이딩 연산도 가능!!
        dst[mask > 0] = src[mask > 0] # -> dist = dst1
      
    • src, mask, dst는 w,h 모두 크기가 같아야 함. src와 dst는 같은 타입. mask는 그레이스케일 타입의 이진 영상.
    • image-20210113090901294
    • dst2 : image-20210113090939395
    • dst과 dst2는 완전히 다른 이미지로 생성되니 주의해서 사용할 것.
  • 투명한 배경이 있는 png 파일 (4channel)
    • src = cv2.imread('airplane.bmp', cv2.IMREAD_UNCHANGED) ## 투명배경 있는 것은 IMREAD_UNCHANGED!!! 
      mask = src[:,:,-1]
      src = src[;,:,0:3]
      h,w = src.shape[:2]
      crop = dst[x:x+h,y:w+2]  # src, mask, dst는 w,h 모두 크기가 같아야 함
      cv2.copyTo(src, mask, crop)
      

2-4강 - OpenCV그리기 함수

  • 주의할 점 : in-place 알고리즘 -> 원본 데이터 회손
  • 자세한 내용은 인강 참조, 혹은 OpenCV 공식 문서 참조 할 것.
  • 직선 그리기 : cv2.line
  • 사각형 그리기 : cv2.rectangle
  • 원 그리기 : cv2.circle
  • 다각형 그리기 : cv2.polylines
  • 문자열 출력 : cv2.putText

5강 - 카메라와 동영상 처리하기 1

  • OpenCV에서는 카메라와 동영상으로부터 프레임(frame)을 받아오는 작업을 cv2.VideoCapture 클래스 하나로 처리함
    image-20210113093215343
  • 카메라 열기
    • index : 2대가 있으면 테스트 해봐서 0,1번 중 하나 이다. domain_offset_id는 무시하기(카메라를 Open하는 방법을 운영체제가 적절한 방법을 사용한다.)
    • 아래 코드 꼭 읽어 보기: image-20210113093306495
    • 추가 함수
      • 준비 완료? : cv2.VideoCapture.isOpened() -> retval
      • 프래임 받아오기 : cv2.VideoCapture.read(image=None) -> retval, image
    •   import sys
        import cv
        cap = cv2.VideoCapture()
        cap.open(0)
        # 혹은 위의 2줄 한줄로 cap = cv2.VideoCapture(0)
            
        if not cap.isOpend()
          print('camera open failed!')
            sys.exit()
        while Ture :
            ret, frame = cap.read()
            if not ret : # frame을 잘 받아 왔는가? # 가장 마지막 프레임에서 멈춘다
                break
            edge = cv2.Canny(frame,50,150)
            cv2.imshow('edge', edge) # 2개의 창이 뜬다!! figure 설정할 필요 없음
            cv2.imshow('frame', frame)
            cv2.waitKey(20) == 27: # ESC눌렀을떄
                break
            
        cap.release() # cap 객체 delete
        cv2.destroyAllWindows()
      
  • 동영상 열기

    • 위의 코드에서 cap = cv2.VideoCapture(‘Video File Path’) 를 넣어주고 나머지는 위에랑 똑같이 사용하면 된다.
  • 카메라 속성 열고 바꾸기
    • cv2.VideoCapture.get(propId) -> cap.get(‘propId’)
    • cv2.VideoCapture.set(propId, value) -> cap.set(‘propId’, value)

2-6장 - 카메라와 동영상 처리하기 2

  • 동영상 저장 : cv2.VideoWriter 클래스
    • 소리는 저장이 안된다!!
    • cv2.VideoWriter / cv2.VideoWriter.open
    • cv2.VideoWriter.isOpened() / cv2.VideoWriter.write(image)
    • image-20210113094959326
  • 코덱 종류와 다운로드 링크

    • image-20210113094922834
  • 예시 코드
    • 이미지 반전 : inversed = ~frame. RGB 중 Grean = 0, RB는 255에 가까워짐
    • # 나의 카메로 open
      cap = cv2.VideoCapture(0)
      w = round(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
      h = round(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
          
      # 동영상 준비 중
      fourcc = cv2.VideoWriter_fourcc(*'DIVX') # *'DIVX' == 'D','I','V','X'
      fps = 30
      delay = round(1000/fps) # 프레임과 프레임 사이의 시간간격 (1000ms/30fps)
      out = cv2.VideoWriter('output.avi', fourcc, 30, (w, h))
          
      if not out.isOpened():
          print('File open failed!')
          cap.release()
          sys.exit()
          
      while True:
          ret, frame = cap.read()
          if not ret:
              break
          inversed = ~frame 
          # 반전하는 코드. RGB 중 Grean = 0, RB는 255에 가까워짐
          # 신기하니, 아래의  cv2.imshow('inversed', inversed) 결과 확인해보기.
              
          """
          edge = cv2.Canny(frame,50,150)
          edge_color = cv2.cvtColor(edge,cv2.COLOR_GRAY2BGR)
          out.write(edge_color)
          """
              
          out.write(frame)
          cv2.imshow('frame', frame) 
          cv2.imshow('inversed', inversed)
          if cv2.waitKey(delay) == 27: # delay는 이와 같이 사용해도 좋다. 없어도 됨.
          	break	
          
      

2-7장 - 키보드 이벤트 처리하기

  • cv2.waitKey(delay=None) -> retval
  • while True: 문을 계속 돌면서, 매 시간 마다 키보드 input이 없으면 필요없는 값을 return하고 while문에는 영향을 끼치지 않는다.
  • # 키보드에서 'i' 또는 'I' 키를 누르면 영상을 반전
    import cv2
    img = cv2.imread('cat.bmp', cv2.IMREAD_GRAYSCALE)
    cv2.imshow('image', img)
    while True:
        keycode = cv2.waitKey()
        if keycode == ord('i') or keycode == ord('I'):
            img = ~img
            cv2.imshow('image', img)
        elif keycode == 27:
            break
    cv2.destroyAllWindows()
    

2-8장 - 마우스 이벤트 처리하기

  • 마우스 이벤트 콜백함수 등록 함수 : cv2.setMouseCallback(windowName, onMouse, param=None) -> None
  • 마우스 이벤트 처리 함수(콜백 함수) 형식 : onMouse(event, x, y, flags, param) -> None
  • 이벤트에 대한 event 목록들은 강의 자료 참조.
  • oldx = oldy = -1
    def on_mouse(event, x, y, flags, param):
        global oldx, oldy
        if event == cv2.EVENT_LBUTTONDOWN:
        	oldx, oldy = x, y
        elif event == cv2.EVENT_MOUSEMOVE:
        	if flags & cv2.EVENT_FLAG_LBUTTON:
                cv2.line(img, (oldx, oldy), (x, y), (0, 0, 255), 4, cv2.LINE_AA)
                cv2.imshow('image', img)
                oldx, oldy = x, y
    img = np.ones((480, 640, 3), dtype=np.uint8) * 255
    cv2.imshow('image', img)
    cv2.setMouseCallback('image', on_mouse)
    cv2.waitKey()
    

2-9강 - 트랙바 사용하기

  • cv2.createTrackbar(trackbarName, windowName, value, count, onChange) -> None
  • def on_level_change(pos):
        value = pos * 16
        if value >= 255:
        	value = 255
        img[:] = value
        cv2.imshow('image', img)
    img = np.zeros((480, 640), np.uint8)
    cv2.namedWindow('image')
    cv2.createTrackbar('level', 'image', 0, 16, on_level_change)
    cv2.imshow('image', img)
    cv2.waitKey()
    cv2.destroyAllWindows()
      
    

10장 - 연산시간 측정

  • python time.time() 사용하자.
  • cv2의 시간측정함수를 소개한다.

2-11장 - 동영상 전환 이펙트 코드 만들기

  • image-20210114084035017
  •     import sys
        import numpy as np
        import cv2
    
    # 두 개의 동영상을 열어서 cap1, cap2로 지정
    cap1 = cv2.VideoCapture('video1.mp4')
    cap2 = cv2.VideoCapture('video2.mp4')

    if not cap1.isOpened() or not cap2.isOpened():
        print('video open failed!')
        sys.exit()

    # 두 동영상의 크기, FPS는 같다고 가정함
    frame_cnt1 = round(cap1.get(cv2.CAP_PROP_FRAME_COUNT))  # 15초 * 24 = Total 360 frame
    frame_cnt2 = round(cap2.get(cv2.CAP_PROP_FRAME_COUNT))
    fps = cap1.get(cv2.CAP_PROP_FPS) # 24
    effect_frames = int(fps * 2)  # 48 -> 1번 동영상의 맨 뒤 48프레임과, 2번 동영상의 맨 앞 48프레임이 겹친다

    print('frame_cnt1:', frame_cnt1)
    print('frame_cnt2:', frame_cnt2)
    print('FPS:', fps)

    delay = int(1000 / fps)

    w = round(cap1.get(cv2.CAP_PROP_FRAME_WIDTH))
    h = round(cap1.get(cv2.CAP_PROP_FRAME_HEIGHT))
    fourcc = cv2.VideoWriter_fourcc(*'DIVX')

    # 출력 동영상 객체 생성
    out = cv2.VideoWriter('output.avi', fourcc, fps, (w, h))

    # 1번 동영상 복사
    for i in range(frame_cnt1 - effect_frames):
        ret1, frame1 = cap1.read()

        if not ret1:
            print('frame read error!')
            sys.exit()

        out.write(frame1)
        print('.', end='')

        cv2.imshow('output', frame1)
        cv2.waitKey(delay)

    # 1번 동영상 뒷부분과 2번 동영상 앞부분을 합성
    for i in range(effect_frames):
        ret1, frame1 = cap1.read()
        ret2, frame2 = cap2.read()

        if not ret1 or not ret2:
            print('frame read error!')
            sys.exit()

        dx = int(w / effect_frames) * i

        frame = np.zeros((h, w, 3), dtype=np.uint8)
        frame[:, 0:dx, :] = frame2[:, 0:dx, :]
        frame[:, dx:w, :] = frame1[:, dx:w, :]

        #alpha = i / effect_frames
        #frame = cv2.addWeighted(frame1, 1 - alpha, frame2, alpha, 0)

        out.write(frame)
        print('.', end='')

        cv2.imshow('output', frame)
        cv2.waitKey(delay)

    # 2번 동영상을 복사
    for i in range(effect_frames, frame_cnt2):
        ret2, frame2 = cap2.read()

        if not ret2:
            print('frame read error!')
            sys.exit()

        out.write(frame2)
        print('.', end='')

        cv2.imshow('output', frame2)
        cv2.waitKey(delay)

    print('\noutput.avi file is successfully generated!')

    cap1.release()
    cap2.release()
    out.release()
    cv2.destroyAllWindows()

```

chap3 - 기본 영상 처리 기법

Ch 03. 기본적인 영상 처리 기법 - 01. 영상의 밝기 조절

  • 밝기 조절을 위한 함수 : cv2.add(src1, src2, dst=None, mask=None, dtype=None) -> dst

Ch 03. 기본적인 영상 처리 기법 - 02. 영상의 산술 및 논리 연산

  • 두 이미지 덧셉, 가중치 합
  • cv2.add(src1, src2, dst=None, mask=None, dtype=None) -> dst
  • cv2.addWeighted(src1, alpha, src2, beta, gamma, dst=None, dtype=None) -> dst
  • 두 이미지 뺄셈
  • cv2.subtract(src1, src2, dst=None, mask=None, dtype=None) -> dst
  • 두 이미지 차이 계산 dst( , ) = |src1( , ) - src2( , ) |
  • cv2.absdiff(src1, src2, dst=None) -> dst

Ch 03. 기본적인 영상 처리 기법 - 03. 컬러 영상 처리와 색 공간

  • b_plane, g_plane, r_plane = cv2.split(src)
  • b_plane = src[:, :, 0] g_plane = src[:, :, 1] r_plane = src[:, :, 2]
  • cv2.cvtColor(src, code, dst=None, dstCn=None) -> dst

Ch 03. 기본적인 영상 처리 기법 - 04. 히스토그램 분석

  • cv2.calcHist(images, channels, mask, histSize, ranges, hist=None, accumulate=None) -> hist

  • src = cv2.imread('lenna.bmp')
    colors = ['b', 'g', 'r']
    bgr_planes = cv2.split(src)
    for (p, c) in zip(bgr_planes, colors):
        hist = cv2.calcHist([p], [0], None, [256], [0, 256])
        plt.plot(hist, color=c)
    plt.show()
    

Ch 03. 기본적인 영상 처리 기법 - 05. 영상의 명암비 조절

  • dst( , ) = saturate(src( , ) + (src( , ) - 128) ) + a
  • image-20210114085414553
  •   src = cv2.imread('lenna.bmp', cv2.IMREAD_GRAYSCALE)
      alpha = 1.0
      dst = np.clip((1+alpha)*src - 128*alpha, 0, 255).astype(np.uint8)
    
  • 명암비 자동 조절

    • dst = cv2.normalize(src, None, 0, 255, cv2.NORM_MINMAX)

Ch 03. 기본적인 영상 처리 기법 - 06. 히스토그램 평활화

  • 히스토그램이 그레이스케일 전체 구간에서 균일한 분포로 나타나도록 변경하는 명암비 향상 기법
  • 히스토그램 균등화, 균일화, 평탄화
  • cv2.equalizeHist(src, dst=None) -> dst

Ch 03. 기본적인 영상 처리 기법 - 07. 특정 색상 영역 추출하기

  • 특정 범위 안에 있는 행렬 원소 검출 : cv2.inRange(src, lowerb, upperb, dst=None) -> dst

Ch 03. 기본적인 영상 처리 기법 - 08. 히스토그램 역투영

  • cv2.calcBackProject(images, channels, hist, ranges, scale, dst=None) -> dst
  • image-20210114090121180

Ch 03. 기본적인 영상 처리 기법 - 09. 실전 코딩 - 크로마키 합성

  • cv2.inRange() 함수를 사용하여 50 ≤ 𝐻 ≤ 80, 150 ≤ 𝑆 ≤ 255, 0 ≤ 𝑉 ≤ 255 범위의 영역을 검출
  • 마스크 연산을 지원하는 cv2.copyTo() 함수 사용
  • image-20210114090209199
  • 강의자료 FastCampus_CV\opencv_python_ch01_ch05\ch03\chroma_key.py 참조

chap4 - 필터링

  • cv2.filter2D

  • cv2.GaussianBlur

  • cv2.medianBlur(src, ksize, dst=None) -> dst

    • 주변 픽셀들의 값들을 정렬하여 그 중앙값(median)으로 픽셀 값을 대체
    • 소금-후추 잡음 제거에 효과적
  • cv2.bilateralFilter(src, d, sigmaColor, sigmaSpace, dst=None, borderType=None) -> dst

    • edge-preserving noise removal filter / Bilateral filter
    • 평균 값 필터 또는 가우시안 필터는 에지 부근에서도 픽셀 값을 평탄하게 만드는 단점
    • 에지가 아닌 부분에서만 blurring(잡음제거)
  • 카툰 필터 만들기

    • 아래의 방법은 사람들이 찾아낸 방법 중 하나. 다양한 방법이 있다.

    • image-20210114090945601

    • image-20210114091006607

    • # 카툰 필터 카메라
          
      import sys
      import numpy as np
      import cv2
          
      def cartoon_filter(img):
          h, w = img.shape[:2]
          img2 = cv2.resize(img, (w//2, h//2))
          blr = cv2.bilateralFilter(img2, -1, 20, 7)
          edge = 255 - cv2.Canny(img2, 80, 120)
          edge = cv2.cvtColor(edge, cv2.COLOR_GRAY2BGR)
          dst = cv2.bitwise_and(blr, edge)  # 논리 연산자
          dst = cv2.resize(dst, (w, h), interpolation=cv2.INTER_NEAREST)
          return dst
          
      def pencil_sketch(img):
          gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
          blr = cv2.GaussianBlur(gray, (0, 0), 3)
          dst = cv2.divide(gray, blr, scale=255)
          return dst
          
      cap = cv2.VideoCapture(0)
      if not cap.isOpened():
          print('video open failed!')
          sys.exit()
      cam_mode = 0
          
      while True:
          ret, frame = cap.read()
          if not ret:
              break
          if cam_mode == 1:
              frame = cartoon_filter(frame)
          elif cam_mode == 2:
              frame = pencil_sketch(frame)
              frame = cv2.cvtColor(frame, cv2.COLOR_GRAY2BGR)
          cv2.imshow('frame', frame)
          key = cv2.waitKey(1)
          if key == 27:
              break
          elif key == ord(' '):
              cam_mode += 1
              if cam_mode == 3:
                  cam_mode = 0
          
      cap.release()
      cv2.destroyAllWindows()
          
      

chap5 - 기하학적 변환

  • 수학적 공식은 ‘20년2학기/윤성민 교수님 컴퓨터 비전 수업 자료 참조’

  • cv2.warpAffine(src, M, dsize, dst=None, flags=None, borderMode=None, borderValue=None) -> dst

  • cv2.resize(src, dsize, dst=None, fx=None, fy=None, interpolation=None) -> dst

  • cv2.flip(src, flipCode, dst=None) -> dst

  • cv2.pyrDown(src, dst=None, dstsize=None, borderType=None) -> dst : 다중 피라미드 이미지 자동 return

  • cv2.pyrUp(src, dst=None, dstsize=None, borderType=None) -> dst

  • rot = cv2.getRotationMatrix2D(cp, 20, 1)

    • dst = cv2.warpAffine(src, rot, (0, 0))
  • 어파인 변환과 투시 변환

    • image-20210114091721057

    • cv2.getAffineTransform(src, dst) -> retval

    • cv2.getPerspectiveTransform(src, dst, solveMethod=None) -> retval

    • cv2.warpAffine(src, M, dsize, dst=None, flags=None, borderMode=None, borderValue=None) -> dst

    • cv2.warpPerspective(src, M, dsize, dst=None, flags=None, borderMode=None, borderValue=None) -> dst

    • src = cv2.imread('namecard.jpg')
      w, h = 720, 400
      srcQuad = np.array([[325, 307], [760, 369], [718, 611], [231, 515]],
      np.float32)
      dstQuad = np.array([[0, 0], [w-1, 0], [w-1, h-1], [0, h-1]], np.float32)
      pers = cv2.getPerspectiveTransform(srcQuad, dstQuad)
      dst = cv2.warpPerspective(src, pers, (w, h))
      
    • image-20210114091945757
  • 리매핑 : 영상의 특정 위치 픽셀을 다른 위치에 재배치하는 일반적인 프로세스

    • cv2.remap(src, Pixel좌표1, Pixel좌표2, interpolation, dst=None, borderMode=None, borderValue=None) -> dst
  • [실전 코딩] 문서 스캐너

    • 위의 방법 적절히 사용
    • 코드는 FastCampus_CV\opencv_python_ch01_ch05\ch03\docuscan.py 참조

chap6 - 영상의 특징 추출

  • 아래의 함수를 사용하고 싶다면, 어줍잖은 블로급 보지 말고 동영상 찾아보자.
  • cv2.Sobel(src, ddepth, dx, dy, dst=None, ksize=None, scale=None, delta=None, borderType=None) -> dst
  • cv2.Scharr(src, ddepth, dx, dy, dst=None, scale=None, delta=None, borderType=None) -> dst
  • 2D 벡터의 크기 계산 함수 : cv2.magnitude(x, y, magnitude=None) -> magnitude
  • 2D 벡터의 방향 계산 함수 : cv2.phase(x, y, angle=None, angleInDegrees=None) -> angle
  • cv2.Canny(image, threshold1, threshold2, edges=None, apertureSize=None, L2gradient=None) -> edges
  • cv2.HoughLines(image, rho, theta, threshold, lines=None, srn=None, stn=None, min_theta=None, max_theta=None) -> lines
  • cv2.HoughLinesP(image, rho, theta, threshold, lines=None, minLineLength=None, maxLineGap=None) -> lines
  • cv2.HoughCircles(image, method, dp, minDist, circles=None, param1=None, param2=None, minRadius=None, maxRadius=None) -> circles

【LinearAlgebra】선형대수 정리 3 (한글강의)

쑤튜브 선형대수 강의내용 정리 45~86강. - 57강 행공간의 보존 ~ 74강까지 패스. 너무 수학적임 나한테 아직 필요 없음

  • 나중에 꼭 들어야 하는 강의 -71강 : k < n, k개의 정규기저백터에서, n-k개의 추가 정규기저백터 찾기
    -72강 : 블록행렬. 내가 만든 열=다열, 행=행다 개념을 블록으로 설명하는 강의.

youtube 강의 링크 : 쓔튜브 선형대수 강의 링크

Matric 내적 정리 요약

  • 블록행렬 강의를 한번 보면 좋을 듯. 하지만 우선 아래는 내가 만든 공식
  • image-20210108203403357

Basis & Dimension

  • 45강, 46강 기저와 차원
  • 기저 백터의 조건
    • 선형적으로 독립
    • n차원이면 n개의 백터 이상.
  • 47강 기저 변환
    • E = {e1,e2,e3 … en} -> V = {v1,v2,v3 … vn} | e1과 v1은 백터 | v끼리는 서로 정규일 필요는 없다.
      • 아래에서 x(kn) 은 V의 원소들의 선형결합 계수 이다.
      • xk1v1 * xk2v2 * xk3v3 * … xknvn = ek | k = 1~n까지 n차 연립방정식
      • 위의 n개의 연립방정식으로 행렬로 표현하면 아래와 같다.
      • image-20210108203403357
      • 정리 :
        • image-20210108203850458
        • 일반화 (48강에서 증명)
          • (x1,x2 … xn)B = B의 기저백터들에 x1,x2,x3..xn의 계수로의 선형결합
          • image-20210108210028031
          • 예시
            image-20210108210028031
          • 해석 : B를 기저로 하는 좌표값이 x1~xn 이라면, 그 좌표를 B’을 기저로하는 좌표값으로 바꾸면 어떤 좌표 y1~yn이 되는가? 에 대한 공식이다.
      • 예제 :
        • (2,1)E는 E의 백터들에 2와 1의 계수로 선형결합 해준 백터 = v1 을 의미함.
        • image-20210108204107154
  • 48강 기저변환과 대각화(= EVD(Eigen Value Decomposition) 기초)
    • 대각화 : P * A * inverse(P) = D’(대각행렬) -> A =inverse(P) * D’(대각행렬) * P
    • 위의 일반화 공식과 고유백터&고유값을 이용해 대각화 공식을 찾아보자.
    • 대각변환 : 축을 기준으로 상수배(확대/축소)하는 변환
    • image-20210108213604777에 대해서 자세히 알아보자. 동영상에서는 위의 기저변환 일반화 공식을 이용해서 아래의 대각화 공식을 정의하고 있다.
      • [v1 v2] A’ [v1 v2]-1 = A’ 을 A의 고유백터 좌표를 기준으로 기저변환한 ‘결과’
      • [v1 v2] A’ [v1 v2]-1 = 위 ‘결과’를 다시 E를 기준으로 기저변환한 결과 = A !!
      • A와 A’은 위의 x1~xn, y1~yn과 같은 역할이다.
        • A’ 은 A의 고유값들로 만든 대각행렬, [v1 v2]는 A의 고유백터를 열백터로 가지는 행렬
        • A 는 [E(기본 좌표계)]를 기준좌표계(기저)로 생각하는 선형변환이다.
    • 고민을 많이 해야하므로 위의 내용을 이해하고 싶으면 강의를 다시 보자.
    • 이 대각화 공식을 다음과 같이 증명하면 쉽게 이해 가능하다.
      • image-20210108214614430
  • 49강 대각화가능행렬과 그 성질들
    • image-20210108214915839
    • 대각화 가능한 행렬 A는 n개의 선형독립인 고유백터를 가진다.
    • n개의 선형독립인 고유백터를 가지는 A는 대각화가 가능하다.
    • 대각화 왜해??
      • 대각행렬(D)은 n승을 하면, 대각원소의 n승인 행렬이다.
      • A^n = P * D^n * inverse(P)
      • A^n을 대각화로 엄청 쉽게 구할 수 있다!!
  • 50강 - 증명 : n차원에서 ‘n개의 원소를 가지는 백터 v’들의 선형독립 백터(v1 v2 … vn)의 최대갯수는 n개이다.
  • 51강 - 증명 : (1) A의 span(열백터들 or 행백터들) = n이면, A는 가역행렬이다. (2) 가역행렬(n차 정사각행렬)의 행백터, 열백터는 n dimention의 기저백터(독립!, 정규일 필요 X)이다.

Matrix similarity, Fuctnion, Space(닮음과 함수, 공간)

  • 52강 Matrix similarity(행렬의 닮음)
    • 두 행렬이 서로 닮음이면, 아래와 같은 많은 성질을 가진다.
    • image-20210109143042489
  • 53강 kernal and range(핵과 치역)
    • kernal : (m x n 행렬 (n차원 백터 -> m차원 백터 로 변환하는 행렬)) 선형사상 F행렬 (=선형함수,=선형변환)에 대해, F * x = {0백터}. 즉 F에 의해서 0백터가 돼버리는 백터(n차원 공간의 좌표)들. 이 백터들을 kernal, null space(영공간) 이라고 한다.
    • 선형사상 F에 의해서 n차원의 부분공간(원소들을 스칼라배, 덧셈을 하면 ‘집합 내의 원소’가 나오는 공간)이 m차원의 부분공간으로 변환됨
    • 선형변환 행렬 A에 대해, range(A) (Ax의 공간. x는 백터) = col(A) (A의 colum space 차원)이다.
    • 더 이해하고 싶으면, 53강 보충강의 보기
  • 54강 일대일 합수
    • 집합의 갯수를 새보자. A = {1,3,4} 3개이다. 새로은 집합 B의 갯수는 몇게 일까?
      • 집합 A와 B의 원소의 갯수가 같으려면, A와 B사이의 일대일 대응 함수가 존재함을 증명하면 된다.
      • 따라서 자연수집합과 정수 집합은 원소의 갯수가 같다. (일대일대응함수는 동영상 참조)
    • Thm : T ( R^n -> R^m ) 이라는 선형사상 T에 대해서, ‘T가 일대응 함수이다.’와 ‘kernal(T) = {0}이다.’ 는 동치이다.
      • 증명은 동영상 참조
  • 55강 전사 함수
    • 단사 : 일대일 대응이고 치역에 남은 원소가 있어도 됨.
    • 전사 : 일대잉 대응이고 치역에 남은 원소가 없다. 모든 정의역에 치역에 대응 됨.
    • 추가 증명 및 내용은 동영상 참조
  • 56강 직교여공간
    • 영공간(null space)
    • 행공간 = 영공간
      • rank (행백터 중 기저가 될 수 있는 백터의 최대 갯수)
    • 직교여공간(orthogonal complement)
      • 추후에 배울 최소제곱법에서 필요한 내용이다.
      • image-20210109163632668
      • non empty set : 영공간이 아닌 백터 집합
      • V = (1,1,1)의 직교여공간은 (1,1,1)를 법선백터로 가지는 평면이다.
      • 직교여공간에 0백터는 무조건 들어가 있다. 어떤 백터든 0백터를 곱하면 0백터가 되므로.
  • 57강 행공간의 보존
  • 74강까지 패스. 너무 수학적임 나한테 아직 필요 없음.

Orthogonal Diagnalizing & Eigen Value Decomposition & SVD

  • 75강 대각화가능 행렬(EVD, 교유값 분해)
    • 대각화 가능한 행렬은 n개의 선형독립인(정규일 필요 X) 고유백터를 가진다. = 모든 열백터가 독립이다. = 가역행렬이다.
  • 77강 직교행렬
    • A 직교행렬 : A의 모든 열백터(and 행백터)는 서로 orthonormal(정규) 하다.
    • 직교 변환 : 두 백터 v1,v2에 대해서 선형변환을 해도 두 백터의 길이(norm)이 유지되고, 두 백터와의 각도도 변하지 않는 변환을 말한다.
  • 78강 직교행렬의 조건
    1. (참조 transpose(T), trace(대각합) 서로 헷갈리지 말자.)
    2. inverse(A) = transpose(A)이면 A는 직교행렬이다.
      • image-20210109165441523
    3. A가 직교행렬이면 A의 행백터는 모두 orthonormal 하다.
    4. A가 직교행렬이면 transpose(A)도 직교행렬이다.
      • 이 모든것의 증명은 동영상 참조. 하지만 직교변환의 개념을 사용하므로 쉽지 않다. 일단 다 외어.
  • 79강 켤레 전치와 대칭 함수
    • 켤레 전치(confugate transpose) : A가 복소행렬(원소가 복소수)일 때, A의 결레전치행렬은
      • image-20210109165441523
      • 을 말한다. bar(A) : 모든 원소에 켤레복소수화. (1+i -> 1-i)
      • 컬레 전치의 기본 성질
          1. (A*)* = A
          2. (AB)* = (B*A*)*
    • 원소가 모두 실수로 이뤄진 ‘대칭행렬’의 고유값은 항상 실수 이다.
      • 증명은 동영상 참조.
  • 80강 직교대각화 가능(Orthogonal Diagonalizability)
    • 직교 닮음 이란?
      • C = inverse(P) * A * P (이때 P는 직교 행렬 : inverse(P) = transpose(P))
      • C는 A와 닮음이고, A는 C와 닮음이다.
      • 아래는 C가 D (대각행렬)
    • 직교 대각화(orthogonal diagonalizability)
      • image-20210109195906359
  • 81강 orthogonal diagonalizing (직교 대각화 하기)=Eigen Value Decomposition 시작
    • 대칭행렬이면 직교대각화가능 행렬이다.
    • 대칭행렬을 직교대각화 하는 방법.
      1. A가 대칭행렬이면, A의 고유백터들은 서로 ‘독립’일 뿐만 아니라 ‘직교’한다. = (‘서로 다른 고유공간’에 속한 고유백터는 서로 직교한다.)
        • ‘서로 다른 고유공간’ 이란?
          • 하나의 고유값에 대해서, 여러개의 고유백터들(1) 존재 가능(ex. 상수배 등)
          • 다른 고유값에 대한, 고유백터들(2)이 존재 할 때.
          • 고유백터들(1)과 고유백터(2)는 서로 직교한다. (당연한 얘기지만 일단 참고)
          • (아래) 선형변환 A를 내적 안에다 넣을 때는 inverse(A)가 들어간다. 증명은 17강 or 75강 참조.
        • image-20210109202311070
      2. 직교대각화하는방법
        1. A는 대칭행렬이다.
        2. A의 n개의 고유값을 구한다.(실수 고유값이 나온다.)
        3. 고유값에 맞는 orthonormal basis(단위 고유 직교 백터) n개 백터들을 구한다.
        4. 위의 n개의 백터를, 열백터로 가는 행렬 P를 만든다.
        5. inverse(P) A P = D(고유값으로 만든 대각행렬)
        6. 즉 A가 P에 의해서 대각행렬이 되었다.
      3. 직교대각화 예제
        1. image-20210110140953404
        2. 그람슈미트 변환을 알면, 고유값의 중근이 존재할 때, 중근인 고유값에 대한 2개의 기저백터를 뽑아내는 방법을 알 수 있다.
  • 82강 고유값 분해를 이용한 이미지 손실 압축(Eigen Value Decomposition)
    • image-20210110141923780
    • image-20210110150938824
  • 83강 SVD(Singular Value Decompostion)
    • 바로 위의 Eigen Value Decompostion의 시작은 대칭행렬이다! 대칭행렬만, 직교 대각화가 가능하므로.
    • A가 대칭행렬이 아니고, 정사각행렬이라면?? ㅠㅠ 직교대각화 (P * D * transpose(P)) 불가능!
    • A = U * Σ * transpose(V) 로 분해해보자.
    • A * transpose(A)는 대칭행렬이기 때문에, 교유백터들은 모두 독립일 뿐만 아니라 직교하다. 이 고유백터들을 각각 정규화(norm = 1)로 만들어 준 행렬이 아래의 V이다.
    • image-20215555
  • 84강 SVD 예제
    • image-20210110162049418
  • 85강 특이값 분해 일반화 (정사각행렬이 아닌 A)
    • image-20210110164410923
  • 86강 축소된 특이값 분해
    • image-20210110165648929

【Pytorch Package】 SSD Pytorch 'Module' Research

SSD package를 공부하면서 새로 익힌 내용들을 정리한다.

  • 아직 python에 대해서도 많은 부분을 모른다.
  • 모르는게 있으면, 끝까지 탐구하는 자세는 좋다. 하지만 너무 오랜 시간은 좋지 않다. 버릴건 버리고 나중에 필요하면 그때 다시 공부하면 이해가 될 수 있다.

1. py파일에서 부모 directory의 py파일에 접근

  • reference
    1. https://myjorney.tistory.com/52
    2. https://devlog.jwgo.kr/2019/09/17/how-to-test-package-created-by-myself/
  • 문제점 : 다음과 같은 파일 구조에서
      aa
          - a.py
          - bb
              - b.py
    

    b.py에서 from .. import a, from … import a 이 잘 동작하지 않는다.

  • 해결책 (위의 레퍼런스 요약)
    1. (1번째 refer) terminal에서 path를 b가 아닌 a에 두고, “$ python -m b/b.py”를 실행한다.
      • “-m” 옵션을 사용함으로써 모듈의 위치에 집중하라고 알려준다,
      • python을 실행할 때, 터미널의 pwd가 굉장히 중요하다,
    2. (추천-2번째 refer) setup.py를 이용한다.
      • sys.path.append 과거 블로그 설명과 사용법, sys.path.insert와 같은 방법. 혹은 컴퓨터의 환경변수를 넣어주는 방법 등이 있지만 모두 비추이다.
      • 나만의 패키지를 만들 때, 가장 맨위 디렉토리에 setup.py를 만들어 준다. 양식은 python공식문서를 참고하면 된다. 그리고 “$python setup.py install /or/ $ pip install .”을 해준다!!
    3. 나중에 setup.py 에 대해서 공부해보자. Google : how work setup.py

2. __init__.py 파일의 힘 (init.py)

  • 문제점
    • “아니 이게 왜 호출이 되지??? import한 적이 없는데???” 라는 생각을 자주해서 해당경로에 __init__.py에 들어가보면 import를 대신 해준것을 확인할 수 있었다.
    • 그렇다면 이게 어떻게 동작하는 걸까?
  • 결론 ⭐
    • 내가 만약 import package.dir1.dir2 를 파일 맨 위에 한다면, dir2에 있는 __init__.py 이 자동으로 호출되며 안의 내용을 모두 읽고 실행한다.
    • 만약 dir2의 __init__.py에 from .dir3.dir4 import fun4 가 있다면?
    • a.py에서 아래의 2가지 방법을 사용하면 된다.
      • from package.dir1 import dir2를 한다면, a.py에서 dir2.fun4로 써놓음으로써 fun4를 사용할 수 있다!!
      • from dir2 import fun4라고 한다면, a.py에서 fun4를 그대로 사용할 수 있다.
    • 원래는 a.py에서 fun4로만 생각해서, 직접 패키지를 만들고 실험을 해봤더니, 에러가 났다.
    • debugging을 해보니까, 다음과 같은 실행이 이뤄짐을 알 수 있었다.
      image
  • 궁금증2

    •   from mmdet.apis import inference_detector, init_detector, show_result_pyplot
      
    • 이러고 inference_detector, init_detector 함수를 그냥 사용할 수 있다. /mmdet/apis.py 파일이 있고, 저 파일안에 저 함수들이 정의되어 있다면 내가 궁금해하지도 않는다. 아래와 같은 구조를 하고 있기 때문이다.

    • image-20210128205145476

    • 물론 위의 문제점1에서 깨달았던 방법을 사용하면 아래와 같은 모듈사용이 가능했다.

        from mmdet import apis
              
        config = 'configs/mask_rcnn/mask_rcnn_r50_caffe_fpn_mstrain-poly_3x_coco.py'
        checkpoint = 'checkpoints/mask_rcnn_r50_caffe_fpn_mstrain-poly_3x_coco_bbox_mAP-0.408__segm_mAP-0.37_20200504_163245-42aa3d00.pth'
              
        model = apis.init_detector(config, checkpoint, device='cuda:0')
      
    • 어떻게 위의 form과 import의 실행이 가능했던 것일까??
  • 결론

    • from이 가르키는 마지막 directory의 __init__.py 또한 일단 다 읽는다! 그리고 import다음으로 넘어간다.
    • 우리가 아는 아주 당연한 방법으로, import 다음 내용으로 from A.B.C import py_file_name/function_defined 과 같이 import를 수행해도 된다.
    • 하지만 from 가장 마지막 directory의 (위의 예시에서 C)의 __init__.py 안에서 한번 import된 함수를 import해서 가져와도 된다.
    • 이를 이용해서, 궁금증2의 첫 실행문을 다시 설명하자면, from mmdet.apis 을 통해서 apis의 __init__.py를 모두 읽는다. 여기서 from .inference import (async_inference_detector, inference_detector,init_detector, show_result_pyplot) 이 수행되므로, import에서 import inference_detector, init_detector, show_result_pyplot를 하는 것에 전혀 무리가 없는 것이다.

3. os.path 모듈

  • reference : https://devanix.tistory.com/298
  • os.path.abspath(path)
  • os.path.basename(path)
  • os.path.commonprefix(path_list)
  • os.path.dirname(path) : 굳이 내가 \로 직접 자를 필요가 없었다.
  • os.path.exists(path)
  • os.path.getsize(path)
  • os.path.isfile(path)
  • os.path.isdir(path)
  • os.path.join(path1[,path2[,…]]) : 나의 os 확인하니, 일반 string class의 + 연산자보다 이게 낫겠다.
  • os.path.normpath(path) : 현재 디렉터리(“.”)나 상위 디렉터리(“..”)와 같은 구분자를 최대한 삭제

4. ModuleList

  •   class VGG(nn.Module):
          def __init__(self, cfg):
              super().__init__()
              size = cfg.INPUT.IMAGE_SIZE
              vgg_config = vgg_base[str(size)]
              extras_config = extras_base[str(size)]
        
              self.vgg = nn.ModuleList(add_vgg(vgg_config : [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'C', 512, 512, 512, 'M', 512, 512, 512]))
        
      def add_vgg(cfg, batch_norm=False):
          layers = []
          in_channels = 3
          for v in cfg:
              if v == 'M':
                  layers += [nn.MaxPool2d(kernel_size=2, stride=2)]
              elif v == 'C':
                  layers += [nn.MaxPool2d(kernel_size=2, stride=2, ceil_mode=True)]
              else:
                  conv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=1) 
                  if batch_norm:
                      layers += [conv2d, nn.BatchNorm2d(v), nn.ReLU(inplace=True)]
                  else:
                      layers += [conv2d, nn.ReLU(inplace=True)]
                  in_channels = v
          pool5 = nn.MaxPool2d(kernel_size=3, stride=1, padding=1)
          conv6 = nn.Conv2d(512, 1024, kernel_size=3, padding=6, dilation=6)
          conv7 = nn.Conv2d(1024, 1024, kernel_size=1)
          layers += [pool5, conv6,
                  nn.ReLU(inplace=True), conv7, nn.ReLU(inplace=True)]
          return layers
    
  • 코드 설명
    • ModuleList()에는 input으로 python-list가 들어가고 list-component는 nn.layer 이다.
    • conv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=1) 이 문장.
      • conv2d은 계속 새로운 nn.Conv2d 객체로 바끤다.
      • 아래의 코드를 참고해보자.
      •   >>> a = (1,2)
          >>> id(a)
          2289005091144
          >>> id((1,2))
          2289005102280
          >>> a = (1,2)
          >>> id(a)
          2289005092296
        
      • 이처럼 같은 클래스 tuple이지만, 객체 (1,2)는 다시 만들어지고 그것을 a가 가리킨다.

5. __init__() defined in Class

  • Class의 __init__함수는 객체 선언시 처음부터 끝까지 읽혀진다.
  • 아래의 코드에서도 self.set_c()까지 처리되는 것을 확인할 수 있다.
  •   class a():
      def __init__(self, a,b):
          self.a = a
          self.b = b
          self.c = 1
          self.set_c()
        
      def set_c(self):
          self.c = self.a + self.b
        
      obj = a(4,3)
      print(obj.c) 
      >> 7
    
  •   class VGG(nn.Module):
      def __init__(self, cfg):
          super().__init__()
          size = cfg.INPUT.IMAGE_SIZE
          vgg_config = vgg_base[str(size)]
          extras_config = extras_base[str(size)]
        
          self.vgg = nn.ModuleList(add_vgg(vgg_config))
          self.extras = nn.ModuleList(add_extras(extras_config, i=1024, size=size))
          self.l2_norm = L2Norm(512, scale=20)
          self.reset_parameters()
    
  • 따라서 위 코드의 reset_parameters도 반드시 실행된다.

6. torch.tensor.function (permute, contiguous)

  •   cls_logits = []
      bbox_pred = []
      for feature, cls_header, reg_header in zip(features, self.cls_headers, self.reg_headers):
          cls_logits.append(cls_header(feature).permute(0, 2, 3, 1).contiguous())
          bbox_pred.append(reg_header(feature).permute(0, 2, 3, 1).contiguous())
    
  • 위의 cls_header, reg_header 는 nn.Conv2d 이다.
  • torch document에 적혀 있는 view는 tensor의 shape, size를 의미한다. view라는 단어를 더 자주쓰지 하나의 명사로 알아두기

7. os.environ([“variable”])

  • 터미널 내부 환경 변수를 읽어오는 모듈이다.
  • $ export COCO_ROOT=”/path/to/coco_root” 와 같이 환경변수를 설정해 두면, python내부 os.environ 함수가 이 환경변수를 읽오와 변수에 저장해둔다.
  • drawing

8. package 다운 후 코드 수정하기

  • 궁금증 :
    • $python setup.py install / $ pip install .
    • 이 명령어를 이용해서, package의 setup을 마친 상태라고 치자.
    • setup을 하고 난 후, package의 코드를 바꾸면 다시 setup을 실행해줘야 하는가?
    • 아니면 setup은 처음에만 하고, 코드 수정 후 그냥 사용하기만 하며 되는가?
  • 해답 :
    • 정답은 ‘처음에만 setup 해주면 된다.’ 이다
    • 아래와 같은 세팅의 실험에서, 내가 추가해준 코드가 아주 잘 실행되는 것을 확인할 수 있었다.
    • image

Pagination


© All rights reserved By Junha Song.