2016-10-24 5 views
-1

イメージから顔を検出し、その周囲に赤い四角形を描くこのコードがありますが、実行時例外があります。私は、顔検出コードの多くを試してみましたが、また私はアンドロイドのイメージから顔を検出したい

{ 
    public class MainActivity extends AppCompatActivity 
    { 
Button btn = (Button) findViewById(R.id.button); 
ImageView myImageView = (ImageView) findViewById(R.id.imgview); 

@Override 
protected void onCreate(Bundle savedInstanceState) 

{ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 




    btn.setOnClickListener(new View.OnClickListener() 
    { 
     @Override 
     public void onClick(View v) 
     { 
      BitmapFactory.Options options = new BitmapFactory.Options(); 
      options.inMutable=true; 
      Bitmap myBitmap = BitmapFactory.decodeResource(
        getApplicationContext().getResources(), 
        R.drawable.test1, 
        options); 

      Paint myRectPaint = new Paint(); 
      myRectPaint.setStrokeWidth(5); 
      myRectPaint.setColor(Color.RED); 
      myRectPaint.setStyle(Paint.Style.STROKE); 

      Bitmap tempBitmap = Bitmap.createBitmap(myBitmap.getWidth(), myBitmap.getHeight(), Bitmap.Config.RGB_565); 
      Canvas tempCanvas = new Canvas(tempBitmap); 
      tempCanvas.drawBitmap(myBitmap, 0, 0, null); 

      FaceDetector faceDetector = new 
        FaceDetector.Builder(getApplicationContext()).setTrackingEnabled(false) 
        .build(); 
      if(!faceDetector.isOperational()){ 
       new AlertDialog.Builder(v.getContext()).setMessage("Could not set up the face detector!").show(); 
       return; 
      } 
      Frame frame = new Frame.Builder().setBitmap(myBitmap).build(); 
      SparseArray<Face> faces = faceDetector.detect(frame); 

      for(int i=0; i<faces.size(); i++) { 
       Face thisFace = faces.valueAt(i); 
       float x1 = thisFace.getPosition().x; 
       float y1 = thisFace.getPosition().y; 
       float x2 = x1 + thisFace.getWidth(); 
       float y2 = y1 + thisFace.getHeight(); 
       tempCanvas.drawRoundRect(new RectF(x1, y1, x2, y2), 2, 2, myRectPaint); 
      } 
      myImageView.setImageDrawable(new BitmapDrawable(getResources(),tempBitmap)); 

     } 
    }); 


} 

}

 here is the exception 
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.hadeel.hadd/com.example.hadeel.hadd.MainActivity}: java.lang.NullPointerException 
+0

この例外の原因となった例外については、ログの猫にもっと多くの情報が必要です。多くの場合、警告レベル –

答えて

1

Button btn = (Button) findViewById(R.id.button); ImageView myImageView = (ImageView) findViewById(R.id.imgview);

動作しませんでした

上記のアンドロイドウィジェットへの参照を保持する変数の初期化は行わないでください。これは、アクティビティのレイアウトが膨らんでいないためです(onCreateメソッドはこのオブジェクトの作成後に実行されます)。方法の直後にfindViewByIdの呼び出しを移動する必要があります。setContentView

+0

に感謝、それは動作しますが、私は画像を変更したい場合は、他の例外が表示されます – HadeelAzzeh

関連する問題