阅读 2260

用App制作一款猫脸识别器

一起用代码吸猫!本文正在参与【喵星人征文活动】

前言

掘金大大又出了新活动,舒服!我喜欢!话不多说,直接开始整活!

先来看看效果: BilBil视频:

准备工作:

  1. 百度动物识别API
  2. Android开发环境

1、配置百度API环境

  1. 进入百度SDK首页,注册并登录对应账号,然后进行认证(公司、个人)

    QQ截图20211112155723.png

  2. 如图所示,选择对应的API文档,并点击立即使用!

  3. 在对应的应用管理里面创建属于自己的项目,并且开通动物识别API!(免费的即可,体验次数够用)

    QQ截图20211112160059.png

  4. 如图所示,进入对应的应用详情,拿到对应的AppId以及AppKey!

2、开始整活

  1. 打开AS,创建一个全新的空项目。

  2. 打开主Module对应的buld.gradle添加如下代码

    
    android {
        ...略
        defaultConfig {
         ...略
         	//写入对应的默认配置
            buildConfigField 'String','GET_OAUTH_TOKEN_URL','"https://aip.baidubce.com/oauth/2.0/token?"'
            buildConfigField 'String','AK','"2p8d23GtrBHyaQixgqyPtAIM"'
            buildConfigField 'String','SECRET','"0SWfrU65xRu6Gxq7nuTHoskRAKLd5rht "'
            buildConfigField 'String','GET_ANIMAL_URL','"https://aip.baidubce.com/rest/2.0/image-classify/v1/animal"'
        }
    ...略
    
    
    dependencies{
        implementation 'androidx.appcompat:appcompat:1.3.1'
        implementation 'com.google.android.material:material:1.4.0'
        implementation 'androidx.constraintlayout:constraintlayout:2.1.1'
        implementation project(path: ':easyPhotos')
        testImplementation 'junit:junit:4.+'
        androidTestImplementation 'androidx.test.ext:junit:1.1.3'
        androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
        implementation 'com.github.bumptech.glide:glide:4.12.0'
        implementation 'com.google.code.gson:gson:2.2.4'
        // 权限请求框架:https://github.com/getActivity/XXPermissions
        implementation 'com.github.getActivity:XXPermissions:12.8'
        implementation 'org.projectlombok:lombok:1.18.8'
        annotationProcessor 'org.projectlombok:lombok:1.18.8'
    }
    
    }
    复制代码
  3. 对应的AndroidManifest添加相应的配置:

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    
    <application
    	...略
    	
    	 <meta-data
                android:name="ScopedStorage"
                android:value="true" />
     </application>
    复制代码
  4. 权限申请

      public void getWriteAndCameraPermission() {
            XXPermissions.with(this)
                    // 申请单个权限
                    .permission(Permission.CAMERA)
                    // 申请多个权限
                    .permission(Permission.Group.STORAGE)
                    .request(new OnPermissionCallback() {
    
                        @Override
                        public void onGranted(List<String> permissions, boolean all) {
                            if (all) {
    //                            toast("获取权限成功");
                                doPermissionSuccess();
                            } else {
                                getWriteAndCameraPermission();
                            }
                        }
                        @Override
                        public void onDenied(List<String> permissions, boolean never) {
                            if (never) {
                                toast("被永久拒绝授权,请手动授予权限");
                                // 如果是被永久拒绝就跳转到应用权限系统设置页面
                                XXPermissions.startPermissionActivity(BaseActivity.this, permissions);
                            } else {
                                toast("获取权限失败");
                            }
                        }
                    });
        }
    复制代码
  5. 权限成功回调

        @Override
        protected void doPermissionSuccess() {
        	//权限申请成功回调后,打开手机照相机
            EasyPhotos.createCamera(this).start(new SelectCallback() {
                @Override
                public void onResult(ArrayList<Photo> photos, ArrayList<String> paths, boolean isOriginal) {
                	//照相机回调结果
                    logCat("doPhotoLast onResult : ");
                    if (paths == null || paths.size() == 0)
                        return;
                    //开始处理图片,进行猫脸识别。
                    doPhotoLast(paths.get(0));
                }
            });
        }
    复制代码
  6. 获取百度API对应的Token:

    1.png

  7. 调用百度API对应的动物识别

    2.png

  8. 调用成功后的回调处理

        @Override
        public boolean handleMessage(@NonNull  Message message) {
            logCat("handleMessage  message.what "+message.what);
            switch (message.what) {
                case 1001:
                    /*
                    * {
                        "refresh_token": "25.6a79e94b2cc92571e57c12f16b3d062d.315360000.1951874992.282335-25104979",
                        "expires_in": 2592000,
                        "session_key": "9mzdA5/DKxagseJ/y/Gmyi+PuJzy8+QyeISLV0LFDFpMMe67P4NW6v+6lTIjnLlNpWcoZbzSXZqGqflBX913xRNT9mmTug==",
                        "access_token": "24.8511933b8b244e2d0863ebb0d43ca5e2.2592000.1639106992.282335-25104979",
                        "scope": "public vis-classify_dishes vis-classify_car brain_all_scope vis-classify_animal vis-classify_plant brain_object_detect brain_realtime_logo brain_dish_detect brain_car_detect brain_animal_classify brain_plant_classify brain_ingredient brain_advanced_general_classify brain_custom_dish brain_poi_recognize brain_vehicle_detect brain_redwine brain_currency brain_vehicle_damage brain_multi_ object_detect wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test权限 vis-classify_flower lpq_开放 cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_开放Scope vis-ocr_虚拟人物助理 idl-video_虚拟人物助理 smartapp_component smartapp_search_plugin avatar_video_test b2b_tp_openapi b2b_tp_openapi_online",
                        "session_secret": "94ec45de181d151310d55efb96aa02b3"
                      }
                    * */
                    accessToken = (String) message.obj;
                    toast("初始化完成!");
                    break;
                case 1002:
                    String result = (String) message.obj;
                    //{"result":[{"name":"孟买猫","score":"0.870167"},{"name":"德文帝王猫","score":"0.0221098"},{"name":"玄猫","score":"0.0211879"},{"name":"哈瓦那棕猫","score":"0.0176104"},{"name":"科拉特猫","score":"0.00979233"},{"name":"俄罗斯蓝猫","score":"0.00612372"}],"log_id":1458311455921558025}
                    logCat("result: "+result);
                    parseCatInfo(result);
                    break;
            }
            return super.handleMessage(message);
        }
    复制代码
  9. 显示小喵咪结果

        private void parseCatInfo(String result) {
            CatInfo catInfo = gson.fromJson(result, CatInfo.class);
            List<CatInfo.ResultBean> listCat = catInfo.getResult();
            if (listCat.size() == 0) {
                toast("猫脸识别失败!");
                return;
            }
            textCatName.setText(listCat.get(0).getName());
        }
    复制代码

3、Demo下载:点我下载

结束语

好了,本篇文章到这里就差不多结束了。内容很简单,就是调用百度API的动物识别API接口就行了,然后根据高分将对应名称显示出来即可!

文章分类
Android
文章标签