next up previous
Next: 5 画像処理 Up: 4 画像の入出力 Previous: 4.1 画像ファイルの読込

4.2 ヒストグラム作成

図 5: ヒストグラム
\includegraphics[width=7.8cm]{/home/inaba/eps/lecture/fig/AiboAkiraHistogram.eps}
// ImageHistogramGraph.java
/*
  <applet code="ImageHistogramGraph.class"
  width=967 height =747>
  </applet>
*/
// for Applet
import java.applet.*;
// for Graphics, Image, MediaTracker
import java.awt.*;
// for PixelGrabber
import java.awt.image.*;
 
public class ImageHistogramGraph
  extends Applet {
  Image image;
  int w;
  int h;
  int ih[] = new int[256]; // intensity
  int ah[] = new int[256]; // alfa
  int rh[] = new int[256]; // red
  int gh[] = new int[256]; // green
  int bh[] = new int[256]; // blue

  public void init(){
    MediaTracker mt = new MediaTracker(this);
    image = getImage(getDocumentBase(),
                     "aiboakira.jpg");
    mt.addImage(image,0);
    try {
      mt.waitForID(0);
    } catch(InterruptedException e) {
    }
    histogram(image);
  }
  static void graph(Graphics g, int w,
                    int h, int [] hist, Color c) {
    int x0=40; int y0=10;
    int xw=w-x0*2; int yw=h-y0*2;
    double scale=6000.0/(w*h);
    for (int i=0; i<hist.length-1; i++) {
      g.setColor(c);
      g.drawLine(x0+xw*i/hist.length,
                 h-y0-(int)(hist[i]*scale),
                 x0+xw*(i+1)/hist.length,
                 h-y0-(int)(hist[i+1]*scale));
    }
    g.setColor(Color.black);
    g.drawLine(x0,h-y0,x0,h-y0-yw);
    g.drawLine(x0,h-y0,x0+xw,h-y0);
    g.drawLine(x0+xw,h-y0-yw,x0,h-y0-yw);
    g.drawLine(x0+xw,h-y0,x0+xw,h-y0-yw);

  }
  static void prt(String str, int[] a) {
    int i=0;
    System.out.print(str +"{");
    if (i<a.length) System.out.print(a[i++]);
    while (i<a.length) {
      System.out.print("," + a[i++]);
    }
    System.out.println("}");
  }
  void histogram(Image img){
    int v; int a; int r; int g; int b; int i;
    w= img.getWidth(this);
    h= img.getHeight(this);
    int pixels[]= new int[w*h];
    PixelGrabber pg =
      new PixelGrabber(img,0,0,w,h,pixels,0,w);

    try { pg.grabPixels();
    } catch (InterruptedException e) {
      showStatus(" "+ e);
    }
    for (int x=0; x< w; x++) 
      for (int y=0; y< h; y++) {
        v = pixels[x+y*w];
        a = (v>>24)& 0xff;
        r = (v>>16)& 0xff;
        g = (v>>8)& 0xff;
        b = v & 0xff;
        i = (int)(0.299*r +0.587*g +0.114*b);
        ih[i]++;
        ah[a]++;
        rh[r]++;
        gh[g]++;
        bh[b]++;
      }
    System.out.println("w= " + w + " h= " + h);
    prt(" alfa:", ah);
    prt(" r:", rh);
    prt(" g:", gh);
    prt(" b:", bh);
    prt(" i:", ih);
  }
  
  public void paint(Graphics g){
    g.drawImage(image, 0, 0, this);
    graph(g, w,h, rh, Color.red);
    graph(g, w,h, gh, Color.green);
    graph(g, w,h, bh, Color.blue);
    graph(g, w,h, ih, Color.white);
  }
}


generated through LaTeX2HTML. M.Inaba 平成18年5月7日