华为图像识别-智慧相册

一、准备

1.工具:VS Code

2.华为云中创建并下载ak和sk

3.安装依赖包

4.准备打标图片,放入目录data

5.根据需求分段执行代码

# 调用包从图像识别包中调用,图像标签,工具包
import utils as ut
import image_tagging as it
# 调用 json 解析传回的结果
import json
# 操作系统文件/文件夹的包
import os
import ais
# 图像处理展示相关的包
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt

def init_global_env(region):
    os.environ[ais.AisService.REGION_MSG] = region

init_global_env('cn-north-4')
# 准备 ak,sk
app_key = 'UUVCBAJJ000U73OBFXP8'
app_secret = 'NriwbSLOVzja9Jq3gj1lr51zyhdBotj9Ra22pwpM'

# ---------------------------------------------------------------
# 打标文件夹下的照片
# # 保存图片标签的字典
# labels = {}
# items = os.listdir(file_path)
# for i in items:
# # 判断是否为文件,而不是文件夹
#     if os.path.isfile:
#         # 华为云 EI 目前支持 JPG/PNG/BMP 格式的图片
#         if i.endswith('jpg') or i.endswith('jpeg') or i.endswith('bmp') or i.endswith('png'):
#             # 为图片打上标签
#             result = it.image_tagging_aksk(app_key, app_secret, 
#             ut.encode_to_base64(file_path + i), '', 'zh', 5, 60)
#             # 解析返回的结果
#             result_dic = json.loads(result)
#             # 将文件名与图片对齐
#             labels[i] = result_dic['result']['tags']
# # 显示结果
# print(labels)

# 保存打标结果
#将标签字典保存到文件
save_path = 'data\\label'
# # 如果文件夹不存在则创建文件
# if not os.path.exists(save_path):
#     os.mkdir(save_path)
# # 创建文件,执行写入操作,并关闭
# with open(save_path + '/labels.json', 'w+') as f:
#     f.write(json.dumps(labels))
# --------------------------------------------------------------
# 用标签分类照片
# 自动分类
# 打开保存的 labels 文件
label_path = file_path+'label\\labels.json'
with open(label_path,'r') as f:
    labels = json.load(f)
print(labels)
# 获取置信度最高的文件分类
classes =[[v[0]['tag'],k] for k, v in labels.items()]
classes
for cls in classes:
    if not os.path.exists(file_path + cls[0]):
        os.mkdir(file_path+ cls[0])
# 复制被对应的图片
    shutil.copy(file_path+ cls[1], file_path+ cls[0]+ 
    '/' + cls[1])
print('已完成移复制!')

分类效果如下:

119 views
Comments
登录后评论
Sign In
·

帖子放不了太多东西,就先这样吧