Screen turning black after face detection using ML kit - android

The upload image function is working but when the detection is initiated the face are detected and then the whole section of the ImageView is turned black.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tempbitmap= Bitmap.createBitmap(bitmap.getWidth(),bitmap.getHeight(),Bitmap.Config.RGB_56);
imageView = (ImageView)findViewById(R.id.imageView);
button = (Button) findViewById(R.id.button)
canvas = new Canvas(tempbitmap);
final Paint paint = new Paint();
paint.setStrokeWidth(5);
paint.setColor(Color.RED);
paint.setStyle(Paint.Style.STROKE);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FaceDetector faceDetector = new FaceDetector.Builder(getApplicationContext())
.setTrackingEnabled(false)
.setLandmarkType(FaceDetector.ALL_LANDMARKS)
.setMode(FaceDetector.FAST_MODE)
.build();
frame = new Frame.Builder().setBitmap(bitmap).build();
SparseArray<Face> sparseArray = faceDetector.detect(frame);
for (int i=0;i<sparseArray.size();i++)
{
Face face = sparseArray.valueAt(i);
float x = face.getPosition().x;
float y = face.getPosition().y;
float x1 = x + face.getWidth();
float y1 = y + face.getHeight();
RectF rectF = new RectF(x,y,x1,y1);
canvas.drawRoundRect(rectF,2,2,paint);
}
imageView.setImageBitmap(tempbitmap);
}
});
}

Related

i want to detect face from image in android

I have this code to detect face from an image and draw a red rectangle around it, but I have a run time exception can anyone fix it please i have no idea what to do , i tried a lot of face detection code but also didn't work
{
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
Button btn = (Button) findViewById(R.id.button);
ImageView myImageView = (ImageView) findViewById(R.id.imgview);
You shouldn't do initialization of variables which hold references to android widgets like above, because layout of activity is not inflated (method onCreate will run after creation of this object). You should move invocation of findViewById right after method setContentView

getting wrong x y from OnTouchListener

I'm trying to draw a circle where I touch so I'm using the OnTouchListener to get the x,y coordinates.
But when I run the code on the emulator the circle is not drawn where I clicked.
public class MainActivity extends AppCompatActivity {
Canvas canvas;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//------------------
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getRealMetrics(displaymetrics);
int screenWidth = displaymetrics.widthPixels;//480
int screenHeight = displaymetrics.heightPixels;//1920
Bitmap bg = Bitmap.createBitmap(screenWidth, screenHeight, Bitmap.Config.ARGB_8888);
canvas = new Canvas(bg);
RelativeLayout ll = (RelativeLayout) findViewById(R.id.RelativeLayoutCells);
ll.setBackgroundDrawable(new BitmapDrawable(bg));
ll.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
float xf = event.getRawX();
float yf = event.getRawY();
Log.d("=", String.valueOf(x) + " " + String.valueOf(xf));
Paint fillpaint= new Paint();;
fillpaint.setColor(Color.RED);
fillpaint.setStyle(Paint.Style.FILL);
canvas.drawCircle(xf, yf, 5, fillpaint);
canvas.drawCircle(x, y, 15, fillpaint);
}
Button button = (Button) findViewById(R.id.button);
button.setText("ghj");
return false;
}
});
}
}
You should not use event.getRawX(). The returned value is completly raw and not adjusted to your view. If the canvas is not scaled, use event.getX() instead. It makes a difference because of what it returns. getX returns x adjusted to custom views but getRawX is based on the screen which causes inaccuracy.

Canvas On Draw Method

I am new to android programming and I am trying to create a green circle image out of the screen. I tried using canvas to draw but it always show an error:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.graphics.Paint.setColor(int)' on a null object reference
at com.example.jordanong09.handeyegame.GameActivity.onDraw(GameActivity.java:61)
at com.example.jordanong09.handeyegame.GameActivity.onCreate(GameActivity.java:47)
Below are my codes for my programme:
public class GameActivity extends Activity {
TextView textViewTime, textViewScore;
int timeLeft,score;
float xcoord,ycoord,radius = 100;
Paint paint;
Canvas canvas1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
String timeData = getIntent().getExtras().getString("timeDuration");
if(timeData == "30sec"){
timeLeft = 30;
}
textViewTime = (TextView)findViewById(R.id.textViewTime);
textViewScore = (TextView)findViewById(R.id.textViewScore);
textViewTime.setText(timeData);
final CounterClass timer = new CounterClass (30000, 1000);
timer.start();
onDraw(canvas1);
}
protected void onDraw (Canvas canvas)
{
Display display = getWindowManager().getDefaultDisplay();
Point screenSize = new Point();
display.getSize(screenSize);
int width = screenSize.x;
int height = screenSize.y;
Random random = new Random();
xcoord = random.nextFloat() * width;
ycoord = random.nextFloat() * height;
paint.setColor(Color.GREEN);
paint.setStyle(Paint.Style.STROKE);
canvas.drawCircle(xcoord, ycoord, radius, paint);
}
I really dunno what is wrong with it because I have been researching online for solutions. Hope I could hear some advice. Thanks
The Paint object is not initialised correctly. You should call
paint = new Paint();
before calling
paint.setColor();
Otherwise paint is null, and you can't call methods on null.
You should go by creating a custom view and adding it as a child to one of your view group. Here is an example code. Hope this will help.
/**
* Created by sanjeet on 2/2/16.
*/
public class GameActivity extends AppCompatActivity {
TextView textViewTime, textViewScore;
int timeLeft, score;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
textViewTime = (TextView)findViewById(R.id.textViewTime);
textViewScore = (TextView)findViewById(R.id.textViewScore);
/*Create a ViewGroup in your layout to contain this custom GameView instance */
LinearLayout gameViewContainer = (LinearLayout)findViewById(R.id.custom_view_container);
gameViewContainer.addView(new GameView(this));
}
class GameView extends View {
Paint paint;
int width;
int height;
private float radius=100;
Random random;
public GameView(Context context) {
super(context);
paint = new Paint();
paint.setColor(Color.GREEN);
paint.setStyle(Paint.Style.STROKE);
Display display = getWindowManager().getDefaultDisplay();
Point screenSize = new Point();
display.getSize(screenSize);
width = screenSize.x;
height = screenSize.y;
random = new Random();
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
float xcoord = random.nextFloat() * width;
float ycoord = random.nextFloat() * height;
canvas.drawCircle(xcoord, ycoord, radius, paint);
}
}
}

canvas erase bitmap code android

I am using below code to erase bitmap from canvas on touch event.
it's working fine in android 2.3 but in 4.0 it show me black spot instead of erasing bitmap.
anyone can help.
public class DemoTouch extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new TouchView(this));
}
class TouchView extends View {
Bitmap bgr;
Bitmap overlayDefault;
Bitmap overlay;
Paint pTouch;
int X = -100;
int Y = -100;
Canvas c2;
public TouchView(Context context) {
super(context);
bgr = BitmapFactory.decodeResource(getResources(), R.drawable.a1);
overlayDefault = BitmapFactory.decodeResource(getResources(),
R.drawable.a2);
overlay = BitmapFactory.decodeResource(getResources(),
R.drawable.a2).copy(Config.ARGB_4444, true);
c2 = new Canvas(overlay);
pTouch = new Paint(Paint.ANTI_ALIAS_FLAG);
pTouch.setXfermode(new PorterDuffXfermode(Mode.CLEAR));
pTouch.setColor(Color.TRANSPARENT);
pTouch.setMaskFilter(new BlurMaskFilter(15, Blur.NORMAL));
pTouch.setAntiAlias(true);
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN: {
X = (int) ev.getX();
Y = (int) ev.getY();
invalidate();
break;
}
case MotionEvent.ACTION_MOVE: {
X = (int) ev.getX();
Y = (int) ev.getY();
invalidate();
break;
}
case MotionEvent.ACTION_UP:
break;
}
return true;
}
#Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
// draw background
canvas.drawBitmap(bgr, 0, 0, null);
// copy the default overlay into temporary overlay and punch a hole
// in it
// c2.drawBitmap(overlayDefault, 0, 0, null); // exclude this line
// to
// show all as you draw
c2.drawCircle(X, Y, 20, pTouch);
// draw the overlay over the background
canvas.drawBitmap(overlay, 0, 0, null);
}
}
}
Have a look at this method of mine. The view EditImageView is a custom ImageView that I also applied that erase function to. I had the same problem until I applied the code below inside the if statement. That fixes the problem for 3.0 and up
/**
* Sets the image to the view in the content view
* #param view
*/
private void setImageView(EditImageView view) {
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
view.setLayoutParams(params);
// #### THIS IS THE IMPORTANT PART ######
if (Build.VERSION.SDK_INT >= 11) {
view.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
LinearLayout main = (LinearLayout) findViewById(R.id.galleryImage);
main.removeAllViews();
main.addView(view);
}
EDIT
You can probably do something like this in your code.
public TouchView(Context context) {
super(context);
// This should fix it from 3.0 and up
if (Build.VERSION.SDK_INT >= 11) {
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
bgr = BitmapFactory.decodeResource(getResources(), R.drawable.a1);
overlayDefault = BitmapFactory.decodeResource(getResources(),
R.drawable.a2);
overlay = BitmapFactory.decodeResource(getResources(),
R.drawable.a2).copy(Config.ARGB_4444, true);
c2 = new Canvas(overlay);
pTouch = new Paint(Paint.ANTI_ALIAS_FLAG);
pTouch.setXfermode(new PorterDuffXfermode(Mode.CLEAR));
pTouch.setColor(Color.TRANSPARENT);
pTouch.setMaskFilter(new BlurMaskFilter(15, Blur.NORMAL));
pTouch.setAntiAlias(true);
}
Hope this also helps you

Why is the position of the drawable also changing when applying ScaleAnimation in Android?

I am trying to apply a scale animation to a rectangle, using code not xml. I want to make the rectangle grow taller, pretty simple.
RectDrawableView - creates a RectShape ShapeDrawable
public class RectDrawableView extends View {
Paint paint;
public RectDrawableView(Context context) {
super(context);
paint = new Paint();
paint.setColor(Color.parseColor("#aacfcce4"));
paint.setStyle(Paint.Style.FILL);
}
protected void onDraw(Canvas canvas) {
int x = 35;
int y = 250;
int width = 50;
int height = 300;
ShapeDrawable shapeDrawable = new ShapeDrawable(new RectShape());
Rect rect = new Rect(x, y, x+width, y+height);
shapeDrawable.setBounds(rect);
shapeDrawable.getPaint().set(paint);
shapeDrawable.draw(canvas);
}
}
Activity: - Creates a new RectDrawableView and adds to layout. OnResume an animation is triggered, which should make the rectangle grow taller.
public class RectActivity extends Activity {
final String TAG = "RectActivity";
TextView rect1;
RectDrawableView rectView;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.basic);
LinearLayout linear = (LinearLayout) findViewById(R.id.basicLayout);
rectView = new RectDrawableView(this);
linear.addView(rectView);
}
#Override
public void onResume() {
super.onResume();
RunAnimations();
}
private void RunAnimations() {
Animation rectAnim1 = new ScaleAnimation(1, 1, 1, 1.3f, ScaleAnimation.RELATIVE_TO_SELF, 0,
ScaleAnimation.RELATIVE_TO_SELF, 1);
rectAnim1.setFillBefore(false);
rectAnim1.setFillAfter(true);
rectAnim1.setStartOffset(500);
rectAnim1.setDuration(500);
rectView.startAnimation(rectAnim1);
}
}
basic.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/basicLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
</LinearLayout>
Result: The rect is growing taller, good, but the location of the rect is also changing, bad. The whole rectangle is being positioned higher up the screen.
When I use this exact same animation code, but apply it to a TextView instead of a ShapeDrawable, all is good.
I've trawled through all the related articles on SO, but I'm still struggling with this one. Any help would be appreciated, thanks.
Complete code, i had changed the height of the rectangle.
public class RectActivity extends Activity {
final String TAG = "RectActivity";
TextView rect1;
RectDrawableView rectView;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.basic);
LinearLayout linear = (LinearLayout) findViewById(R.id.rectangle);
rectView = new RectDrawableView(this);
linear.addView(rectView);
Button sbutton = (Button)findViewById(R.id.sbutton);
sbutton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
RectActivity.this.RunAnimations();
}
});
Button tbutton = (Button)findViewById(R.id.tbutton);
tbutton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
RectActivity.this.runTranslateAnimation();
}
});
}
#Override
public void onResume() {
super.onResume();
RunAnimations();
}
private void RunAnimations() {
Animation rectAnim1 = new ScaleAnimation(1, 1, 1, 1.3f,
ScaleAnimation.RELATIVE_TO_SELF, 0,
ScaleAnimation.ABSOLUTE, 250);
rectAnim1.setFillBefore(false);
rectAnim1.setFillAfter(true);
rectAnim1.setStartOffset(500);
rectAnim1.setDuration(500);
rectView.startAnimation(rectAnim1);
}
private void runTranslateAnimation() {
float x = rectView.getX();
float y = rectView.getY();
TranslateAnimation trans = new TranslateAnimation(0, 0, 0, (90));
trans.setFillAfter(true);
trans.setStartOffset(500);
trans.setDuration(500);
rectView.startAnimation(trans);
}
}
public class RectDrawableView extends View {
Paint paint;
Rect rect;
public RectDrawableView(Context context) {
super(context);
paint = new Paint();
paint.setColor(Color.parseColor("#aacfcce4"));
paint.setStyle(Paint.Style.FILL);
}
protected void onDraw(Canvas canvas) {
int x = 50;
int y = 150;
int width = 50;
int height = 100;
ShapeDrawable shapeDrawable = new ShapeDrawable(new RectShape());
rect = new Rect(x, y, x+width, y+height);
shapeDrawable.setBounds(rect);
shapeDrawable.getPaint().set(paint);
shapeDrawable.draw(canvas);
}
}
Try this code. Keep the pivotYType as ABSOLUTE with value 550 ( y + height )
Animation rectAnim1 = new ScaleAnimation(1, 1, 1, 1.3f,
ScaleAnimation.RELATIVE_TO_SELF, 0,
ScaleAnimation.ABSOLUTE, 550);

Categories

Resources