読者です 読者をやめる 読者になる 読者になる

Daily Creative Coding

元「30 min. Processing」。毎日、Creative Codingします。

画像を鮮鋭化(アンシャープ化)する

画像処理

入力画像

f:id:aa_debdeb:20151127095933j:plain

出力画像

f:id:aa_debdeb:20151127095945j:plain
/**
* Unsharp Masking
*
* @author aa_debdeb
* @date 2015/12/01
*/

void setup(){
  size(512, 512);
  noLoop();
  PImage image = loadImage("blur_lena.jpg");
  image(image, 0, 0);
  int winSize = 5;
  int halfWinSize = winSize / 2;
  println(halfWinSize);
  float intensity = 10.0;
  
  color[][] blurImage = new color[width][height];
  loadPixels();
  for(int x = 0; x < width; x++){
    for(int y = 0; y < height; y++){
      if(x <= halfWinSize - 1 || x >= width - halfWinSize || y <= halfWinSize - 1 || y >= height - halfWinSize){
        blurImage[x][y] = color(0);
      } else {
        float r = 0, g = 0, b = 0;
        for(int u = x - halfWinSize; u <= x + halfWinSize; u++){
          for(int v = y - halfWinSize; v <= y + halfWinSize; v++){
            color c = pixels[v * width + u];
            r += red(c);
            g += green(c);
            b += blue(c);
          }
        }
        r /= float(winSize) * winSize;
        g /= float(winSize) * winSize;
        b /= float(winSize) * winSize;
        blurImage[x][y] = color(r, g, b);
      }
    }
  }
    
  for(int x = 0; x < width; x++){
    for(int y = 0; y < height; y++){
      if(x <= halfWinSize - 1 || x >= width - halfWinSize || y <= halfWinSize - 1 || y >= height - halfWinSize){
        pixels[y * width + x] = blurImage[x][y];
      } else {
        color c = pixels[y * width + x];
        color blur = blurImage[x][y];
        float variantR = (red(c) - red(blur)) * intensity;
        float variantG = (green(c) - green(blur)) * intensity;
        float variantB = (blue(c) - blue(blur)) * intensity;
        pixels[y * width + x] = color(red(c) + variantR, green(c) + variantG, blue(c) + variantB);
      }
    }
  }
  
  updatePixels();
}