Tuesday, August 07, 2012

groovyで画像を二値化してぼかす

groovyで画像を二値化してぼかすには、以下のコードを実行します。
@Grab(group='com.jhlabs', module='filters', version='2.0.235')
import java.awt.*
import java.awt.image.*
import java.io.*
import javax.imageio.*
import com.jhlabs.composite.*
import com.jhlabs.image.*

// 二値化してぼかす
def img = ImageIO.read(new File("sf2.jpg"))
def imga = new BufferedImage(
    img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_ARGB
)
def gr = imga.createGraphics()
gr.drawImage(img,0,0,null)
gr.dispose()

def threshold = 127
def white = (int)0x00000000
def black = (int)0xff5d6056

def wr = imga.getRaster()
def buf = new int[4]
for(int ly=0;ly<wr.getHeight();ly++){
  for(int lx=0;lx<wr.getWidth();lx++){
    wr.getPixel(lx, ly, buf)

    if( PixelUtils.brightness((buf[0]<<16)+(buf[1]<<8)+buf[2]) > threshold ){
      buf[0] = (white >> 16) & 0xff
      buf[1] = (white >> 8) & 0xff
      buf[2] = white & 0xff
      buf[3] = (white >> 24) & 0xff
    } else {
      buf[0] = (black >> 16) & 0xff
      buf[1] = (black >> 8) & 0xff
      buf[2] = black & 0xff
      buf[3] = (black >> 24) & 0xff
    }

    wr.setPixel(lx, ly, buf)
  }
}
def gf = new GaussianFilter()
gf.setRadius(5f)
imga = gf.filter(imga, null)

ImageIO.write(imga, "png", new File("thresholdblur.png"))


元画像

出力画像


動作環境
groovy 1.8.6, JDK7 update4

No comments: