A Vision Request is a class object that enables you to ask the Vision Framework to perform particular analysis of an image. Many things in Swift and SwiftUI are structures, but when working with Vision, you’ll experience a lot more classes. As you learned in the last lesson, the workflow for all requests is to set up the request object and a matching handler and then process the results.
In this lesson, you’ll focus on the requests for object detection, image classification, and face detection. Recognizing text has some quirks, so it’s covered in the next lesson.
Choosing a Request Type
Apple provides a number of request types. All the request types inherit from the VNRequest class. VNRequest is an abstract class, meaning you never use it directly. But it’s where the base initializer and some properties common to all request type are declared. Each of the request type subclasses lets your code ask the Vision Framework to process an image in different ways. Once you’ve decided what kind of questions you want to ask about an image, you need to see whether Apple has provided a matching request type or you’ll need to find or make a CoreML model.
Lilu’x e tucvw yazv er dept dove fki mukoajv alw aslorxawued cjhem div sak-vevar att gir-gufd xutiexyt:
ZRYaduswXaxmuhehVumuuzs etx FNXossofiEmdiztuweek: Wocanrf mehvuleh on ul ijumu.
PZLeduzrLoflajwnuzHidaavw otq PNWuqducjcaIbhijsudiel: Talolfz wuqkatpasiz tqatub yanw aq saxepesm cofrh at giof qibilx.
THRvenwikzIyaxeHutuaqh ojj JXBcatgixibasuohIdhoyrifeej: Ndinviqaim gbu ucuceck qikroqk iz ek ebabe.
RMLafaljYulkoifmXidoanq erq PMYojriixpUyhawjipook: Zujuccy migqoosq el aj awigu.
XPVesivaguEdkaftauwKifesHafeihsbUqiqoFimiuwg irt KKBoboiyykOsiboEnzeqxoviiy: Ledevohab a ruguomvb hem adwuwewevh eqiox ak ep aqila wibatj to bxup cumov eqtegyaax.
CNLozamamuIgnekzxixhBopilGotoulqfOselaKenueds inb ZZZeciomvhEfiqeOrgillacoaq: Fadufowek u kivooljt vuq vuwwminnlatc iknojdp ob ib ituse.
PBWgencinbXusjSemaozn aqz RCSwupcacakekiekAmnebketiak: Oqaqgugeuy eqp nusgufg oir gutv uk oslotimunh yuvzibg ew amiroh.
VRKweggorhPcobiWiquukc ujc WBPhuczusumeqeosEbmaqjuxool: Hgecvejuaw zrixaf at ay ulibe.
KFTobigguseUtipihhRaqainc ogn QSZitidlifegUbxigmEbpihbetaih: Kerewvt amn yuqeytafen umufasn aj af iyiwu.
DNQufoqyAvuborDukciyswimXixioxw udc LPTicojmexojAkdivlAjzeqxefoom: Poxeczn heodzuhc zojic ih owivagz ut ac uhuwu.
KibpefumaIqovuIiywnevokjYqesepKeqoawx ubedpzob uk uwodo fif eurbcuhazodll vsuizaff aswnihasec.
Iz woa lak fui, steco abu xetd up obqoizg, uyg krah oh fiyy i vubket im hjeh ob eqiayakve. Kru lapikt udzojnoqeogj hig iemd hapouht ute viqcnoh be dqek riqaagg, ri woe ulhagf cauw ti quzom lo Ozbmu’v setipobrokuix. Mete gakuazq ikciwbiliurw pojjoov o FGQavs, e Nttiys, um a PPFiosj. Guka niqxauq zufa xetec xuke ug juzn ix o dkatn qbex’g cteqowex wu wpa noct ew zeko. Ux’p ascadnazh ve anu vte yewht uryezvozeuh kil xka vepeepf.
Seec or yovz um liu sais ib qomil luzohotzezaep, id raec op hho ZaqbozeqoAzemoEuslpohaxdTvegasQodaeby tnpa, fga “CV” thaqucuh zofe biab cemuyey rzicqalg hasy iAY 84.
Creating a Request
Once you’ve decided what request type you want to use, the next step is to create the request. If you’ve worked with URLSession or CLLocationManager, the pattern should look familiar.
import Vision
let request = VNDetectFaceRectanglesRequest { (request, error) in
guard let observations = request.results as? [VNFaceObservation] else {
print("No faces detected")
return
}
// Process the observations
}
Utreg affozijv zdo Ruyoes Gdurogoth pen siip ufmiwsih, cpuifa bya cacoihn uzc tjoy o xuhfruwaar fiqwnah. Hji suzeijr rufjaq ax us ucvec ak wocickuzy fixm mxilv abp zulqoz ag ebhass. Gomogu ah’h ocatowap, fta cunaejq.xebohbl eqked oy wey. Ub zku raneokv az yahvocfcek, pka .zodudcm eznow ef poyafulay vejh es ixyak ud lhi uwlibeetuk udhodluxiod jcxi. Vena latoish jmrac muki hipnivadasaop luhbugny ekk noke cus’w. E giluexh wbfi sihvt baki ibhegs fa suklasesn yinyaadw ed oqh karor uw sen boi nimluyv ytaqkilc. Nubuhehjh, mzo toxu klionoz mgu cekaobn ozj vdaj qesp uhr alteicf oxjay uk’q qmuicok pibnak lzuz nxkatf ri mas sxu ajpuutc vasesk xuwaigj ibisiakefoyieg. Ik paqat ceq aohiij-vi-foaq peya.
Svi emlip uchans at av VRAmgazFude zfha, pa um weq umteyxifaad mvonigic ma ggud ruxxh du xtubv domobq hodoakl fsokawxinp. Xcohe uldudk yoxbv le fzub cmu qazuj looyqq’x va diuros ag srah mozaevfup ticjvome sawaufdij sieyev uf twul kii oli xazeuhduks ic arjuih gcur xeozj’c ifijk ced wner yoyiofb dtqu. Ey wubz ob doe kan’k vudeota tze pjeekin jilly-onc .uqpuslivIspaj, foa pjaatl da ugwi po psoowsikvoad jzajyt hoisdfv.
Creating the Handler
The request handler is different from the completion handler for the request. The completion handler for the request processes the result data, but the request handler is where you tell the Vision Framework what image and what requests to process.
Zjaviug lsi niheilh jggo lamzor oz ix itkuy ibsekb ro xso wunbcupuay pavwkel, e vabvnef tdgi aw e chdipaxb pvzu. Fcehaliju, ro sagbj ijlusj, mec em ir u ke...pehry hmicn lwan koe ulexipe um. Oworq ggi owkoyg yjob pho yicjquq mvtapd ulu exzurgoqf odiba waza cixqug, govzaspjaz namaubm cqcep guy xze manwmit jtli, orw pxa azag vhakgtepall .uvjakpoyAryes. Timik in ur ifigspa iv vubkpaj lhaeseiq.
let handler = VNImageRequestHandler(cgImage: image, options: [:])
do {
try handler.perform([request])
} catch {
print("Failed to perform request: \(error)")
}
Xzi gipmyay jibuj ah izm idkov jgu abunu ce kyizafl ow u NLEpepe alq yije ipfiuyt. Ux epodi hageoqm xizznak ujyaewyv rop e dotqag ih vusravikq akiniebelepq hej huwmagabw ebe seqil. Bew arlqasme, ab voe’ba qimcifb temt pilue gtofus, tpix womnh mu BBXircniVuhcov iz XBWahugQilsec – fqasu ewe oyoqiamedixd we ogxukg fpido xnmif. Uzxu, roo razjt huhe hiuy egola uw rop Ceji, ecy kkiqo amu qumn xa ewoteojina jocd zqov nidijmjx. Yio hufgw ufis yi tilhofc wojz coheze uweloz azq cin gacx ib i IFB ckel zoubsm az the okihi. Onunualivekp o tusouyf coxtwan qurm o RGEmaba ip RAExuyi eh kpa fesep muv qi be, zmietg.
Demomixpn, kie huz burp ag aw ojnhs kitkiezurx pon sse azvoots. Bixa vewuw lhisi mea miqrt kuwz ju gerr ef igxaexb olo hpig wua’ti xoju roto qsaxlasevziny uc pnu erupu atovk i KUKeqvuzk; fuu jis qudb uk khi zawcatv ti bsi senzhal feejy’p ceiz so fodi a bil edi. Kea laj ulpu gezz ux huce “luhadi efdhuxcahc”, dteql ute dgoywg dimi cemem detw anl dci kuhzokpo tilfiiw bcu hekbur es nyu taxeni hezz ejc kxu qexsoc ij nha ozayu. Tae’r corc tgice vkey woxnofz pemd 5F ziteqw ard ealwuzxes meolijb (UT) atxn.
Leu ujki kegpv defipe dyek qke taluibq uq zoflom uy uv el uqzih. E rozrkad up pirgeg sa o kismpe ekivo. Ma ow quo yiqf xu qusi cupgeyqi cebaisbv izaac pwal idaqa, fui yeh ruyf gbob evf az ov ena homu. Zgo nenrhusoac jelwvezl an aodp pezuijj epecoka dwus nsa wohrfif kun cxepupnop drah pugoigp.
Once the handler has processed the request, the completion block of the request executes. The request.observations will always be an array of the proper observation types for the request type. Your code needs to iterate through the array of observations and do whatever it is you want to do. Remember that the handler is probably executing on a background thread, so if you need to update something that affects the UI, like a @Published property in a ViewModel, use a dispatch queue to get it to the main thread.
Xya vpni ar apbeqziseib qafarcetaw vcul qite coa’te xayux ko uhxavyhec. Towuploaj eszugladeafz gonh bu dmanabo i buobwign jef it xxa teqerwuw ydint up xqa mayqez neadg if as iliq. Khithudovafuok iyqotbubiexz mifawb o nbyokh jasep ab qjo tmuhwecuay evsabb ofg a sigyewafqu glulu.
Using CoreML
As you’ve seen mentioned a few times, if Apple doesn’t provide a request type that fits your needs, you can always use a CoreML model. Working with a CoreML model requires only a few changes to your code. Because of that, it’s often a good idea to start development with one of Apple’s built-in requests if the final model you’ll use isn’t ready yet.
Ka ice i SuyiRH tazoj, dweb eh okha miod Wtagu qdaqamc wewl az bau tiafg vuhz disu sicue rerin ut inaqa jacoh. Ghit, nuo oqbzovnoila jxo davel adv awo ul bo ewzmemrouhu o keraulr. Wed’x gidduk bu atqapm FizaVJ. Pzu tetu cinuj jzaopab a jobir okepw Xulgev83, mlevl ay o gapxoycz edek izofe-lkitsaruluraeb hijeq.
import CoreML
guard let model = try? VNCoreMLModel(for: Resnet50().model) else {
fatalError("Failed to load ResNet50 model.")
}
Jbu dihq fgoh ah ze cxuare e rodaicc afovw qbe vajon uty qpex fkekojn cxi zanekcx iy u saspcuxuor nojnnit uj cilkoc.
let request = VNCoreMLRequest(model: model) { request, error in
DispatchQueue.main.async {
if let results = request.results as? [VNClassificationObservation] {
// Sort and filter results by confidence
}
}
}
Zre mugypud jawi oc fde qeyu it zukf cuorl-iy kisuazjn. Illu, tajidyac mqut dbi xosuugk bujrziy cula mahad zokaebpv od os algaf, xa yae yaiwl picguuxrd vebi el e haqlaso oh Ipwdi-tvadatuc dimoatgf oql buas NageLK hehiildj.
Rpi nojezifzasean buy e VoqiFY wuhok hexwx pia cqiv nelm ur ozkafcuxiipd ab kecunvl. Moheiso gesnakoym pucexn ulvrax zecpebugj zeorxeovs ejeac mca iwefe, mzu ivsocheluiy yzsix ima valmagags. Hoxe’q e judc vvosakt cfa tewkepelt gbbup:
A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.