Android 在 Facedetection 中祝酒 API

Android show a toast in Facedetection API

相当简单 Android 麻烦:我正在尝试在 Android Cookbook 示例中展示一个 Android "Toast" 的人脸检测示例。但是,我在代码末尾包含的 FaceDetectionView.java 中似乎不允许使用 Toast 方法。我得到的错误代码如下:

Error:(113, 22) error: no suitable method found for makeText(FaceDetectionView,float,int)
method Toast.makeText(Context,int,int) is not applicable
(actual argument FaceDetectionView cannot be converted to Context by method invocation conversion)
method Toast.makeText(Context,CharSequence,int) is not applicable
(actual argument FaceDetectionView cannot be converted to Context by method invocation conversion)

这是Main.java:

package com.examples.androface;

import android.app.Activity;
import android.os.Bundle;

public class Main extends Activity
    {
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState)
            {
                super.onCreate(savedInstanceState);
                setContentView(new FaceDetectionView(this, "face5.JPG"));
            }
    }

这是FaceDetectionView.java:

package com.examples.androface;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.Rect;
import android.media.FaceDetector;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

/**
 * @author wdavid01
 * 
 */
public class FaceDetectionView extends View
  {
    private static final String tag = FaceDetectionView.class.getName();
    private static final int NUM_FACES = 10;
    private FaceDetector arrayFaces;
    private final FaceDetector.Face getAllFaces[] = new FaceDetector.Face[NUM_FACES];
    private FaceDetector.Face getFace = null;

    private final PointF eyesMidPts[] = new PointF[NUM_FACES];
    private final float eyesDistance[] = new float[NUM_FACES];

    private Bitmap sourceImage;

    private final Paint tmpPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    private final Paint pOuterBullsEye = new Paint(Paint.ANTI_ALIAS_FLAG);
    private final Paint pInnerBullsEye = new Paint(Paint.ANTI_ALIAS_FLAG);

    private int picWidth, picHeight;
    private float xRatio, yRatio;
    private ImageLoader mImageLoader = null;

    public FaceDetectionView(Context context, String imagePath)
      {
        super(context);
        init();
        mImageLoader = ImageLoader.getInstance(context);
        sourceImage = mImageLoader.loadFromFile(imagePath);
        detectFaces();

      }

    private void init()
      {
        Log.d(tag, "Init()...");
        pInnerBullsEye.setStyle(Paint.Style.FILL);
        pInnerBullsEye.setColor(Color.RED);
        pOuterBullsEye.setStyle(Paint.Style.STROKE);
        pOuterBullsEye.setColor(Color.RED);
        tmpPaint.setStyle(Paint.Style.STROKE);
        tmpPaint.setTextAlign(Paint.Align.CENTER);
        BitmapFactory.Options bfo = new BitmapFactory.Options();
        bfo.inPreferredConfig = Bitmap.Config.RGB_565;

      }

    private void loadImage(String imagePath)
      {
        sourceImage = mImageLoader.loadFromFile(imagePath);
      }

    @Override
    protected void onDraw(Canvas canvas)
      {
        Log.d(tag, "onDraw()...");

        xRatio = getWidth() * 1.0f / picWidth;
        yRatio = getHeight() * 1.0f / picHeight;
        canvas.drawBitmap(sourceImage, null, new Rect(0, 0, getWidth(), getHeight()), tmpPaint);
        for (int i = 0; i < eyesMidPts.length; i++)
          {
            if (eyesMidPts[i] != null)
              {
                pOuterBullsEye.setStrokeWidth(eyesDistance[i] / 6);
                canvas.drawCircle(eyesMidPts[i].x * xRatio, eyesMidPts[i].y * yRatio, eyesDistance[i] / 2, pOuterBullsEye);
                canvas.drawCircle(eyesMidPts[i].x * xRatio, eyesMidPts[i].y * yRatio, eyesDistance[i] / 6, pInnerBullsEye);
              }
          }
      }

    private void detectFaces()
      {
        Log.d(tag, "detectFaces()...");

        picWidth = sourceImage.getWidth();
        picHeight = sourceImage.getHeight();

        arrayFaces = new FaceDetector(picWidth, picHeight, NUM_FACES);
        arrayFaces.findFaces(sourceImage, getAllFaces);

        for (int i = 0; i < getAllFaces.length; i++)
          {
            getFace = getAllFaces[i];
            try
              {
                PointF eyesMP = new PointF();
                getFace.getMidPoint(eyesMP);
                eyesDistance[i] = getFace.eyesDistance();
                eyesMidPts[i] = eyesMP;

                Log.i("Face", i + " " + getFace.confidence() + " " + getFace.eyesDistance() + " " + "Pose: (" + getFace.pose(FaceDetector.Face.EULER_X) + "," + getFace.pose(FaceDetector.Face.EULER_Y) + "," + getFace.pose(FaceDetector.Face.EULER_Z) + ")" + "Eyes Midpoint: (" + eyesMidPts[i].x + "," + eyesMidPts[i].y + ")");
                Toast.makeText(FaceDetectionView.this, getFace.confidence(),
                        Toast.LENGTH_LONG).show();
              }
            catch (Exception e)
              {
                Log.e("Face", i + " is null");
              }
          }
      }
  }

@RRR 在应用下面的解决方案后,即使代码是在 运行 时编译的,我收到此错误消息: 似乎上下文仍然没有正确创建:

20106-20106/com.examples.androface E/AndroidRuntime: FATAL EXCEPTION: main
                                                                        Process: com.examples.androface, PID: 20106
                                                                        java.lang.RuntimeException: Unable to start activity ComponentInfo{com.examples.androface/com.examples.androface.Main}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
                                                                            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
                                                                            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
                                                                            at android.app.ActivityThread.access0(ActivityThread.java:151)
                                                                            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
                                                                            at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                            at android.os.Looper.loop(Looper.java:135)
                                                                            at android.app.ActivityThread.main(ActivityThread.java:5257)
                                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                                            at java.lang.reflect.Method.invoke(Method.java:372)
                                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
                                                                         Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
                                                                            at android.widget.Toast.<init>(Toast.java:101)
                                                                            at android.widget.Toast.makeText(Toast.java:258)
                                                                            at com.examples.androface.FaceDetectionView.detectFaces(FaceDetectionView.java:122)
                                                                            at com.examples.androface.FaceDetectionView.<init>(FaceDetectionView.java:52)
                                                                            at com.examples.androface.Main.onCreate(Main.java:13)
                                                                            at android.app.Activity.performCreate(Activity.java:5990)
                                                                            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
                                                                            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
                                                                            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390) 
                                                                            at android.app.ActivityThread.access0(ActivityThread.java:151) 
                                                                            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
                                                                            at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                            at android.os.Looper.loop(Looper.java:135) 
                                                                            at android.app.ActivityThread.main(ActivityThread.java:5257) 
                                                                            at java.lang.reflect.Method.invoke(Native Method) 
                                                                            at java.lang.reflect.Method.invoke(Method.java:372) 
                                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
                                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 
01-04 05:27:26.006 20106-20112/com.examples.androface W/art: Suspending all threads took: 16.056ms
01-04 05:27:49.109 20106-20106/? I/Process: Sending signal. PID: 20106 SIG: 9

试试这个:添加用于保存上下文的新变量

package com.examples.androface;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.Rect;
import android.media.FaceDetector;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

/**
* @author wdavid01
* 
*/
public class FaceDetectionView extends View
{
private static final String tag = FaceDetectionView.class.getName();
private static final int NUM_FACES = 10;
private FaceDetector arrayFaces;
private final FaceDetector.Face getAllFaces[] = new FaceDetector.Face[NUM_FACES];
private FaceDetector.Face getFace = null;

private final PointF eyesMidPts[] = new PointF[NUM_FACES];
private final float eyesDistance[] = new float[NUM_FACES];

private Bitmap sourceImage;

private final Paint tmpPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
private final Paint pOuterBullsEye = new Paint(Paint.ANTI_ALIAS_FLAG);
private final Paint pInnerBullsEye = new Paint(Paint.ANTI_ALIAS_FLAG);

private int picWidth, picHeight;
private float xRatio, yRatio;
private ImageLoader mImageLoader = null;
private Context context;

public FaceDetectionView(Context context, String imagePath)
  {
    super(context);
    init();
    this.context = context;
    mImageLoader = ImageLoader.getInstance(context);
    sourceImage = mImageLoader.loadFromFile(imagePath);
    detectFaces();

  }

private void init()
  {
    Log.d(tag, "Init()...");
    pInnerBullsEye.setStyle(Paint.Style.FILL);
    pInnerBullsEye.setColor(Color.RED);
    pOuterBullsEye.setStyle(Paint.Style.STROKE);
    pOuterBullsEye.setColor(Color.RED);
    tmpPaint.setStyle(Paint.Style.STROKE);
    tmpPaint.setTextAlign(Paint.Align.CENTER);
    BitmapFactory.Options bfo = new BitmapFactory.Options();
    bfo.inPreferredConfig = Bitmap.Config.RGB_565;

  }

private void loadImage(String imagePath)
  {
    sourceImage = mImageLoader.loadFromFile(imagePath);
  }

@Override
protected void onDraw(Canvas canvas)
  {
    Log.d(tag, "onDraw()...");

    xRatio = getWidth() * 1.0f / picWidth;
    yRatio = getHeight() * 1.0f / picHeight;
    canvas.drawBitmap(sourceImage, null, new Rect(0, 0, getWidth(), getHeight()), tmpPaint);
    for (int i = 0; i < eyesMidPts.length; i++)
      {
        if (eyesMidPts[i] != null)
          {
            pOuterBullsEye.setStrokeWidth(eyesDistance[i] / 6);
            canvas.drawCircle(eyesMidPts[i].x * xRatio, eyesMidPts[i].y * yRatio, eyesDistance[i] / 2, pOuterBullsEye);
            canvas.drawCircle(eyesMidPts[i].x * xRatio, eyesMidPts[i].y * yRatio, eyesDistance[i] / 6, pInnerBullsEye);
          }
      }
  }

private void detectFaces()
  {
    Log.d(tag, "detectFaces()...");

    picWidth = sourceImage.getWidth();
    picHeight = sourceImage.getHeight();

    arrayFaces = new FaceDetector(picWidth, picHeight, NUM_FACES);
    arrayFaces.findFaces(sourceImage, getAllFaces);

    for (int i = 0; i < getAllFaces.length; i++)
      {
        getFace = getAllFaces[i];
        try
          {
            PointF eyesMP = new PointF();
            getFace.getMidPoint(eyesMP);
            eyesDistance[i] = getFace.eyesDistance();
            eyesMidPts[i] = eyesMP;

            Log.i("Face", i + " " + getFace.confidence() + " " + getFace.eyesDistance() + " " + "Pose: (" + getFace.pose(FaceDetector.Face.EULER_X) + "," + getFace.pose(FaceDetector.Face.EULER_Y) + "," + getFace.pose(FaceDetector.Face.EULER_Z) + ")" + "Eyes Midpoint: (" + eyesMidPts[i].x + "," + eyesMidPts[i].y + ")");
            Toast.makeText(context, getFace.confidence() + "",
                    Toast.LENGTH_LONG).show();
          }
        catch (Exception e)
          {
            Log.e("Face", i + " is null");
          }
      }
  }
}

您不能在 Toast.makeText 的第一个参数中使用 View

改为尝试

Toast.makeText(getContext(), getFace.confidence(),
                    Toast.LENGTH_LONG).show();

Context存储在一个变量中

Context context;
public FaceDetectionView(Context context, String imagePath)
{
     this.context=context;
     //rest of your code
}

在您尝试显示时使用上下文 Toast

Toast.makeText(context, getFace.confidence(),
                    Toast.LENGTH_LONG).show();

确保 getFace.confidence() 应该是字符串值,否则将其与 ""

连接
Toast.makeText(context, ""+getFace.confidence(),
                    Toast.LENGTH_LONG).show();