我有这个代码来检测图像中的面部并在其周围绘制一个红色矩形,但我有一个运行时异常可以任何人修复它请我不知道该怎么做,我尝试了很多面部检测代码但是也没有工作
{
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 :(得分:2)
Button btn = (Button) findViewById(R.id.button); ImageView myImageView = (ImageView) findViewById(R.id.imgview);
你不应该对包含如上所述的android小部件的引用的变量进行初始化,因为活动的布局不会膨胀(方法onCreate将在创建此对象后运行)。您应该在方法findViewById
setContentView