一、阿里云官网资料及配置本地
二、配置环境变量
三、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。
执行以下命令,配置环境变量。
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为例进行说明。
# -*- coding: utf-8 -*-
# 引入依赖包
# pip install alibabacloud_imagerecog20190930
import 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 RuntimeOptions
config = 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',
# 访问的域名对应的region
region_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:
# 初始化Client
client = 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秒)
如上,测试成功,说明阿里云垃圾分类方案对接成功。
改造下garbage.py里面的代码,封装成一个函数,供后C程序调用
# garbage.py
# -*- coding: utf-8 -*-
# 引入依赖包
# pip install alibabacloud_imagerecog20190930
import 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 RuntimeOptions
config = 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',
# 访问的域名对应的region
region_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 = img
runtime = RuntimeOptions()
try:
# 初始化Client
client = 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()
#if 1
#include
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
#ifndef __GARBAGE__H
#define __GARBAGE__H
void garbage_init();
void garbage_final();
char *garbage_category(char *category);
#endif
#if 1
#include
#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
#include
#include
#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