Alibaba cloud OSS upload and intelligent image recognition garbage recognition

Posted by varzosu on Wed, 23 Feb 2022 13:55:49 +0100

Alibaba cloud OSS object storage upload pictures and intelligent image recognition garbage recognition

I believe that the majority of novice programmers, like me, want to write an intelligent image recognition, but they can't find it in Baidu or don't know what it means when they check. Next, I will contribute my own process and code of writing and checking documents

preparation
First, we have to Apply for Alibaba cloud intelligent image recognition
Search here for intelligent image recognition

Then choose here Portal

Open here

Of course, I have opened it, so I can't open it again. I can only choose [East China 2 (Shanghai)] here to open all intelligent image recognition except for paid use

Then the place agreed

Finally, select "open now" in the lower right corner

Here is Document address of Alibaba cloud intelligent image recognition , here are detailed descriptions of various parameters

Here's my code

First use node JS interface technology, I believe all the leaders know what nodejs needs to prepare, and I will present my most important part

I also came out of Baidu here, and then according to the document reference Baidu came out
First NPM I @ alicloud / Pop core - save

// Alibaba cloud visual intelligent open platform image recognition garbage classification
// Garbage classification and recognition in image recognition
const Core = require('@alicloud/pop-core')

server.post('/gcs', (req, res, next) => {
  var client = new Core({
    accessKeyId: 'This is your address at Alibaba cloud AccessKey ID,I believe everyone knows how to apply',
    accessKeySecret: 'Here is every AccessKey ID Corresponding AccessKey Secret',
    // securityToken: '<your-sts-token>', // use STS Token
    endpoint: 'https://imagerecog.cn-shanghai.aliyuncs.com',
    apiVersion: '2019-09-30',
  })
  let imgUrl = req.body.imgUrl//I'm here to cooperate with vue to obtain the url address on the OSS object storage server corresponding to the image generated after the image is uploaded successfully
  var params = {
    ImageURL: imgUrl,
  }

  var requestOption = {
    method: 'POST',
  }

  client.request('ClassifyingRubbish', params, requestOption).then(
    ress => {
      // console.log(JSON.stringify(ress))
      res.send({
        message: 'Recognition successful',
        code: 200,
        results: ress,
      })
    },
    err => {
      // console.log(err)
      res.send({ message: 'Recognition failure', code: 201, results: err })
      return
    }
  )
})

The next step is to upload pictures from Alibaba cloud OSS object storage

First, we need to enter the Alibaba cloud console

Click here after entering

Then search the object storage OSS
If you don't open it, he will prompt you to open it

Then create a buffer here


The next step is to present my code snippet. I use vue+vant

First, NPM I Ali OSS

Create a utils folder in the src directory, and then create a JS file alioss js

alioss.js

var OSS = require("ali-oss")

export function client() {
  var client = new OSS({
    Region: "East China 2 (Shanghai)",//If you follow my steps, this is it
    region: "oss-cn-shanghai",//If you follow my steps, this is it
    Endpoint: "oss-cn-shanghai",//If you follow my steps, this is it
    //   region: 'oss.shanci.tech',
    accessKeyId: "This is the same as the one above accessKeyId equally",
    accessKeySecret: "This is the same as the one above accessKeySecret equally",
    bucket: "gcss",//Here is the name of the buffer just created
  }) //Back end provides data
  return client
}

index.vue
HTML part

 <van-grid :border="false" :column-num="5">
      <van-uploader :after-read="afterRead">
        <van-grid-item>
          <van-icon name="photograph" size="2.3rem" color="#666" />
          <span>Photo recognition</span>
        </van-grid-item>
      </van-uploader>
 </van-grid>
 
 <!-- Pop up layer after garbage identification -->
 <!-- Popup  -->
 <van-popup v-model="show" closeable>
   <div class="ljfl-tcc">
     <img :src="url" alt="" />
     <span>garbage:{{ garbage_lj.Rubbish }}</span>
     <span>Garbage category:{{ garbage_lj.Category }}</span>
   </div>
 </van-popup>


<script>
import { client } from "../utils/alioss"//Here is the introduction of alioss JS file
export default {

 data() {
   return {
     url: "", //url parameters passed after taking photos
     garbage_lj: "", //Garbage data sent back after taking photos
   }
 },
 methods: {
   afterRead(file) {
     this.$toast.loading({
       message: "Identifying...",
       forbidClick: true,
     })
     // At this time, you can upload the file to the server by yourself
     file.status = "uploading"
     file.message = "Uploading..."
     let len = len || 32
     var Imgname = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678"
     var maxPos = Imgname .length
     var pwd = ""
     for (let i = 0; i < len; i++) {
       pwd += Imgname .charAt(Math.floor(Math.random() * maxPos)) // Generate 32-bit random characters
     }
     let name = file.file.name
     var pos = name.indexOf(".")
     let type = name.substr(pos)
     var fileName = `${Date.parse(new Date())}` + pwd + type // File name (timestamp + random character + suffix)
     client()
       .multipartUpload(fileName, file.file)
       .then((res) => {
         this.url = res.res.requestUrls[0].split("?")[0]
         // console.log("res", res.res.requestUrls[0])
         console.log("url", this.url)
         let imageUrlObj = {}
         imageUrlObj.fileName = res.res.requestUrls[0]
         imageUrlObj.fileUrl = res.res.requestUrls[0]
         imageUrlObj.fileType = 1
         imageUrlObj.type = 1
         this.imageUrlIdCard = imageUrlObj
         // this.submitFile() / / call the backend interface to transfer the data returned by oss to the backend repository
         file.status = ""
         file.message = ""
         let params = `imgUrl=${this.url}`//Here is the url generated by the OSS object storage after the obtained image is uploaded successfully
         console.log(params)
         //This is to the node just now JS sends a request for garbage classification and identification
         this.axios.post("/gcs", params).then((res) => {
           // console.log(res)
           if (res.data.code != 200) {
             this.$toast.fail("i 'm sorry!Recognition failure!We are studying hard!")
           } else {
             this.garbage_lj = res.data.results.Data.Elements[0]
             // console.log(this.garbage_lj)
             this.show = true
           }
         })
       })
       .catch((err) => {
         console.warn(err)
       })
     console.log(file)
   },
 },
}
</script>

Style of pop-up layer

// Pop up layer style
<style lang="scss" scoped>
.van-popup--center {
 border-radius: 1.5rem;
}
.ljfl-tcc {
 width: 70vw;
 text-align: center;
 img {
   display: block;
   margin: auto;
   margin-top: 0.9rem;
   width: 90%;
   border-radius: 1.5rem;
 }
 span {
   display: block;
   margin: 0.7rem 0;
 }
}
.van-button--large {
 width: 90%;
 display: block;
 margin: auto;
 margin-bottom: 0.5rem;
}
</style>

This is the effect picture of my successful upload

Well, that's all for my introduction. It's not easy to write. If there's any infringement, please contact me, or if you feel there's something wrong, you can point it out and contact me for modification

Tomorrow is new year's Eve. I wish you all a happy new year in advance and your career will rise step by step in the new year

Thank you for your patience in reading the articles written by Xiao*

Topics: Front-end html Interview Deep Learning cloud computing