04-07 06:55
Notice
Recent Posts
Recent Comments
관리 메뉴

Scientific Computing & Data Science

[Programming / Image Processing] Binary Image를 Text 파일로 변환하기 본문

Scientific Computing/Image Processing

[Programming / Image Processing] Binary Image를 Text 파일로 변환하기

cinema4dr12 2016. 6. 10. 23:58

이번 글에서는 R을 이용하여 필기된 숫자가 포함된 이미지를 0과 1의 binary text 형식으로 변환하는 방법에 대하여 알아보겠다.


우선 R의 Image Processing Package인 EBImage를 다운로드한다.


source("http://bioconductor.org/biocLite.R")
biocLite("EBImage")



다음과 같이 필기된 숫자가 포함된 이미지를 0과 1의 binary text 형식으로 변환하는 R 함수를 작성하였다:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
####################################################################################################
# @function : ConvertImageToText
# @author : Geol Choi, phD
# @email  : cinema4dr12@gmail.com
# @date   : 06/10/2016
####################################################################################################
ConvertImageToText <- function(imgName, threshold, fileName) {
  library("EBImage");
   
  img <- readImage(imgName);
   
  # convert input image to grayscale image
  colorMode(img) <- Grayscale;
   
  # image resize to 64-by-64
  img = resize(img, w = 64, h = 64)
   
  # make a binary image
  img_bin <- img > threshold;
   
  # display the binary image to plot
  display(img_bin, method="raster");
  
  # extract the first color element of the grayscaled image
  img_new <- img_bin[,,1];
   
  height <- dim(img_new)[1];
  width <- dim(img_new)[2];
   
  # if "TRUE" set the value to "0" and if "FALSE" set the value to "1"
  img_new[img_new == "TRUE"] <- "0";
  img_new[img_new == "FALSE"] <- "1";
   
  # write into file
  cat(paste(img_new[,1], sep = "", collapse = ""), file = fileName, sep = "\n");
  for(i in 2:height) {
    cat(paste(img_new[,i], sep = "", collapse = ""), file = fileName, sep="\n", append = TRUE);
  }
}



입력 파라미터는 다음과 같다:


@imgName : 이미지 파일 이름

@threshold : Binary 텍스트를 생성할 기준, 0과 1 사이 값이며 해당 픽셀 값이 이 값과 같거나 보다 작으면 "FALSE"를 이 값보다 크면 "TRUE"를 저장

@fileName : Binary Text를 저장할 파일 이름



이제 이미지 편집기 등을 이용하여 숫자를 하나 쓰고 이미지를 저장한다.


설명을 위해 다음 이미지를 준비하였다.


[4.jpg]




R 콘솔에 ConvertImageToText.R 소스를 등록하고 예를 들어 다음과 같이 입력한다.


> ConvertImageToText("4.jpg", 0.5, "outfile.txt")



출력 결과는 다음과 같다.


우선 Binary Image는 다음과 같이 출력되며,






Binary Text 출력 파일은 다음과 같다:




이 글은 Machine Learning 알고리즘을 통해 필기를 인식하기 위한 전과정(Pre-Step)이며, 다음 글에서 필기 인식 알고리즘에 대하여 알아보도록 하겠다.



Comments