i want to detect face from image in android - 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

Related

Screen turning black after face detection using ML kit

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);
}
});
}

Drawing a circle on ImageView2 in same coordinates as ImageView1 if i tap a place in ImageView1 and Vice versa

I'm trying to make find the difference game app, but I never made anything like that and since I'm a new to development I'm stuck
well baby Steps are always needed to learn xD
I read in some documentation that i have to get each ImageView height and width separately so when i touch imageView1 its coordinates can be set to ImageVIew2 and ViceVersa I MAYBE BE WRONG XD
Right now I have a layout with 2 Images set vertically
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".PlayActivity"
android:id="#+id/hello1">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/hello">
<ImageView
android:id="#+id/image1"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#drawable/pic_9" />
<ImageView
android:id="#+id/image2"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#drawable/pic_9a" />
</LinearLayout>
What i want to do is if i tap a place in image1 a circle should be created on the same place in image2
after reading along a few things i have made a circle if i tap the layout but i am stuck after this i cant find what to do next maybe i cant find documentation related to my problems
public class PlayActivity extends AppCompatActivity {
RelativeLayout layout;
float x = 0;
float y = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play);
layout=(RelativeLayout) findViewById(R.id.hello1);
layout.addView(new CustomView(PlayActivity.this));
}
public class CustomView extends View {
Bitmap mBitmap;
Paint paint;
public CustomView(Context context) {
super(context);
mBitmap = Bitmap.createBitmap(400, 800, Bitmap.Config.ARGB_8888);
paint = new Paint();
paint.setColor(Color.RED);
paint.setStyle(Paint.Style.FILL);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawCircle(x, y, 50, paint);
}
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
x = event.getX();
y = event.getY();
invalidate();
}
return false;
}
}}
Right now i think my two ImageView arent separate because when i touch between the 2 images a circle is created which shouldn't since imageView1 ends im not sure if im thinking in right direction its just my guess on how should it work for the game to work I MAYBE BE WRONG XD
I still have a long way to go, but I'm stuck here
can anyone help?
I replaced my PlayActivity code using Tejas Pandya
RelativeLayout layout;
float x = 0;
float y = 0;
ImageView ImageView1, ImageView2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play);
layout=(RelativeLayout) findViewById(R.id.hello1);
layout.addView(new CustomView(PlayActivity.this));
ImageView1 = (ImageView) findViewById(R.id.image1);
ImageView2 = (ImageView) findViewById(R.id.image2);
}
public class CustomView extends View {
public CustomView(Context context) {
super(context);
}
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
x = event.getX();
y = event.getY();
invalidate();
drawCircle(R.id.image2,ImageView2,x,y);
}
return false;
}
public void drawCircle(int my_image_id, ImageView my_imageview, float x , float y){
BitmapFactory.Options myOptions = new BitmapFactory.Options();
myOptions.inDither = true;
myOptions.inScaled = false;
myOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;// important
myOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), my_image_id,myOptions);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(Color.BLUE);
Bitmap workingBitmap = Bitmap.createBitmap(bitmap);
Bitmap mutableBitmap = workingBitmap.copy(Bitmap.Config.ARGB_8888, true);
Canvas canvas = new Canvas(mutableBitmap);
canvas.drawCircle(x, y, 25, paint);
my_imageview.setAdjustViewBounds(true);
my_imageview.setImageBitmap(mutableBitmap);
}
}
and i get this error
E/MessageQueue-JNI: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference
at android.graphics.Bitmap.createBitmap(Bitmap.java:742)
at com.example.pc.blazedifferencegame.PlayActivity$CustomView.drawCircle(PlayActivity.java:68)
at com.example.pc.blazedifferencegame.PlayActivity$CustomView.onTouchEvent(PlayActivity.java:49)
When You tape on Image . You are getting x,y coordinate in
x = event.getX();
y = event.getY();
Now you have x,y coordinate . call your drawCircle() method on both of your imageview with this same x,y coordinate.
For Drawing circle :
make one function drawCircle();
public void drawCircle(int my_image_id,Imageview my_imageview,int x ,int y){
BitmapFactory.Options myOptions = new BitmapFactory.Options();
myOptions.inDither = true;
myOptions.inScaled = false;
myOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;// important
myOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), my_image_id,myOptions);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(Color.BLUE);
//please check here . you've got your bitmap or it is null.
// if it is null,there might be some problem with decoding your resources above.
Bitmap workingBitmap = Bitmap.createBitmap(bitmap);
Bitmap mutableBitmap = workingBitmap.copy(Bitmap.Config.ARGB_8888, true);
Canvas canvas = new Canvas(mutableBitmap);
canvas.drawCircle(x, y, 25, paint);
my_imageview.setAdjustViewBounds(true);
my_imageview.setImageBitmap(mutableBitmap);
}
now for
image 1 . use drawCircle(R.id.imageview1,imageview,x,y) and for
image 2 . use drawCircle(R.id.imageview2,imageview2,x,y)

android : Why I couldn't rotate antiClockwise?

In my App I should rotate a picture like hand of clock clockwise and anticlockwise around bottom center.
I use this code :
private ImageView myImageView;
private float curScale = 1F;
private float curRotate = 70;
private Bitmap bitmap;
private int bmpHeight;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myImageView = (ImageView) findViewById(R.id.imageview);
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.teste);//here you insert your image
bmpHeight = bitmap.getHeight();
drawMatrix();
}
private void drawMatrix() {
Matrix matrix = new Matrix();
Matrix matrixb = new Matrix();
Matrix matrixc = new Matrix();
matrix.postScale(curScale, curScale);
matrixb.setRotate(curRotate, 100, bmpHeight);
matrixc.setTranslate(100, 0);
matrix.setConcat(matrixb, matrixc);
Bitmap targetBitmap = Bitmap.createBitmap(200, bmpHeight,
bitmap.getConfig());
Canvas canvas = new Canvas(targetBitmap);
canvas.drawBitmap(bitmap, matrix, new Paint());
myImageView.setImageBitmap(targetBitmap);
}
But I couldn't rotate it anticlockwise because the width of picture change.
is there any solution?
Thanks in Advance.

Android : Converting imageview to bitmap, to grayscale, bitmap to imageview

I don't don't get any warning on eclipse when I compile this code, but when I run it on device or emulator, that program was forced to close.
public class MainActivity extends Activity {
ImageView img;
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//convert imageview to bitmap
img =(ImageView) findViewById(R.id.imageView1);
BitmapDrawable drawable = (BitmapDrawable) img.getDrawable();
final Bitmap imgbitmap = drawable.getBitmap();
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//convert bitmap to grayscale
Bitmap imgnew;
imgnew = toGrayscale(imgbitmap);
//convert bitmap to imageview
ImageView imgbit;
imgbit = (ImageView) findViewById(R.id.imageView2);
imgbit.setImageBitmap(imgnew);
}
});
}
public Bitmap toGrayscale(Bitmap bmpOriginal){
int width, height;
height = bmpOriginal.getHeight();
width = bmpOriginal.getWidth();
Bitmap bmpGrayscale = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
Canvas c = new Canvas(bmpGrayscale);
Paint paint = new Paint();
ColorMatrix cm = new ColorMatrix();
cm.setSaturation(0);
ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
paint.setColorFilter(f);
c.drawBitmap(bmpOriginal, 0, 0, paint);
return bmpGrayscale;
}
}
If above is your full code then, basic problem is there, you haven't define btn. You need to define it before using it, else when you ar egoing to click on the button it will not work. and this might closing your application.
btn=(Button) findViewById(R.id.button1);

How to rotate the image without changing its size?

I am developing an android app where I have to rotate a circular image around another circular image, but when I am running this the size of my circular image gets automatically changing continuously. So please help me how to solve this. Here is my code
public class JobSearch extends Activity implements OnTouchListener {
private ImageView dialer;
private float y=0;
public boolean onTouch(View v, MotionEvent event) {
double r=Math.atan2(event.getX()-dialer.getWidth()/2, dialer.getHeight()/2-event.getY());
int rotation=(int)Math.toDegrees(r);
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
break;
case MotionEvent.ACTION_MOVE:
//x=event.getX();
y=event.getY();
updateRotation(rotation);
break;
case MotionEvent.ACTION_UP:
break;
}//switch
return true;
}//onTouch
private void updateRotation(double rot){
float newRot=new Float(rot);
Bitmap bitmap=BitmapFactory.decodeResource(getResources(),R.drawable.round_button_big);
Matrix matrix=new Matrix();
matrix.postRotate(newRot);//,bitmap.getWidth()/2,bitmap.getHeight()/2);
Bitmap reDrawnBitmap=Bitmap.createBitmap(bitmap,0,0,bitmap.getWidth(),bitmap.getHeight(),matrix,true);
dialer.setImageBitmap(reDrawnBitmap);
if(newRot>=-5 && newRot<=5)
Toast.makeText(this,"12 O\'Clock",Toast.LENGTH_SHORT).show();
if(newRot>=85 && newRot<=95)
Toast.makeText(this,"3 O\'Clock",Toast.LENGTH_SHORT).show();
if(newRot>=175 || newRot<=-175)
Toast.makeText(this,"6 O\'Clock",Toast.LENGTH_SHORT).show();
if(newRot>=-95 && newRot<=-85)
Toast.makeText(this,"9 O\'Clock",Toast.LENGTH_SHORT).show();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
dialer = (ImageView) findViewById(R.id.big_button);
dialer.setOnTouchListener(this);
}//onCreate
}
This this one; worked for me perfectly.
private Bitmap rotateBitmap(Bitmap bitmap, int rotationAngleDegree){
int w = bitmap.getWidth();
int h = bitmap.getHeight();
int newW=w, newH=h;
if (rotationAngleDegree==90 || rotationAngleDegree==270){
newW = h;
newH = w;
}
Bitmap rotatedBitmap = Bitmap.createBitmap(newW,newH, bitmap.getConfig());
Canvas canvas = new Canvas(rotatedBitmap);
Rect rect = new Rect(0,0,newW, newH);
Matrix matrix = new Matrix();
float px = rect.exactCenterX();
float py = rect.exactCenterY();
matrix.postTranslate(-bitmap.getWidth()/2, -bitmap.getHeight()/2);
matrix.postRotate(rotationAngleDegree);
matrix.postTranslate(px, py);
canvas.drawBitmap(bitmap, matrix, new Paint( Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG | Paint.FILTER_BITMAP_FLAG ));
matrix.reset();
return rotatedBitmap;
}
Try this code for Rotating Image -
public class bitmaptest extends Activity {
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
LinearLayout linLayout = new LinearLayout(this);
// load the origial BitMap (500 x 500 px)
Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),
R.drawable.android);
int width = bitmapOrg.width();
int height = bitmapOrg.height();
int newWidth = 200;
int newHeight = 200;
// calculate the scale - in this case = 0.4f
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// createa matrix for the manipulation
Matrix matrix = new Matrix();
// resize the bit map
matrix.postScale(scaleWidth, scaleHeight);
// rotate the Bitmap
matrix.postRotate(45);
// recreate the new Bitmap
Bitmap resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0,
width, height, matrix, true);
// make a Drawable from Bitmap to allow to set the BitMap
// to the ImageView, ImageButton or what ever
BitmapDrawable bmd = new BitmapDrawable(resizedBitmap);
ImageView imageView = new ImageView(this);
// set the Drawable on the ImageView
imageView.setImageDrawable(bmd);
// center the Image
imageView.setScaleType(ScaleType.CENTER);
// add ImageView to the Layout
linLayout.addView(imageView,
new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT
)
);
// set LinearLayout as ContentView
setContentView(linLayout);
}
}
And, also see this Tutorial
This is my code to rotate image around itself and slowly reduce the speed
rotateAnimation1 = new RotateAnimation(0, 360,
Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF, 0.5f);
rotateAnimation1.setInterpolator(new LinearInterpolator());
rotateAnimation1.setDuration(duration);
rotateAnimation1.setRepeatCount(0);
imgBottle.startAnimation(rotateAnimation1);
flagSpinAvailable = false;
rotateAnimation1.setAnimationListener(new AnimationListener() {
public void onAnimationStart(Animation anim) {
};
public void onAnimationRepeat(Animation anim) {
};
public void onAnimationEnd(Animation anim) {
duration = duration + 70;
startMoving();
};
});
this is the code of rotate the image
Bitmap bMap = BitmapFactory.decodeResource(getResources(),R.drawable.test);
Matrix mat = new Matrix();
mat.postRotate(90);
Bitmap bMapRotate = Bitmap.createBitmap(bMap, 0, 0,
bMap.getWidth(), bMap.getHeight(), mat, true);
BitmapDrawable bmd = new BitmapDrawable(bMapRotate);
image.setImageBitmap(bMapRotate);
image.setImageDrawable(bmd);

Categories

Resources