一、阿里云官网资料及配置本地
二、配置环境变量
三、C语言调用阿里云Python接口
一、阿里云官网资料及配置本地
阿里云官网
垃圾识别分类
sudo apt install python3-pip
pip3 install alibabacloud_imagerecog20190930
可能出现的网络问题
二、配置环境变量
配置环境变量ALIBABA_CLOUD_ACCESS_KEY_ID和ALIBABA_CLOUD_ACCESS_KEY_SECRET。
-
Linux和macOS系统配置方法
-
在IntelliJ IDEA中打开终端Terminal。
-
执行以下命令,配置环境变量。
-
<access_key_id>需替换为您RAM用户的AccessKey ID,<access_key_secret>替换为您RAM用户的AccessKey Secret。如果后续需要进行更多权限相关的配置,具体操作请参见使用RAM Policy控制访问权限。
export ALIBABA_CLOUD_ACCESS_KEY_ID=<access_key_id>
export ALIBABA_CLOUD_ACCESS_KEY_SECRET=<access_key_secret>
vi ~/.bashrc
和 /etc/profile
#然后在末尾输入上面两行后保存
然后退出终端重新登录下,此时再执行export,能看到这两个Key的存在
export
declare -x ALIBABA_CLOUD_ACCESS_KEY_ID="你的阿里云Key ID"
declare -x ALIBABA_CLOUD_ACCESS_KEY_SECRET="你的阿里云Key Secret"
-
Windows系统配置方法
新建环境变量文件,添加环境变量ALIBABA_CLOUD_ACCESS_KEY_ID和ALIBABA_CLOUD_ACCESS_KEY_SECRET,并写入已准备好的AccessKey ID和AccessKey Secret。然后重启Windows系统。本操作以Windows 10为例进行说明。-
打开文件资源管理器,在此电脑上右键单击属性。
-
在右侧导航栏,单击高级系统配置。
-
在系统属性对话框的高级页签下,单击环境变量。
-
在环境变量对话框中,单击新建(W)。
-
在弹出的新建系统变量对话框中,添加环境变量ALIBABA_CLOUD_ACCESS_KEY_ID和ALIBABA_CLOUD_ACCESS_KEY_SECRET,并写入已准备好的AccessKey ID和AccessKey Secret。
-
重启Windows系统,使配置生效。
-
示例代码
文件在本地或文件不在同一地域OSS
# -*- coding: utf-8 -*-
# 引入依赖包
# pip install alibabacloud_imagerecog20190930import os
import io
from urllib.request import urlopen
from alibabacloud_imagerecog20190930.client import Client
from alibabacloud_imagerecog20190930.models import ClassifyingRubbishAdvanceRequest
from alibabacloud_tea_openapi.models import Config
from alibabacloud_tea_util.models import RuntimeOptionsconfig = Config(# 创建AccessKey ID和AccessKey Secret,请参考https://help.aliyun.com/document_detail/175144.html。# 如果您用的是RAM用户的AccessKey,还需要为RAM用户授予权限AliyunVIAPIFullAccess,请参考https://help.aliyun.com/document_detail/145025.html# 从环境变量读取配置的AccessKey ID和AccessKey Secret。运行代码示例前必须先配置环境变量。access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'),access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),# 访问的域名endpoint='imagerecog.cn-shanghai.aliyuncs.com',# 访问的域名对应的regionregion_id='cn-shanghai'
)
#场景一:文件在本地
#img = open(r'/tmp/ClassifyingRubbish1.jpg', 'rb')
#场景二:使用任意可访问的url
url = 'https://viapi-test-bj.oss-cn-beijing.aliyuncs.com/viapi-3.0domepic/imagerecog/ClassifyingRubbish/ClassifyingRubbish1.jpg'
img = io.BytesIO(urlopen(url).read())
classifying_rubbish_request = ClassifyingRubbishAdvanceRequest()
classifying_rubbish_request.image_urlobject = img
runtime = RuntimeOptions()
try:# 初始化Clientclient = Client(config)response = client.classifying_rubbish_advance(classifying_rubbish_request, runtime)# 获取整体结果print(response.body)
except Exception as error:# 获取整体报错信息print(error)# 获取单个字段print(error.code)
场景一是从本地读取文件
场景二是从网址上访问读取文件
将场景二注释,场景一代码打开,并修改输入自己测试图片的路径,如下:
其中“/home/orangepi/Image_recognition/test.png”为本地测试用图片路径(根据在线文档要求:图像类型:JPEG、JPG、PNG,图像大小:不大于3 MB,图像分辨率:不限制图像分辨率,但图像分辨率太高可能会导致API识别超时,超时时间为5秒)
如上,测试成功,说明阿里云垃圾分类方案对接成功。
三、C语言调用阿里云Python接口
调用前先测试下
改造下garbage.py里面的代码,封装成一个函数,供后C程序调用
# garbage.py
# -*- coding: utf-8 -*-
# 引入依赖包
# pip install alibabacloud_imagerecog20190930import os
import io
from urllib.request import urlopen
from alibabacloud_imagerecog20190930.client import Client
from alibabacloud_imagerecog20190930.models import ClassifyingRubbishAdvanceRequest
from alibabacloud_tea_openapi.models import Config
from alibabacloud_tea_util.models import RuntimeOptionsconfig = Config(# 创建AccessKey ID和AccessKey Secret,请参考https://help.aliyun.com/document_detail/175144.html。# 如果您用的是RAM用户的AccessKey,还需要为RAM用户授予权限AliyunVIAPIFullAccess,请参考https://help.aliyun.com/document_detail/145025.html# 从环境变量读取配置的AccessKey ID和AccessKey Secret。运行代码示例前必须先配置环境变量。access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'),access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),# 访问的域名endpoint='imagerecog.cn-shanghai.aliyuncs.com',# 访问的域名对应的regionregion_id='cn-shanghai'
)def alibaba_garbage():# 场景一:文件在本地img = open(r'/home/orangepi/Image_recognition/test.png', 'rb')# 场景二:使用任意可访问的url# url = 'https://viapi-test-bj.oss-cn-beijing.aliyuncs.com/viapi-3.0domepic/imagerecog/ClassifyingRubbish/ClassifyingRubbish1.jpg'# img = io.BytesIO(urlopen(url).read())classifying_rubbish_request = ClassifyingRubbishAdvanceRequest()classifying_rubbish_request.image_urlobject = imgruntime = RuntimeOptions()try:# 初始化Clientclient = Client(config)response = client.classifying_rubbish_advance(classifying_rubbish_request, runtime)# 获取整体结果# print(response.body)# 打印并返回需要的结果print(response.body.to_map()['Data']['Elements'][0]['Category'])return response.body.to_map()['Data']['Elements'][0]['Category']except Exception as error:# 获取整体报错信息# print(error)print(type('获取失败'))return '获取失败'# 获取单个字段# print(error.code)if __name__ == "__main__":alibaba_garbage()
garbage.c
#if 1
#include <Python.h>int main() {// 初始化Python解释器Py_Initialize();// 获取sys.path对象PyObject* sysPath = PySys_GetObject("path");// 将当前路径添加到sys.path中PyList_Append(sysPath, PyUnicode_DecodeFSDefault(".")); // PyUnicode_FromString将c字符串转换成Python字符串// 导入Python模块PyObject* pModule = PyImport_ImportModule("garbage");if (pModule != NULL) {// 获取Python函数对象PyObject* pFunction = PyObject_GetAttrString(pModule, "alibaba_garbage");if (pFunction != NULL && PyCallable_Check(pFunction)) {// 调用Python函数,这里是无参数调用PyObject* pArgs = PyTuple_New(0); // 传递空参数元组PyObject* pResult = PyObject_CallObject(pFunction, pArgs);if (pResult != NULL) {// 将返回值转换为C类型char *result = NULL;if (!PyArg_Parse(pResult, "s", &result)) {PyErr_Print();printf("Error: parse failed\n");}// 打印返回值printf("pResult = %s\n", result);Py_DECREF(pResult);} else {PyErr_Print(); // 打印Python错误信息}Py_DECREF(pFunction);Py_DECREF(pArgs);} else {PyErr_Print();}Py_DECREF(pModule);} else {PyErr_Print();}// 关闭Python解释器Py_Finalize();return 0;
}
#endif
c调用python代码garbage.py里函数, 封装并实现以下代码
garbage.h
#ifndef __GARBAGE__H
#define __GARBAGE__Hvoid garbage_init();
void garbage_final();
char *garbage_category(char *category);#endif
garbage.c
#if 1
#include <Python.h>
#include "garbage.h"void garbage_init()
{// 初始化Python解释器Py_Initialize();// 获取sys.path对象PyObject* sysPath = PySys_GetObject("path");// 将当前路径添加到sys.path中PyList_Append(sysPath, PyUnicode_DecodeFSDefault(".")); // PyUnicode_FromString将c字符串转换成Python字符串
}void garbage_final()
{// 关闭Python解释器Py_Finalize();
}char *garbage_category(char *category)
{// 导入Python模块PyObject* pModule = PyImport_ImportModule("garbage");if (pModule != NULL) {// 获取Python函数对象PyObject* pFunction = PyObject_GetAttrString(pModule, "alibaba_garbage");if (pFunction != NULL && PyCallable_Check(pFunction)) {// 调用Python函数,这里是无参数调用PyObject* pArgs = PyTuple_New(0); // 传递空参数元组PyObject* pResult = PyObject_CallObject(pFunction, pArgs);if (pResult != NULL) {// 将返回值转换为C类型char *result = NULL;if (!PyArg_Parse(pResult, "s", &result)) {PyErr_Print();printf("Error: parse failed\n");}// 打印返回值printf("pResult = %s\n", result);// 为垃圾分类信息分配内存,复制返回值category = (char *)malloc(sizeof(char) * (strlen(result) + 1));memset(category, 0, (strlen(result) + 1));strncpy(category, result, (strlen(result) + 1));Py_DECREF(pResult);} else {PyErr_Print(); // 打印Python错误信息}Py_DECREF(pFunction);Py_DECREF(pArgs);} else {PyErr_Print();}Py_DECREF(pModule);} else {PyErr_Print();}return category;
}
#endif
garbage_test.c
//garbage_test.c
#include <stdio.h>
#include <stdlib.h>
#include "garbage.h"int main(int argc, char *argv[])
{char *category = NULL;garbage_init();category = garbage_category(category);printf("category = %s\n", category);garbage_final();if (category) {free(category);}return 0;
}
编译和运行这个程序,可以使用以下命令(假设使用的是gcc编译器和Python 3.10版本):
gcc -o garbage_test garbage.h garbage.c garbage_test.c -I /usr/include/python3.10/ -l python3.10
./garbage_test