Recently, Beijing started to carry out garbage sorting, which has led to a sudden increase in the research interest of garbage, garbage people say that they have never received such a high level of attention. In fact, Shanghai began to implement last year, there are many mature online courses, such as “garbage classification from entry to master”, “simple garbage classification”, “10 basic principles of garbage classification you should master”. It’s out of character for us to do it ourselves. As programmers, we should leave it to the machine so we can spend more time working on 996.
So much nonsense, now to get back to the point, today this article mainly introduces how to use existing tools to implement a garbage sorting application. I came up with this idea yesterday and finished it in less than a day today. I mainly made three core contents:
- Compare existing garbage classification services, select a suitable and code implementation
- Develop a desktop garbage sorting APP
- Develop micro program for garbage classification
The first part of the above three parts is back-end work, the other two parts are front-end work, so I don’t have much experience in these three parts, basically oriented to search engine programming. Although my main business is doing big data, I really want to do such an interesting project, after all, a front-end is not a good big data engineer.
Old rules, first look at the renderings, PC version:
Small program:
Attach the small program QR code, you can experience. If you can’t see the effect, you may not pass the audit. You can open it a little later.
This article will post more code, and the public number is not very convenient to read, so I will attach the source code at the end of the article. (Public number reply keyword garbage classification can get the whole article all source code)
So, let’s get into the details of how it’s done. In fact, garbage classification has begun for a long time, there will certainly be some service providers to garbage classification ability through THE WAY of API open for everyone to call. I found 3 simple comparison for your reference:
- Aggregated data (www.juhe.cn) : provides text, image, and voice classification. Free call 20 times, inflexible pricing can only be bought in bulk
- Skyline Data (www.tianapi.com) : provides text, image and voice classification. Text classification 5000 times, other 50 times, pricing by volume
- Jd AI open platform: text, image and voice classification. Free, 5000 times a day
After a simple comparison of image classification, aggregation and day line data are obviously better, and after comprehensive pricing factors, I finally decided to use day line data. Let’s write the code to encapsulate the API interface into the service we need. Take the text (junk name) classification interface as an example. The requested interface is as follows
http://api.tianapi.com/txapi/lajifenlei/index?key=APIKEY&word= glassesCopy the code
APIKEY needs to be registered on the Tianhang website to obtain, and the result returned is as follows:
{
"code":200.
"msg":"success".
"newslist": [
{
"name":"Contact lenses".
"type":3.
"aipre":0.
"explain":"Dry waste means other waste, which means domestic waste other than recyclables, hazardous waste and kitchen waste (wet waste).".
"contain":"Common items include tiles, ceramics, muck, toilet paper, cat litter, soiled plastic, hair, hard shells, disposable products, clay, porcelain fragments and other difficult to recycle waste.".
"tip":"Drain as much water as possible; Household waste that is difficult to identify can be put into dry waste containers."
},
{
"name":"Glasses".
"type":3.
"aipre":0.
"explain":"Dry waste means other waste, which means domestic waste other than recyclables, hazardous waste and kitchen waste (wet waste).".
"contain":"Common items include tiles, ceramics, muck, toilet paper, cat litter, soiled plastic, hair, hard shells, disposable products, clay, porcelain fragments and other difficult to recycle waste.".
"tip":"Drain as much water as possible; Household waste that is difficult to identify can be put into dry waste containers."
},
]
}
Copy the code
The field description of the interface can be seen in the official documentation, but I won’t go over it here. Write the following request text classification interface code:
import base64
import requests
class TxApiService:
def __init__(self):
self.appkey = 'xxx' # Need to change to your own
self.text_cls_url_root = 'https://api.tianapi.com/txapi/lajifenlei/index?key=%s&word=%s'
self.img_cls_url_root = 'https://api.tianapi.com/txapi/imglajifenlei/index'
def get_text_cls_res(self, garbage_name):
url = self.text_cls_url_root % (self.appkey, garbage_name)
response = requests.get(url)
res = []
if response.status_code == 200:
res_json = response.json()
if res_json.get('newslist') :
new_list_json = res_json['newslist']
for item in new_list_json:
name = item.get('name')
cat = self.garbage_id_to_name(item.get('type'))
tip = item.get('tip')
ai_pre = item.get('aipre')
pre_type = 'None'
if ai_pre == 0:
pre_type = 'Normal result'
if ai_pre == 1:
pre_type = 'Prediction result'
item_dict = {'name': name, 'type': cat, 'tip': tip, 'pre_type': pre_type}
res.append(item_dict)
return res
else:
return None
return None
def garbage_id_to_name(self, id):
if id == 0:
return 'Recyclables'
if id == 1:
return 'Hazardous waste'
if id == 2:
return 'Kitchen waste'
if id == 3:
return 'Other Rubbish'
return None
Copy the code
The code is simple, using Python’s Requests library to request the garbage sorting interface and format the returned data. Next to write the request image classification interface
def get_img_cls_res(self, img_base64):
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
body = {
'key': self.appkey,
"img": img_base64,
}
response = requests.post(self.img_cls_url_root, headers=headers, data=body)
res = []
if response.status_code == 200:
res_json = response.json()
if res_json.get('newslist') :
new_list_json = res_json['newslist']
for item in new_list_json:
name = item.get('name')
cat = self.garbage_id_to_name(item.get('lajitype'))
tip = item.get('lajitip')
trust = item.get('trust')
if trust <= 80:
continue
item_dict = {'name': name, 'type': cat, 'tip': tip, 'pre_score': trust}
res.append(item_dict)
return res
else:
return None
return None
Copy the code
The parameter of the function is the base64 encoding of the image, and the request is a POST request. The return value field is slightly different from the text classification, but the idea is the same. These two parts are actually simpler, so I won’t explain them too much here.
With data service, let’s develop GUI. Here I use Tkinter, and the APP written with it can run on Linux, Windows and Mac systems. I won’t give too much introduction to the use of Tkinter. I’ve never done this before and I’ve basically followed the instructions on the Internet. First, create the GarbageClassificationApp class to define the various components used
import base64
import tkinter
from tkinter import *
import hashlib
import time
from tkinter import filedialog
from TxApiService import TxApiService
class GarbageClassificationApp:
def __init__(self, tk):
"" "
Initialize each component
:param tk:
"" "
self.tk = tk
The first line defines the components related to text categorization
self.text_cls_label = Label(self.tk, text="Garbage name:")
self.garbage_name_text = Entry(self.tk)
self.text_cls_button = \
Button(self.tk, text="Garbage Name Classification", bg="lightblue", width=10, height=1, command=self.garbage_name_cls)
The second line defines the components related to image classification
self.img_cls_label = Label(self.tk, text="Junk pictures:")
self.select_file_button = Button(self.tk, text='Select picture', command=self.select_pic)
self.img_cls_button = \
Button(self.tk, text="Picture classification", bg="lightblue", width=10, height=1, command=self.garbage_img_cls)
self.img_name_text = Text(self.tk, height=2)
self.img_name_text.insert(1.0.'Unselected image:')
self.img_name_text['state'] = DISABLED
The third line defines the components associated with the output
self.cls_result_label = Label(self.tk, text="Classification Results:")
self.output_cls_result_list_box = Listbox(self.tk, width=100, height=30)
Initialize the API service
self.api_service = TxApiService()
self.set_init_window()
Copy the code
Then create the set_init_window function to lay out the components
Component layout
def set_init_window(self):
self.tk.title("Garbage sorting")
self.tk.geometry('1068x681+350+200') # 1068x681 is the window size, +100 +100 defines the default display position when the window pops up
The first line of text classifies the layout of each component
self.text_cls_label.grid(row=0, column=0, sticky=E)
self.garbage_name_text.grid(row=0, column=1)
self.text_cls_button.grid(row=0, column=2, padx=10)
# The second line of image classifies the layout of each component
self.img_cls_label.grid(row=1, column=0, sticky=E)
self.select_file_button.grid(row=1, column=1)
self.img_cls_button.grid(row=1, column=2, padx=10)
self.img_name_text.grid(row=1, column=3, padx=10)
The third line outputs the layout of the resulting components
self.cls_result_label.grid(row=2, column=0, rowspan=2, sticky=E)
self.output_cls_result_list_box.grid(row=4, column=1, columnspan=10, pady=10, sticky=E)
Copy the code
This completes the interface. Some of the components defined above have some event handling logic, such as when a Button Button is pressed, it calls the function specified by the Commond property. Take the text classification Button as an example (text_cls_button). After the user presses the Button, the program will execute the garbage_name_cls function, in which we can request the text classification service and display the returned data on the interface. The code is as follows:
def garbage_name_cls(self):
garbage_name = self.garbage_name_text.get()
cat_arr = self.api_service.get_text_cls_res(garbage_name)
self.output_cls_result_list_box.delete(0, END)
if cat_arr:
i = 0
for item in cat_arr:
name = 'Garbage name: %s' % item.get('name'.'None')
self.output_cls_result_list_box.insert(i, name)
i += 1
cat = 'Garbage category: %s' % item.get('type'.'None')
self.output_cls_result_list_box.insert(i, cat)
i += 1
pre_type = 'Prejudgment type: %s' % item.get('pre_type'.'None')
self.output_cls_result_list_box.insert(i, pre_type)
i += 1
tip = 'Drop hint: %s' % item.get('tip'.'None')
self.output_cls_result_list_box.insert(i, tip)
i += 1
self.output_cls_result_list_box.insert(i, ' ')
i += 1
Copy the code
The other event processing logic is similar, and the code is as follows
def select_pic(self):
"" "
Radio images
:return:
"" "
file_name = filedialog.askopenfilename(
filetypes=[('images', ('.png'.'.jpg'.'.jpeg')))
if file_name:
self.img_name_text['state'] = NORMAL
self.img_name_text.delete(1.0, END)
self.img_name_text.insert(1.0.'Selected image: %s' % file_name)
self.img_name_text['state'] = DISABLED
def garbage_img_cls(self):
img_name_text = self.img_name_text.get(1.0, END)
if img_name_text.startswith('Selected image:') :
file_path = img_name_text[6:].strip()
else:
return
with open(file_path, 'rb') as f:
base64_data = base64.b64encode(f.read())
img_base64 = base64_data.decode()
cat_arr = self.api_service.get_img_cls_res(img_base64)
self.output_cls_result_list_box.delete(0, END)
if cat_arr:
i = 0
for item in cat_arr:
name = 'Garbage name: %s' % item.get('name'.'None')
self.output_cls_result_list_box.insert(i, name)
i += 1
cat = 'Garbage category: %s' % item.get('type'.'None')
self.output_cls_result_list_box.insert(i, cat)
i += 1
pre_type = 'Predicted score: %s' % item.get('pre_score'.'None')
self.output_cls_result_list_box.insert(i, pre_type)
i += 1
tip = 'Drop hint: %s' % item.get('tip'.'None')
self.output_cls_result_list_box.insert(i, tip)
i += 1
self.output_cls_result_list_box.insert(i, ' ')
i += 1
Copy the code
At this point, the PC desktop APP has been developed. We have not implemented the voice classification service here, but the idea is the same. You can try it. Small program code I will not stick, I will put together in the source directory, in the public number reply keyword garbage classification can get the whole article all source. It took a lot of time to develop this small project today, and the article was sorted out late. Now it is about 1:00 a.m. If you need me to explain the latter in depth, you can leave a message to me. In addition, the time is tight, so the APP is poor and the interaction is poor. Any suggestions are welcome to leave a message.
Welcome the public account “du Code” to export the dry goods you can’t see elsewhere.