Menu

Skip to content
AppleScriptの穴
  • Home
  • Products
  • Books
  • Docs
  • Events
  • Forum
  • About This Blog
  • License
  • 仕事依頼

AppleScriptの穴

Useful & Practical AppleScript archive. Click '★Click Here to Open This Script' Link to download each AppleScript

Microsoft Azure Computer Vision API Version 1.0で画像認識(analyze) v2

Posted on 3月 27, 2018 by Takaaki Naganoya

Microsoft AzureのComputer Vision API Version 1.0(analyze)を呼び出して、画像認識するAppleScriptです。

Microsoft Azureで無料アカウントを取得して「Computer Vision API」を使用する設定にするとAPI Keyが開示されるので、Keyを本Script末尾のハンドラにコピー&ペーストで記入してください。

再掲載時に動作確認してみたら、REST APIのEndpointのURLがMicrosoft Projext OxfordからMicrosoft Azureのものに変更になっていたので、書き換えました。そのぐらいです。

あいかわらず、惚れ惚れするぐらい見事に画像認識してくれて驚かされます。これでWebサイトがわかりやすかったら最高なのに、、、、(ーー;; 

ちなみに、水着の女性の認識率がぶっちぎりで高く、その一方で子供の認識率が低いという趣味に走りまくった特徴があります。学習モデルの偏りがすごくて好感が持てます。顔認識、人物認識はWASP向けに最適化されていて、黄色人種などの有色人種の認識でえっらく苦労していますね。コンピュータには影の部分なので黒いのか、それとも髪が黒くてその部分が黒いのかはわかりません。とくに、われわれ「平たい顔」族の顔認識と、肌が黒い方々の顔認識が大変なようです。物量で乗り切るか、写真撮影の方法に一手間加えるしかありません。


–> {{metadata:{width:450, |format|:”Png”, height:600}, categories:{{|name|:”drink_”, score:0.6875}}, |description|:{tags:{“bottle”, “table”, “indoor”, “wine”, “sitting”, “food”, “glass”, “cup”, “beer”, “top”, “banana”, “wooden”, “computer”, “sandwich”, “counter”, “phone”, “desk”, “refrigerator”, “laying”, “pizza”, “kitchen”, “plate”, “white”}, captions:{{|text|:”a bottle of wine and a glass of beer on a table”, confidence:0.669977619305}}}, requestId:”fa209b50-f693-428b-9502-bb04ae18a612″}}


–> {{metadata:{width:450, |format|:”Png”, height:338}, categories:{{|name|:”others_”, score:0.00390625}, {|name|:”people_”, score:0.40625}}, |description|:{tags:{“cake”, “table”, “indoor”, “thing”, “birthday”, “object”, “food”, “sitting”, “lit”, “chocolate”, “plate”, “decorated”, “top”, “woman”, “covered”, “bowl”, “man”, “holding”, “people”, “standing”}, captions:{{|text|:”a person sitting at a table with a birthday cake with lit candles”, confidence:0.767489416177}}}, requestId:”f8a27ffe-7a0c-44ef-b4d3-403b539f7202″}}


–> {{metadata:{width:450, |format|:”Png”, height:338}, categories:{{|name|:”outdoor_”, score:0.0078125, detail:{landmarks:{}}}, {|name|:”outdoor_waterside”, score:0.2890625, detail:{landmarks:{}}}}, |description|:{tags:{“outdoor”, “sunset”, “building”, “plane”, “airplane”, “runway”, “sitting”, “large”, “track”, “front”, “sun”, “orange”, “cloudy”, “top”, “road”, “train”, “light”, “standing”, “city”, “riding”, “jet”, “red”, “bridge”, “tower”, “man”, “water”, “flying”, “white”, “night”, “parked”, “tarmac”, “blue”, “traffic”, “air”}, captions:{{|text|:”a sunset over a city”, confidence:0.920834312504}}}, requestId:”dce04975-c95a-4d70-9f9d-661ffda12de8″}}


–> {{metadata:{width:450, |format|:”Png”, height:338}, categories:{{|name|:”animal_horse”, score:0.984375}}, |description|:{tags:{“grass”, “outdoor”, “animal”, “bird”, “standing”, “field”, “water”, “white”, “walking”, “small”, “food”, “brown”, “sitting”, “large”, “green”, “grassy”, “parrot”, “river”}, captions:{{|text|:”a bird that is standing in the grass”, confidence:0.958508972922}}}, requestId:”4372eca0-ce0a-484a-ada9-4c49e5490f00″}}


–> {{metadata:{width:450, |format|:”Png”, height:338}, categories:{{|name|:”abstract_net”, score:0.18359375}, {|name|:”abstract_texture”, score:0.53515625}, {|name|:”others_”, score:0.00390625}}, |description|:{tags:{“animal”, “outdoor”, “shellfish”, “snail”, “food”, “bird”, “piece”, “sitting”, “street”, “laying”, “top”, “beach”, “fruit”, “standing”, “slug”, “plate”, “board”, “white”}, captions:{{|text|:”a snail on the ground”, confidence:0.889422773135}}}, requestId:”7edb1788-2887-45d9-bb48-68f78f72ee2c”}}


–> {{metadata:{width:450, |format|:”Png”, height:338}, categories:{{|name|:”dark_fireworks”, score:0.99609375}}, |description|:{tags:{“object”, “fireworks”}, captions:{{|text|:”fireworks in the sky”, confidence:0.542768984765}}}, requestId:”0a2d5b92-27ff-4ac4-a431-14ca2f0454c3″}}


–> {{metadata:{width:1280, |format|:”Jpeg”, height:960}, categories:{{|name|:”others_”, score:0.00390625}, {|name|:”outdoor_”, score:0.01171875, detail:{landmarks:{}}}}, |description|:{tags:{“outdoor”, “person”, “toy”, “thing”, “man”, “white”, “grass”, “standing”, “people”, “field”, “riding”, “jumping”, “doing”, “air”, “holding”, “group”, “trick”, “board”, “statue”, “dog”, “player”, “ramp”}, captions:{{|text|:”a statue of a man”, confidence:0.666301928732}}}, requestId:”45a3a778-c4d5-4b9e-9a0f-480345197fc6″}}

AppleScript名:Microsoft Asure Analyze Image APIで画像認識(analyze) v2
— Created 2017-05-03 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

property |NSURL| : a reference to current application’s |NSURL|
property NSData : a reference to current application’s NSData
property NSString : a reference to current application’s NSString
property NSMutableData : a reference to current application’s NSMutableData
property NSURLQueryItem : a reference to current application’s NSURLQueryItem
property NSURLConnection : a reference to current application’s NSURLConnection
property NSJSONSerialization : a reference to current application’s NSJSONSerialization
property NSURLComponents : a reference to current application’s NSURLComponents
property NSMutableDictionary : a reference to current application’s NSMutableDictionary
property NSMutableURLRequest : a reference to current application’s NSMutableURLRequest
property NSUTF8StringEncoding : a reference to current application’s NSUTF8StringEncoding
property NSURLRequestReloadIgnoringLocalCacheData : a reference to current application’s NSURLRequestReloadIgnoringLocalCacheData

set imgFilePath to POSIX path of (choose file of type {"public.image"} with prompt "Select an Image to Analyze")
set aRes to recogImage(imgFilePath) of me
–>  {{metadata:{width:3264, |format|:"Jpeg", height:2448}, categories:{{|name|:"abstract_", score:0.01171875}, {|name|:"abstract_shape", score:0.4609375}, {|name|:"others_", score:0.0078125}, {|name|:"outdoor_", score:0.046875, detail:{landmarks:{{|name|:"Tokyo Skytree", confidence:0.999957323074}}}}}, |description|:{tags:{"outdoor", "building", "bridge", "large", "water", "top", "tower", "blue", "tall", "riding", "city", "standing", "snow", "train", "man", "clock", "air", "sign", "white", "skiing", "street", "boat", "flying", "group", "people"}, captions:{{|text|:"a close up of Tokyo Skytree", confidence:0.90930354838}}}, requestId:"72909fd5-c0be-47dd-81ce-d626873fcbfe"}}

on recogImage(imgFilePath)
  set reqURLStr to "https://westcentralus.api.cognitive.microsoft.com/vision/v1.0/analyze" –Microsoft Azure (New)
  
–set reqURLStr to "https://api.projectoxford.ai/vision/v1.0/analyze" –Microsoft Project Oxford (OLD)
  
set myAPIkey to retAPIkey() of me –API Key 1
  
  
set aRec to {visualFeatures:"Description", details:"Celebrities", |language|:"en"} –age, gender, headPose, smile, facialHair, glasses
  
set bURL to retURLwithParams(reqURLStr, aRec) of me
  
  
set aRes to callRestPOSTAPIAndParseResultsWithImage(bURL, imgFilePath, myAPIkey) of me
  
set aRESTres to json of aRes
  
set aRESCode to responseCode of aRes
  
set aRESHeader to responseHeader of aRes
  
  
return (aRESTres as list)
end recogImage

–POST methodのREST APIを画像をアップロードしつつ呼ぶ
on callRestPOSTAPIAndParseResultsWithImage(aURL, imgFilePath, anAPIkey)
  –Get Image Contents from file
  
set imgPathStr to NSString’s stringWithString:imgFilePath
  
set imgData to NSData’s dataWithContentsOfFile:imgPathStr
  
set postBody to NSMutableData’s |data|()
  
postBody’s appendData:imgData
  
  
–Request
  
set aRequest to NSMutableURLRequest’s requestWithURL:(|NSURL|’s URLWithString:aURL)
  
aRequest’s setHTTPMethod:"POST"
  
aRequest’s setCachePolicy:(NSURLRequestReloadIgnoringLocalCacheData)
  
aRequest’s setHTTPShouldHandleCookies:false
  
aRequest’s setTimeoutInterval:60
  
aRequest’s setHTTPBody:postBody
  
aRequest’s setValue:"application/octet-stream" forHTTPHeaderField:"Content-Type"
  
aRequest’s setValue:anAPIkey forHTTPHeaderField:"Ocp-Apim-Subscription-Key"
  
  
–CALL REST API
  
set aRes to NSURLConnection’s sendSynchronousRequest:aRequest returningResponse:(reference) |error|:(missing value)
  
  
–Parse Results
  
set resList to aRes as list
  
  
set bRes to contents of (first item of resList)
  
set resStr to NSString’s alloc()’s initWithData:bRes encoding:(NSUTF8StringEncoding)
  
  
set jsonString to NSString’s stringWithString:resStr
  
set jsonData to jsonString’s dataUsingEncoding:(NSUTF8StringEncoding)
  
set aJsonDict to NSJSONSerialization’s JSONObjectWithData:jsonData options:0 |error|:(missing value)
  
  
–Get Response Code
  
set dRes to contents of second item of resList
  
if dRes = missing value then
    set resCode to -1
    
set resHeaders to {}
  else
    set resCode to (dRes’s statusCode()) as integer
    
–Get Response Header
    
set resHeaders to (dRes’s allHeaderFields()) as record
  end if
  
  
return {json:aJsonDict, responseCode:resCode, responseHeader:resHeaders}
  
end callRestPOSTAPIAndParseResultsWithImage

on retURLwithParams(aBaseURL, aRec)
  set aDic to NSMutableDictionary’s dictionaryWithDictionary:aRec
  
  
set aKeyList to (aDic’s allKeys()) as list
  
set aValList to (aDic’s allValues()) as list
  
set aLen to length of aKeyList
  
  
set qList to {}
  
repeat with i from 1 to aLen
    set aName to contents of item i of aKeyList
    
set aVal to contents of item i of aValList
    
set the end of qList to (NSURLQueryItem’s queryItemWithName:aName value:aVal)
  end repeat
  
  
set aComp to NSURLComponents’s alloc()’s initWithString:aBaseURL
  
aComp’s setQueryItems:qList
  
set aURL to (aComp’s |URL|()’s absoluteString()) –as text
  
  
return aURL
end retURLwithParams

on retAPIkey()
  return "xxXXXxXXxxXxXXXXxXXxXxXXXXxXxxXX" –API Primary Key
end retAPIkey

★Click Here to Open This Script 

More from my site

  • Wikipedia経由で2つの単語の共通要素を計算するcommon elements Lib Script LibraryWikipedia経由で2つの単語の共通要素を計算するcommon elements Lib Script Library
  • 画面上の指定座標にマウスカーソルを強制移動させてクリック画面上の指定座標にマウスカーソルを強制移動させてクリック
  • checkboxLibをアップデート(3)sdefにサンプルドキュメントを入れるcheckboxLibをアップデート(3)sdefにサンプルドキュメントを入れる
  • checkboxLibをアップデートcheckboxLibをアップデート
  • アイテム番号リストをもとに、ヒットしなかった項目を返すアイテム番号リストをもとに、ヒットしなかった項目を返す
  • メインScript側で宣言したglobal変数値をサブ側で使用するメインScript側で宣言したglobal変数値をサブ側で使用する
(Visited 160 times, 1 visits today)
Posted in Image JSON Network REST API | Tagged 10.11savvy 10.12savvy 10.13savvy | 1 Comment

1 thoughts on “<span>Microsoft Azure Computer Vision API Version 1.0で画像認識(analyze) v2</span>”

  1. 12/10/18
    11:03 PM
    2018年12月10日
    11:03 PM

    Reply

    (POST) Google Translate APIで翻訳 – AppleScriptの穴 says:

    […] だとただ翻訳できるだけで、あまり面白味はありません。本ScriptはMicrosoft Azure Computer Vision APIで画像認識を行なったときに、その画像認識テキストが英文で返ってきており、その内容を日 […]

Leave a Reply to (POST) Google Translate APIで翻訳 – AppleScriptの穴 Cancel reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

電子書籍(PDF)をオンラインストアで販売中!

Google Search

Popular posts

  • macOS 14, Sonoma
  • macOS 13.6.5 AS系のバグ、一切直らず
  • 出るか?「AppleScript最新リファレンス」のバージョン2.8対応版
  • 画像をExcelのワークシート上に配置
  • PowerPoint書類の各スライドのタイトルを取得
  • 指定画像をbase64エンコード文字列に変換→デコード
  • 指定のアプリケーションの実行アーキテクチャを変更
  • macOS 14の変更がmacOS 13にも反映
  • 与えられた文字列の1D Listのすべての順列組み合わせパターン文字列を返す v3(ベンチマーク用)
  • Cocoa-AppleScript Appletランタイムが動かない?
  • Apple純正マウス、キーボードのバッテリー残量取得
  • 当分、macOS 14へのアップデートを見送ります
  • 新刊発売 AppleScript最新リファレンス v2.8対応
  • Finder上で選択中のPDFのページ数を加算
  • macOS 14、英語環境で12時間表記文字と時刻の間に不可視スペースを入れる仕様に
  • Claris FileMaker 2023がリリースされる
  • ディスプレイをスリープ状態にして処理続行
  • HammerspoonでLuaを実行
  • macOS 14, Sonoma 9月27日にリリース
  • CotEditorで2つの書類の行単位での差分検出

Tags

10.11savvy (1101) 10.12savvy (1242) 10.13savvy (1390) 10.14savvy (586) 10.15savvy (434) 11.0savvy (278) 12.0savvy (193) 13.0savvy (87) 14.0savvy (31) CotEditor (62) Finder (48) iTunes (19) Keynote (102) NSAlert (60) NSArray (51) NSBezierPath (18) NSBitmapImageRep (20) NSBundle (20) NSButton (34) NSColor (51) NSDictionary (27) NSFileManager (23) NSFont (18) NSImage (41) NSJSONSerialization (21) NSMutableArray (62) NSMutableDictionary (21) NSPredicate (36) NSRunningApplication (56) NSScreen (30) NSScrollView (22) NSString (117) NSURL (97) NSURLRequest (23) NSUTF8StringEncoding (30) NSView (33) NSWorkspace (20) Numbers (59) Pages (42) Safari (41) Script Editor (22) WKUserContentController (21) WKUserScript (20) WKWebView (23) WKWebViewConfiguration (22)

カテゴリー

  • 2D Bin Packing
  • 3D
  • AirDrop
  • AirPlay
  • Animation
  • AppleScript Application on Xcode
  • Beginner
  • beta
  • Bluetooth
  • Books
  • boolean
  • bounds
  • Bug
  • Calendar
  • call by reference
  • Clipboard
  • Code Sign
  • Color
  • Custom Class
  • dialog
  • diff
  • drive
  • exif
  • file
  • File path
  • filter
  • folder
  • Font
  • Font
  • GAME
  • geolocation
  • GUI
  • GUI Scripting
  • Hex
  • History
  • How To
  • iCloud
  • Icon
  • Image
  • Input Method
  • Internet
  • iOS App
  • JavaScript
  • JSON
  • JXA
  • Keychain
  • Keychain
  • Language
  • Library
  • list
  • Locale
  • Machine Learning
  • Map
  • Markdown
  • Menu
  • Metadata
  • MIDI
  • MIME
  • Natural Language Processing
  • Network
  • news
  • Noification
  • Notarization
  • Number
  • Object control
  • OCR
  • OSA
  • PDF
  • Peripheral
  • PRODUCTS
  • QR Code
  • Raw AppleEvent Code
  • Record
  • rectangle
  • recursive call
  • regexp
  • Release
  • Remote Control
  • Require Control-Command-R to run
  • REST API
  • Review
  • RTF
  • Sandbox
  • Screen Saver
  • Script Libraries
  • sdef
  • search
  • Security
  • selection
  • shell script
  • Shortcuts Workflow
  • Sort
  • Sound
  • Spellchecker
  • Spotlight
  • SVG
  • System
  • Tag
  • Telephony
  • Text
  • Text to Speech
  • timezone
  • Tools
  • Update
  • URL
  • UTI
  • Web Contents Control
  • WiFi
  • XML
  • XML-RPC
  • イベント(Event)
  • 未分類

アーカイブ

  • 2024年5月
  • 2024年4月
  • 2024年3月
  • 2024年2月
  • 2024年1月
  • 2023年12月
  • 2023年11月
  • 2023年10月
  • 2023年9月
  • 2023年8月
  • 2023年7月
  • 2023年6月
  • 2023年5月
  • 2023年4月
  • 2023年3月
  • 2023年2月
  • 2023年1月
  • 2022年12月
  • 2022年11月
  • 2022年10月
  • 2022年9月
  • 2022年8月
  • 2022年7月
  • 2022年6月
  • 2022年5月
  • 2022年4月
  • 2022年3月
  • 2022年2月
  • 2022年1月
  • 2021年12月
  • 2021年11月
  • 2021年10月
  • 2021年9月
  • 2021年8月
  • 2021年7月
  • 2021年6月
  • 2021年5月
  • 2021年4月
  • 2021年3月
  • 2021年2月
  • 2021年1月
  • 2020年12月
  • 2020年11月
  • 2020年10月
  • 2020年9月
  • 2020年8月
  • 2020年7月
  • 2020年6月
  • 2020年5月
  • 2020年4月
  • 2020年3月
  • 2020年2月
  • 2020年1月
  • 2019年12月
  • 2019年11月
  • 2019年10月
  • 2019年9月
  • 2019年8月
  • 2019年7月
  • 2019年6月
  • 2019年5月
  • 2019年4月
  • 2019年3月
  • 2019年2月
  • 2019年1月
  • 2018年12月
  • 2018年11月
  • 2018年10月
  • 2018年9月
  • 2018年8月
  • 2018年7月
  • 2018年6月
  • 2018年5月
  • 2018年4月
  • 2018年3月
  • 2018年2月

https://piyomarusoft.booth.pm/items/301502

メタ情報

  • ログイン
  • 投稿フィード
  • コメントフィード
  • WordPress.org

Forum Posts

  • 人気のトピック
  • 返信がないトピック

メタ情報

  • ログイン
  • 投稿フィード
  • コメントフィード
  • WordPress.org
Proudly powered by WordPress
Theme: Flint by Star Verte LLC