Monday, September 23, 2013

Face Detection example in andoid from Gallery and by Camera capure image

Hello Every one ,

I recently learn face detection  in android by searching in google and other blogger i found below code and i have made some change in it .

Hope you will like my code and also shared your information in image processing and your expose in face detection in android.


Below is my android Activity code :



public class FaceDetectActivity extends Activity  implements OnClickListener{

        private static final int TAKE_PICTURE_CODE = 100;
        private static final int MAX_FACES = 5;
        
        private static final int SELECT_PICTURE = 6;
       
        private Bitmap cameraBitmap = null;
        private Button btn_TakePhoto;
       
        private Button btn_select_image;
       
        private Button btn_facedetect;
        
        private ImageView imageView;
       
        private int mWidth;
        private int mHeight;
       
        private ProgressDialog mProgressDialog;
       
        private Button btn_select_img;
       
      
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_face_detect);
       
        initDisplay();
       
        btn_TakePhoto=(Button)findViewById(R.id.take_picture);
        btn_TakePhoto.setOnClickListener(this);
        btn_select_img=(Button)findViewById(R.id.btn_select_gallary);
        btn_select_img.setOnClickListener(this);
       
       
       
    }


   
   
    private void initDisplay(){
       
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);

        mHeight=metrics.heightPixels;
        mWidth=metrics.widthPixels;
       
        Log.v("LOG_TAG", "Wdith is "+ mWidth +"Height is "+ mHeight);
    }
   
   
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.face_detect, menu);
        return true;
    }

   
   
    private void openCamera(){
        Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        
        startActivityForResult(intent, TAKE_PICTURE_CODE);
    }
    
    private void processCameraImage(Intent intent){
        setContentView(R.layout.face_detect_layout);
        
        btn_facedetect=(Button)findViewById(R.id.detect_face);
        btn_facedetect.setOnClickListener(this);
        
       
       
        btn_select_image=(Button)findViewById(R.id.btn_pickimag);
       
        btn_select_image.setOnClickListener(this);
       
       
        imageView= (ImageView)findViewById(R.id.image_view);
        
        cameraBitmap = (Bitmap)intent.getExtras().get("data");
        
        imageView.setImageBitmap(cameraBitmap);
    }

    @Override
    public void onClick(View v) {
       
        switch(v.getId()){
       
        case R.id.take_picture:
           
            openCamera();
            break;
           
        case R.id.detect_face:
           
            //detectFaces();
           
            new FaceDetectAsyncTask().execute(cameraBitmap);
           
            break;
           
        case R.id.btn_pickimag:
           
            startImagePicker();
           
            break;
       
           
        case R.id.btn_select_gallary:
           
            startImagePicker();
           
            break;
       
        }
       
    }
   
   
   
    private Object[] detectFaces(Bitmap mBitmap){
      
        Object[] mObject = new Object[2];
       
        if(null != mBitmap){
               
               int width = mBitmap.getWidth();
                int height = mBitmap.getHeight();
                
                FaceDetector detector = new FaceDetector(width, height,FaceDetectActivity.MAX_FACES);
                Face[] faces = new Face[FaceDetectActivity.MAX_FACES];
                
                Bitmap bitmap565 = Bitmap.createBitmap(width, height, Config.RGB_565);
                Paint ditherPaint = new Paint();
                Paint drawPaint = new Paint();
                
                ditherPaint.setDither(true);
                drawPaint.setColor(Color.GREEN);
                drawPaint.setStyle(Paint.Style.STROKE);
                drawPaint.setStrokeWidth(2);
                
                Canvas canvas = new Canvas();
                canvas.setBitmap(bitmap565);
                canvas.drawBitmap(mBitmap, 0, 0, ditherPaint);
                
                int facesFound = detector.findFaces(bitmap565, faces);
                PointF midPoint = new PointF();
                float eyeDistance = 0.0f;
                float confidence = 0.0f;
                
                Log.i("FaceDetector", "Number of faces found: " + facesFound);
                
                if(facesFound > 0)
                {
                        for(int index=0; index<facesFound; ++index){
                                faces[index].getMidPoint(midPoint);
                                eyeDistance = faces[index].eyesDistance();
                                confidence = faces[index].confidence();
                                
                                Log.i("FaceDetector",
                                                "Confidence: " + confidence +
                                                ", Eye distance: " + eyeDistance +
                                                ", Mid Point: (" + midPoint.x + ", " + midPoint.y + ")");
                                
                                canvas.drawRect((int)midPoint.x - eyeDistance ,
                                                                (int)midPoint.y - eyeDistance ,
                                                                (int)midPoint.x + eyeDistance,
                                                                (int)midPoint.y + eyeDistance, drawPaint);
                        }
                }else{
                    //Toast.makeText(this, "No Face Detect", Toast.LENGTH_SHORT).show();
                }
                
                /*String filepath = Environment.getExternalStorageDirectory() + "/facedetect" + System.currentTimeMillis() + ".jpg";
                
                        try {
                                FileOutputStream fos = new FileOutputStream(filepath);
                                
                                bitmap565.compress(CompressFormat.JPEG, 90, fos);
                                
                                fos.flush();
                                fos.close();
                        } catch (FileNotFoundException e) {
                                e.printStackTrace();
                        } catch (IOException e) {
                                e.printStackTrace();
                        }*/
                        
                       /* ImageView imageView = (ImageView)findViewById(R.id.image_view);
                        
                        imageView.setImageBitmap(bitmap565);*/
               
                mObject[0]=facesFound;
                mObject[1]=bitmap565;
               
                        return mObject;
        }
       
        return mObject;
    }
   
   
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
    
            if(TAKE_PICTURE_CODE == requestCode){
                   
                if(Activity.RESULT_OK==resultCode){
                    processCameraImage(data);
                }else{
                    Toast.makeText(this, "You have not capture Image", Toast.LENGTH_SHORT).show();
                   
                     setContentView(R.layout.face_detect_layout);
                    
                        btn_facedetect=(Button)findViewById(R.id.detect_face);
                        btn_facedetect.setOnClickListener(this);
                        
                       
                       
                        btn_select_image=(Button)findViewById(R.id.btn_pickimag);
                       
                        btn_select_image.setOnClickListener(this);
                       
                       
                        imageView= (ImageView)findViewById(R.id.image_view);
                }
               
            }else if(SELECT_PICTURE==requestCode){
               
               
                if(Activity.RESULT_OK==resultCode){
                   
                    Uri selectedImageUri = data.getData();
                    String selectedImagePath = getPath(selectedImageUri);
                   
                   
                    setContentView(R.layout.face_detect_layout);
                   
                    btn_facedetect=(Button)findViewById(R.id.detect_face);
                    btn_facedetect.setOnClickListener(this);
                    
                   
                   
                    btn_select_image=(Button)findViewById(R.id.btn_pickimag);
                   
                    btn_select_image.setOnClickListener(this);
                   
                   
                    imageView= (ImageView)findViewById(R.id.image_view);
                   
                    updateImageFromGallary(selectedImagePath);
                   
                   
                   
                   
                   
                }else{
                   
                }
               
            }
           
           
    }
   
   
    private void updateImageFromGallary(String imgPath){
       
        try{
           
            cameraBitmap=null;
           
            //cameraBitmap=BitmapFactory.decodeFile(imgPath);
           
            cameraBitmap=decodeSampledBitmapFromResource(getResources(),imgPath,mWidth,mHeight);
           
            imageView.setImageBitmap(cameraBitmap);
           
            Toast.makeText(this, "Press Face detect for Face Detection", Toast.LENGTH_SHORT).show();
           
        }catch(OutOfMemoryError outMemeoryError){
           
            Toast.makeText(this, "Unable to Load Image", Toast.LENGTH_SHORT).show();
           
        }
       
       
       
       
    }
   
   
    private void startImagePicker(){
       
        // in onCreate or any event where your want the user to
        // select a file
        /*Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);*/
        Intent intent = new Intent(Intent.ACTION_PICK,
                   android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
       
        startActivityForResult(Intent.createChooser(intent,
                "Select Picture"), SELECT_PICTURE);
       
    }
   
   
    public String getPath(Uri uri) {
       
       
       
         Uri selectedImage = uri;
         String[] filePathColumn = {MediaStore.Images.Media.DATA};

         Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
        
         cursor.moveToFirst();

         int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
         String filePath = cursor.getString(columnIndex);
       
         return filePath;
       
       /* String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);*/
    }
   
   
    public static int calculateInSampleSize(
            BitmapFactory.Options options, int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {

        // Calculate ratios of height and width to requested height and width
        final int heightRatio = Math.round((float) height / (float) reqHeight);
        final int widthRatio = Math.round((float) width / (float) reqWidth);

        // Choose the smallest ratio as inSampleSize value, this will guarantee
        // a final image with both dimensions larger than or equal to the
        // requested height and width.
        inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
    }

    return inSampleSize;
}
   
   
    public static Bitmap decodeSampledBitmapFromResource(Resources res, String path,
            int reqWidth, int reqHeight) {

        // First decode with inJustDecodeBounds=true to check dimensions
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
       // BitmapFactory.decodeResource(res, resId, options);
       // BitmapFactory.decodeFile(path);
       
        BitmapFactory.decodeFile(path, options);
        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
       //return BitmapFactory.decodeResource(res, resId, options);
       
        return  BitmapFactory.decodeFile(path, options);
    }
   
   
   
    public class FaceDetectAsyncTask extends AsyncTask<Bitmap, Void, Object[]>{

       
       
        @Override
        protected void onPostExecute(Object[] result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
           
           
           
            dismissProgressDialog();
           
            if(result!=null){
               
                if(result[0]!=null){
                   
                    int faceDetect=(Integer) result[0];
                    if(faceDetect>0){
                       
                        ImageView imageView = (ImageView)findViewById(R.id.image_view);
                        
                        imageView.setImageBitmap((Bitmap) result[1]);
                    }else{
                        Toast.makeText(FaceDetectActivity.this, "No Face Detect", Toast.LENGTH_SHORT).show();
                    }
                }else{
                    Toast.makeText(FaceDetectActivity.this, "No Face Detect", Toast.LENGTH_SHORT).show();
                }
               
               
            }
           
           
           
           
           
        }

        /*@Override
        protected void onPostExecute(Bitmap result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
           
             dismissProgressDialog();
           
             ImageView imageView = (ImageView)findViewById(R.id.image_view);
            
             imageView.setImageBitmap(result);
            
           
        }
*/
        @Override
        protected void onPreExecute() {
           
            super.onPreExecute();
           
            showProgressDialog();
        }

        @Override
        protected Object[] doInBackground(Bitmap... params) {
            // TODO Auto-generated method stub
           
            Bitmap mBitmap=params[0];
            Object [] mObjArray;
           
            mObjArray=detectFaces(mBitmap);
           
            return mObjArray;
        }

       
    }
   
   
    private void showProgressDialog(){
       
        if(mProgressDialog!=null && mProgressDialog.isShowing()){
            return ;
        }else{
            mProgressDialog=new ProgressDialog(this);
           
            mProgressDialog.setTitle("Please wait...");
           
            mProgressDialog.setMessage("Detecting face from image");
           
            mProgressDialog.setCancelable(false);
           
            mProgressDialog.show();
        }
    }
   
    private void dismissProgressDialog(){
   
        if(mProgressDialog!=null && mProgressDialog.isShowing()){
            mProgressDialog.dismiss();
            mProgressDialog=null;
        }
    }
   
   
}


Here are my layout files  code:

activity_face_detection.xml


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".FaceDetectActivity"
    android:gravity="center"
     >

     <!-- <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/app_info"
        android:gravity="center_horizontal"
        android:layout_weight="1.0"
        android:id="@+id/txt_appinfo"
        /> -->
        
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/take_picture"
        android:layout_margin="5dip"
        android:text="@string/take_picture"
        android:layout_gravity="center_horizontal"
        android:layout_centerHorizontal="true"
       
       
        />
   
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/btn_select_gallary"
        android:layout_margin="5dip"
        android:text="@string/select_image_from_gallary"
        android:layout_gravity="center_horizontal"
        android:layout_centerHorizontal="true"
        android:layout_below="@+id/take_picture"
        />

</RelativeLayout>

face_detect_layout.xml



<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/image_view"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1.0"
         />
   
   
   
   
    <LinearLayout
       
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
         >
       
         <Button
        android:id="@+id/detect_face"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
       
        android:text="@string/detect_face"
        android:layout_gravity="center_vertical"
         />
        
          <Button
        android:id="@+id/btn_pickimag"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
       android:layout_gravity="center_vertical"
        android:text="@string/select_image_from_gallary" />
       
    </LinearLayout>
</LinearLayout>

Creating a Clock Widget in Android with Custom Font.

Hi all
if you have been a regular visitor of this website you have seen that I have shown you how to create a simple widget, adding controls to it, adding event handlers in the views etc…
Do check this website for more tutorials on widgets.
You can find other tutorials by following this LINK.
This tutorial is also an important one on widgets.
People always find it difficult to customize their widgets with Custom Fonts. AS of now you cannot directly set the font in a TextView in a Widget. For that you have to go indirectly.
In this example I will show you how to create a Clock widget with Custom Font.

Android JellyBean new features


  • WI-Fi Direct


  • 1080p video recording for stock Android devices
  • Improved error correction on the keyboard
  • You can directly access the apps from the lock screen
  • Upgraded copy and paste functionality
  • Support for the WebP image format
  • Hardware acceleration of the universal Interface
  • Soft buttons from Android 3.x are now available for use on phones
  • Widgets in a new tab can be separated, listed in a similar manner to apps
  • Folders can easily be created with a drag-and-drop style
  • Launcher Customizer
  • Enhanced visual voicemail with the ability to speed up or slow down voicemail messages
  • Pinch-to-zoom functionality in the calendar
  • Integrated screenshot capture (accomplished by holding down the Power and Volume-Down buttons)
  • Improved voice integration and continuous, real-time speech to text dictation
  • Face Unlock, a feature that allows users to unlock handsets using facial recognition software
  • New tabbed web browser under Google’s Chrome brand, allowing up to 16 tabs
  • Automatic syncing of browser with users’ Chrome bookmarks
  • A new typeface family for the UI, Roboto
  • A data Usage section in settings that lets users set warnings when they approach a certain usage limit, and disable data use when the limit is exceeded
  • Shut down apps ability that are using data in the background
  • An improved camera app with zero shutter lag, time lapse settings, panorama mode, and the ability to zoom while recording
  • Built-in photo editor
  • You can organize New gallery layout by location and person
  • Refreshed “People” app with social network integration, status updates and hi-res images
  • A near-field communication feature (Android Beam) allowing the rapid short-range exchange of web bookmarks, contact info, directions, YouTube videos and other data
  • Android VPN Framework (AVF), and TUN (but not TAP) kernel module.
  • Samsung Galaxy Note 3 in India for Rs.49990

    Here are Galaxy note 3 specs.






    General
    2G NetworkGSM 850 / 900 / 1800 / 1900
    3G NetworkHSDPA 850 / 900 / 1900 / 2100
    4G NetworkLTE
    SIMMicro-SIM
    Announced2013, September
    StatusComing soon. Exp. release 2013, September
    Body
    Dimensions151.2 x 79.2 x 8.3 mm (5.95 x 3.12 x 0.33 in)
    Weight168 g (5.93 oz)

    - S Pen stylus
    Display
    TypeSuper AMOLED capacitive touchscreen, 16M colors
    Size1080 x 1920 pixels, 5.7 inches (~386 ppi pixel density)
    MultitouchYes
    Sound
    Alert typesVibration; MP3, WAV ringtones
    LoudspeakerYes
    3.5mm jackYes
    Memory
    Card slotmicroSD, up to 64 GB
    Internal32/64 GB storage, 3 GB RAM
    Data
    GPRSYes
    EDGEYes
    SpeedHSDPA, 42 Mbps; HSUPA; LTE, Cat4, 50 Mbps UL, 150 Mbps DL
    WLANWi-Fi 802.11 a/b/g/n/ac, dual-band, DLNA, Wi-Fi Direct, Wi-Fi hotspot
    BluetoothYes, v4.0 with A2DP, LE, EDR
    NFCYes
    Infrared portYes
    USBYes, microUSB v3.0 (MHL 2), USB Host
    Camera
    Primary13 MP, 4128 x 3096 pixels, autofocus, LED flash
    FeaturesDual Shot, Simultaneous HD video and image recording, geo-tagging, touch focus, face and smile detection, image stabilization, panorama, HDR
    VideoYes, 2160p@30fps, 1080p@60fps (N9005)/ 1080p (N9000)
    SecondaryYes, 2 MP, 1080p@30fps
    Features
    OSAndroid OS, v4.3 (Jelly Bean)
    ChipsetQualcomm Snapdragon 800 (N9005)/ Exynos 5 Octa 5420 (N9000)
    CPUQuad-core 2.3 GHz Krait 400 (N9005)/ Quad-core 1.9 GHz Cortex-A15 & quad-core 1.3 GHz Cortex-A7 (N9000)
    GPUAdreno 330 (N9005)/ Mali-T628 MP6 (N9000)
    SensorsAccelerometer, gyro, proximity, compass, barometer, temperature, humidity, gesture
    MessagingSMS(threaded view), MMS, Email, Push Mail, IM, RSS
    BrowserHTML5
    RadioNo
    GPSYes, with A-GPS support and GLONASS
    JavaYes, via Java MIDP emulator
    ColorsBlack, White, Pink

    - ANT+ support 
    – S-Voice natural language commands and dictation 
    – Air gestures 
    – SNS integration 
    – Active noise cancellation with dedicated mic 
    – Dropbox (50 GB storage) 
    – TV-out (via MHL A/V link) 
    – MP4/DivX/XviD/WMV/H.264/H.263 player 
    – MP3/WAV/eAAC+/AC3/FLAC player 
    – Organizer 
    – Image/video editor 
    – Document editor (Word, Excel, PowerPoint, PDF) 
    – Google Search, Maps, Gmail, 
    YouTube, Calendar, Google Talk, Picasa 
    – Voice memo/dial/commands 
    – Predictive text input (Swype)
    Battery

    Li-Ion 3200 mAh battery