R から ADSC 形式の画像を書き出す

バイナリファイル書き出しの練習として。

writeADSC <- function(filename, img, lambda_in_A=1.0, orgx=ncol(img)/2.0, orgy=nrow(img)/2.0,
                      pixel_size=0.172, camera_length_in_mm=50.0) {
  width <- ncol(img)
  height <- nrow(img)
  conn <- file(filename, "wb")
  header <- sprintf(paste0(
        "{\n",
        "HEADER_BYTES=512;\n",
        "DIM=2;\n",
        "BYTE_ORDER=little_endian;\n",
        "TYPE=unsigned_short;\n",
        "SIZE1=%d;\n",
        "SIZE2=%d;\n",
        "PIXEL_SIZE=%f;\n",
        "WAVELENGTH=%f;\n",
        "DISTANCE=%f;\n",
        "PHI=0.0;\n",
        "OSC_START=0.00;\n",
        "OSC_END=0.01;\n",
        "OSC_RANGE=0.01;\n",
        "AXIS=phi;\n",
        "BEAM_CENTER_X=%f;\n",
        "BEAM_CENTER_Y=%f;\n",
        "}\n"), 
        width, height, pixel_size,
        lambda_in_A, camera_length_in_mm,
        orgx, orgy)
  suppressWarnings(writeChar(header, conn, 511))
  writeBin(as.integer(as.vector(img)), conn, size=2, endian="little")
  close(conn)
}

NX <- 20
NY <- 20
img <- matrix(rpois(NX * NY, 1), NX, NY)
writeADSC("test001.img", img)