利用Python實現(xiàn)給圖像添加標簽
一、需求
給指定的圖片添加標簽
二、代碼
# !/usr/bin/env python
# coding: utf-8
import tkinter as tk
from tkinter import filedialog, messagebox
import os
import json
from google.protobuf.json_format import MessageToJson
from clarifai_grpc.channel.clarifai_channel import ClarifaiChannel
from clarifai_grpc.grpc.api import resources_pb2, service_pb2, service_pb2_grpc
from clarifai_grpc.grpc.api.status import status_code_pb2
# 授權密鑰
API_KEY = '5************************************'
USER_ID = '3*********h'
APP_ID = 'my***************'
# 注冊網(wǎng)址:https://www.clarifai.com/
# 網(wǎng)址注冊后,拿授權密鑰,每月1000次免費
def analyze_image(image_path):
# 使用 Clarifai API 進行圖像分析
results = []
channel = ClarifaiChannel.get_grpc_channel()
stub = service_pb2_grpc.V2Stub(channel)
metadata = (('authorization', 'Key ' + API_KEY),)
userDataObject = resources_pb2.UserAppIDSet(user_id=USER_ID, app_id=APP_ID)
with open(image_path, 'rb') as f:
file_bytes = f.read()
try:
print(f"開始分析圖像: {image_path}") # 添加調試語句
post_model_outputs_response = stub.PostModelOutputs(
service_pb2.PostModelOutputsRequest(
user_app_id=userDataObject,
model_id='general-image-recognition',
inputs=[
resources_pb2.Input(
data=resources_pb2.Data(
image=resources_pb2.Image(
base64=file_bytes
)
)
)
]
),
metadata=metadata
)
print(f"圖像分析完成: {image_path}") # 添加調試語句
except Exception as e:
messagebox.showerror("錯誤", "圖像分析失敗,原因: " + str(e))
return
if post_model_outputs_response.status.code != status_code_pb2.SUCCESS:
messagebox.showerror("錯誤", "模型輸出提交失敗,狀態(tài): " + post_model_outputs_response.status.description)
return
# 將獲取到的結果轉為 JSON
json_result = MessageToJson(post_model_outputs_response)
json_output = json.loads(json_result)
print(json_output)
# 從 JSON 結果中提取并顯示關鍵信息
for output in json_output["outputs"]:
for concept in output['data']['concepts']:
object_name = concept['name']
results.append(object_name)
return results
if __name__ == '__main__':
image_path = r"D:\Desktop\tp.png"
ret = analyze_image(image_path)三、圖片

四、結果
['interior design', 'luxury', 'contemporary', 'indoors', 'furniture', 'comfort', 'family', 'room', 'hotel', 'sofa', 'no person', 'minimalist', 'rug', 'chair', 'seat', 'lamp', 'coffee table', 'curtain', 'trading floor', 'mansion']
到此這篇關于利用Python實現(xiàn)給圖像添加標簽的文章就介紹到這了,更多相關Python圖像添加標簽內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
python六種基本數(shù)據(jù)類型及常用函數(shù)展示
這篇文章主要為大家介紹了python六種基本數(shù)據(jù)類型及常用函數(shù),具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助2021-11-11
python+selenium實現(xiàn)自動化百度搜索關鍵詞
在本篇文章里我們給大家分享了一篇關于python+selenium實現(xiàn)自動化百度搜索關鍵詞的實例文章,需要的朋友們可以跟著操作下。2019-06-06
Python中的命名元組簡單而強大的數(shù)據(jù)結構示例詳解
namedtuple是Python中一個非常有用的數(shù)據(jù)結構,它提供了一種簡單的方式創(chuàng)建具有固定字段的輕量級對象,通過使用namedtuple,可以提高代碼的可讀性和可維護性,避免了使用類定義對象的復雜性,這篇文章主要介紹了Python中的命名元組簡單而強大的數(shù)據(jù)結構,需要的朋友可以參考下2024-05-05

