Reasonable use of Baidu open platform (1)---animal identification

Animal identification

本文介绍如何接入百度图像识别
Example for animal identification

Create project

First create a Vue project, or H5 ordinary project can be

Baidu AI open platform application application

Baidu AI Open Platform

Insert picture description hereEnter the console

No registration requires registration certification

Insert picture description here
Insert picture description here

Remember to read the manual.
Manual entrance: entrance

Insert picture description here

Get Access Token

You can enter
https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id= API KEY &client_secret= Secret Key
Insert picture description herein the browser. The Firefox browser I use
Insert picture description here

Get Access Token here

Sending a POST request can
have the following effect
Insert picture description here

send request

Use POSTMAN or other debugging software to send POST request, you can also use the page to request directly.
In VUE we use AXIOS

此处不封装axios

import axios from "axios";

It is convenient to explain and directly introduce and use, and the actual use needs to be encapsulated
.
Insert picture description here

<div>
    <input
      type="file"
      accept="image/*"
      @change="toGOs($event)"
      id="file"
    /><br />
    <canvas  id="canvas"></canvas>
    <p>{
   
   { name }}</p>
  </div>

Page code The
picture needs to be converted to base64 and the encoding header is removed before uploading after urlencode. The
picture size is too large.
We compress the picture.
Compression principle. Large pictures are drawn to small canvases into small pictures.
Recommendation: You can call the
webmaster tool to convert online pictures to base64 during testing.
Webmaster tool urlencode encoding

The first step is to upload the image file

 let file = event.target.files[0];
 let reader = new FileReader();
 reader.readAsDataURL(file);

Compress image

Compression principle Draw a large picture to a small canvas into a small picture
Asynchronously load in reader.onload

  let canvas = document.getElementById("canvas");
  let context = canvas.getContext("2d");
  canvas.width = 100;
  canvas.height = (100 * image.height) / image.width ;
  context.drawImage(image, 0, 0, 100, (100 * image.height) / image.width);

Large pictures are compressed proportionally to width 100, height * ratio, if it does not exceed the limit, no compression is required, just add a picture width and height judgment, this time unified compression

Image to base64, remove header, encode

  let d = canvas.toDataURL();//base64
let urlcode = d.substring(reader.result.indexOf(","));//去头
let encodeurl =  encodeURIComponent(this.urlcode);//编码

Submit data processing data

submit data

 axios
      .post(
       "https://aip.baidubce.com/rest/2.0/image-classify/v1/animal?access_token=你的Access Token" + encodeurl
          )

Submit and process the data The data
received looks like this
Insert picture description here

We only display the first one, so we can extract as many data as we want

 axios
      .post(
       "https://aip.baidubce.com/rest/2.0/image-classify/v1/animal?access_token=你的Access Token" + encodeurl
          ).then(res => {
            this.name = res.data.result[0].name;
          });

Complete code written by the test

<template>
  <div>
    <input
      type="file"
      accept="image/*"
      @change="toBase64s($event)"
      id="file"
    /><br />
    <canvas  id="canvas"></canvas>
    <p>{
   
   { name }}</p>
  </div>
</template>

<script>
import axios from "axios";
export default {
     
     
  name: "ind",
  data() {
     
     
    return {
     
     
      srcs: "",
      urlcode: "",
      name: ""
    };
  },
  methods: {
     
     
    toBase64s(event) {
     
     
      // console.log(event.target.files)
      let file = event.target.files[0];
      let reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => {
     
     
        this.srcs = reader.result;
        let image = new Image();
        image.src = this.srcs;
        let canvas = document.getElementById("canvas");
        let context = canvas.getContext("2d");
        canvas.width = 100;
        canvas.height = (100 * image.height) / image.width ;
        context.drawImage(image, 0, 0, 100, (100 * image.height) / image.width);
        let d = canvas.toDataURL();
        this.urlcode = d.substring(reader.result.indexOf(","));
        axios
          .post(
            "https://aip.baidubce.com/rest/2.0/image-classify/v1/animal?access_token=xxxxxx&image=" +
			                encodeURIComponent(urlcode)
          )
          .then(res => {
     
     
            this.name = res.data.result[0].name;
          });
      };
    }
  },
  mounted() {
     
     }
};
</script>

<style scoped></style>

Insert picture description here
It may be a bit inaccurate. After all, I used the free version, but I actually took a mixed picture of duck and goose.

HTML version

Sili is the same as vue, the
effect
Insert picture description here
code is as follows

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
	</head>
	<body>
		  <div>
		    <input
		      type="file"
		      accept="image/*"
		      onchange="toBase64s()"
		      id="file"
		    /><br />
		    <canvas  id="canvas"></canvas>
		    <p id="names"></p>
		  </div>
		  <script type="text/javascript">
			  
			  function toBase64s() {
     
     
			        // console.log(event.target.files)
			        let file = document.getElementById("file").files[0];
			        let reader = new FileReader();
			        reader.readAsDataURL(file);
			        reader.onload = () => {
     
     
			          let srcs = reader.result;
			          let image = new Image();
			          image.src = srcs;
			          // console.log(image.style.height+"+"+image.width)
			          let canvas = document.getElementById("canvas");
			          let context = canvas.getContext("2d");
			          canvas.width = 100;
			          canvas.height = (100 * image.height) / image.width ;
			          context.drawImage(image, 0, 0, 100, (100 * image.height) / image.width);
			          let d = canvas.toDataURL();
			          console.log(d);
			          let urlcode = d.substring(reader.result.indexOf(","));
			          axios
			            .post(
			              "https://aip.baidubce.com/rest/2.0/image-classify/v1/animal?access_token=xxxxxx&image=" +
			                encodeURIComponent(urlcode)
			            )
			            .then(res => {
     
     
			              document.getElementById("names").innerText = res.data.result[0].name;
			            });
			        };
			      }
		  </script>
	</body>
</html>







  Hello everyone, I am a code husky, a student of network engineering in the Software College, because I am a "dog", and I can eat meat for thousands of miles. I want to share what I learned during university and make progress with everyone. However, due to the limited level, there will inevitably be some mistakes in the blog. If there are any omissions, please let me know! For the time being, only update on the csdn platform, the blog homepage: https://blog.csdn.net/qq_42027681 .

未经本人允许,禁止转载

Insert picture description here


Will be launched later

Front-end: vue entry vue development applet, etc.
Back-end: java entry springboot entry, etc.
Server: MySQL entry server simple instructions cloud server to run the project
python: recommended not to warm up, be sure to see
the use of some plug-ins, etc.

The way of university is also in oneself, study hard, youth
with passion. If you are interested in programming, you can join our qq group to communicate together: 974178910
Insert picture description here

If you have any questions, you can leave a message below, I will reply if you see it

Guess you like

Origin blog.csdn.net/qq_42027681/article/details/109787372