functional.py 139 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039
  1. """Functional implementations of geometric image transformations.
  2. This module provides low-level functions for geometric operations such as rotation,
  3. resizing, flipping, perspective transforms, and affine transformations on images,
  4. bounding boxes and keypoints.
  5. """
  6. from __future__ import annotations
  7. import math
  8. from collections import defaultdict
  9. from collections.abc import Mapping, Sequence
  10. from typing import Any, Literal, cast
  11. from warnings import warn
  12. import cv2
  13. import numpy as np
  14. from albucore import (
  15. get_num_channels,
  16. hflip,
  17. maybe_process_in_chunks,
  18. preserve_channel_dim,
  19. vflip,
  20. )
  21. from albumentations.augmentations.utils import angle_2pi_range, handle_empty_array
  22. from albumentations.core.bbox_utils import (
  23. bboxes_from_masks,
  24. bboxes_to_mask,
  25. denormalize_bboxes,
  26. mask_to_bboxes,
  27. masks_from_bboxes,
  28. normalize_bboxes,
  29. )
  30. from albumentations.core.type_definitions import (
  31. NUM_BBOXES_COLUMNS_IN_ALBUMENTATIONS,
  32. NUM_KEYPOINTS_COLUMNS_IN_ALBUMENTATIONS,
  33. NUM_MULTI_CHANNEL_DIMENSIONS,
  34. REFLECT_BORDER_MODES,
  35. )
  36. PAIR = 2
  37. ROT90_180_FACTOR = 2
  38. ROT90_270_FACTOR = 3
  39. @handle_empty_array("bboxes")
  40. def bboxes_rot90(bboxes: np.ndarray, factor: int) -> np.ndarray:
  41. """Rotates bounding boxes by 90 degrees CCW (see np.rot90)
  42. Args:
  43. bboxes (np.ndarray): Array of bounding boxes with shape (num_boxes, 4+)
  44. factor (int): Number of 90-degree rotations (1, 2, or 3)
  45. Returns:
  46. np.ndarray: Rotated bounding boxes
  47. """
  48. if factor == 0:
  49. return bboxes
  50. rotated_bboxes = bboxes.copy()
  51. x_min, y_min, x_max, y_max = bboxes[:, 0], bboxes[:, 1], bboxes[:, 2], bboxes[:, 3]
  52. if factor == 1:
  53. rotated_bboxes[:, 0] = y_min
  54. rotated_bboxes[:, 1] = 1 - x_max
  55. rotated_bboxes[:, 2] = y_max
  56. rotated_bboxes[:, 3] = 1 - x_min
  57. elif factor == ROT90_180_FACTOR:
  58. rotated_bboxes[:, 0] = 1 - x_max
  59. rotated_bboxes[:, 1] = 1 - y_max
  60. rotated_bboxes[:, 2] = 1 - x_min
  61. rotated_bboxes[:, 3] = 1 - y_min
  62. elif factor == ROT90_270_FACTOR:
  63. rotated_bboxes[:, 0] = 1 - y_max
  64. rotated_bboxes[:, 1] = x_min
  65. rotated_bboxes[:, 2] = 1 - y_min
  66. rotated_bboxes[:, 3] = x_max
  67. return rotated_bboxes
  68. @handle_empty_array("bboxes")
  69. def bboxes_d4(
  70. bboxes: np.ndarray,
  71. group_member: Literal["e", "r90", "r180", "r270", "v", "hvt", "h", "t"],
  72. ) -> np.ndarray:
  73. """Applies a `D_4` symmetry group transformation to a bounding box.
  74. The function transforms a bounding box according to the specified group member from the `D_4` group.
  75. These transformations include rotations and reflections, specified to work on an image's bounding box given
  76. its dimensions.
  77. Args:
  78. bboxes (np.ndarray): A numpy array of bounding boxes with shape (num_bboxes, 4+).
  79. Each row represents a bounding box (x_min, y_min, x_max, y_max, ...).
  80. group_member (Literal["e", "r90", "r180", "r270", "v", "hvt", "h", "t"]): A string identifier for the
  81. `D_4` group transformation to apply.
  82. Returns:
  83. BoxInternalType: The transformed bounding box.
  84. Raises:
  85. ValueError: If an invalid group member is specified.
  86. """
  87. transformations = {
  88. "e": lambda x: x, # Identity transformation
  89. "r90": lambda x: bboxes_rot90(x, 1), # Rotate 90 degrees
  90. "r180": lambda x: bboxes_rot90(x, 2), # Rotate 180 degrees
  91. "r270": lambda x: bboxes_rot90(x, 3), # Rotate 270 degrees
  92. "v": lambda x: bboxes_vflip(x), # Vertical flip
  93. "hvt": lambda x: bboxes_transpose(
  94. bboxes_rot90(x, 2),
  95. ), # Reflect over anti-diagonal
  96. "h": lambda x: bboxes_hflip(x), # Horizontal flip
  97. "t": lambda x: bboxes_transpose(x), # Transpose (reflect over main diagonal)
  98. }
  99. # Execute the appropriate transformation
  100. if group_member in transformations:
  101. return transformations[group_member](bboxes)
  102. raise ValueError(f"Invalid group member: {group_member}")
  103. @handle_empty_array("keypoints")
  104. @angle_2pi_range
  105. def keypoints_rot90(
  106. keypoints: np.ndarray,
  107. factor: Literal[0, 1, 2, 3],
  108. image_shape: tuple[int, int],
  109. ) -> np.ndarray:
  110. """Rotate keypoints by 90 degrees counter-clockwise (CCW) a specified number of times.
  111. Args:
  112. keypoints (np.ndarray): An array of keypoints with shape (N, 4+) in the format (x, y, angle, scale, ...).
  113. factor (int): The number of 90 degree CCW rotations to apply. Must be in the range [0, 3].
  114. image_shape (tuple[int, int]): The shape of the image (height, width).
  115. Returns:
  116. np.ndarray: The rotated keypoints with the same shape as the input.
  117. """
  118. if factor == 0:
  119. return keypoints
  120. height, width = image_shape[:2]
  121. rotated_keypoints = keypoints.copy().astype(np.float32)
  122. x, y, angle = keypoints[:, 0], keypoints[:, 1], keypoints[:, 3]
  123. if factor == 1:
  124. rotated_keypoints[:, 0] = y
  125. rotated_keypoints[:, 1] = width - 1 - x
  126. rotated_keypoints[:, 3] = angle - np.pi / 2
  127. elif factor == ROT90_180_FACTOR:
  128. rotated_keypoints[:, 0] = width - 1 - x
  129. rotated_keypoints[:, 1] = height - 1 - y
  130. rotated_keypoints[:, 3] = angle - np.pi
  131. elif factor == ROT90_270_FACTOR:
  132. rotated_keypoints[:, 0] = height - 1 - y
  133. rotated_keypoints[:, 1] = x
  134. rotated_keypoints[:, 3] = angle + np.pi / 2
  135. return rotated_keypoints
  136. @handle_empty_array("keypoints")
  137. def keypoints_d4(
  138. keypoints: np.ndarray,
  139. group_member: Literal["e", "r90", "r180", "r270", "v", "hvt", "h", "t"],
  140. image_shape: tuple[int, int],
  141. **params: Any,
  142. ) -> np.ndarray:
  143. """Applies a `D_4` symmetry group transformation to a keypoint.
  144. This function adjusts a keypoint's coordinates according to the specified `D_4` group transformation,
  145. which includes rotations and reflections suitable for image processing tasks. These transformations account
  146. for the dimensions of the image to ensure the keypoint remains within its boundaries.
  147. Args:
  148. keypoints (np.ndarray): An array of keypoints with shape (N, 4+) in the format (x, y, angle, scale, ...).
  149. group_member (Literal["e", "r90", "r180", "r270", "v", "hvt", "h", "t"]): A string identifier for
  150. the `D_4` group transformation to apply.
  151. Valid values are 'e', 'r90', 'r180', 'r270', 'v', 'hv', 'h', 't'.
  152. image_shape (tuple[int, int]): The shape of the image.
  153. params (Any): Not used.
  154. Returns:
  155. KeypointInternalType: The transformed keypoint.
  156. Raises:
  157. ValueError: If an invalid group member is specified, indicating that the specified transformation
  158. does not exist.
  159. """
  160. rows, cols = image_shape[:2]
  161. transformations = {
  162. "e": lambda x: x, # Identity transformation
  163. "r90": lambda x: keypoints_rot90(x, 1, image_shape), # Rotate 90 degrees
  164. "r180": lambda x: keypoints_rot90(x, 2, image_shape), # Rotate 180 degrees
  165. "r270": lambda x: keypoints_rot90(x, 3, image_shape), # Rotate 270 degrees
  166. "v": lambda x: keypoints_vflip(x, rows), # Vertical flip
  167. "hvt": lambda x: keypoints_transpose(
  168. keypoints_rot90(x, 2, image_shape),
  169. ), # Reflect over anti diagonal
  170. "h": lambda x: keypoints_hflip(x, cols), # Horizontal flip
  171. "t": lambda x: keypoints_transpose(x), # Transpose (reflect over main diagonal)
  172. }
  173. # Execute the appropriate transformation
  174. if group_member in transformations:
  175. return transformations[group_member](keypoints)
  176. raise ValueError(f"Invalid group member: {group_member}")
  177. @preserve_channel_dim
  178. def resize(
  179. img: np.ndarray,
  180. target_shape: tuple[int, int],
  181. interpolation: int,
  182. ) -> np.ndarray:
  183. """Resize an image to the specified dimensions.
  184. This function resizes an input image to the target shape using the specified
  185. interpolation method. If the image is already the target size, it is returned unchanged.
  186. Args:
  187. img (np.ndarray): Input image to resize.
  188. target_shape (tuple[int, int]): Target (height, width) dimensions.
  189. interpolation (int): Interpolation method to use (cv2 interpolation flag).
  190. Examples: cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_NEAREST, etc.
  191. Returns:
  192. np.ndarray: Resized image with shape target_shape + original channel dimensions.
  193. """
  194. if target_shape == img.shape[:2]:
  195. return img
  196. height, width = target_shape[:2]
  197. resize_fn = maybe_process_in_chunks(
  198. cv2.resize,
  199. dsize=(width, height),
  200. interpolation=interpolation,
  201. )
  202. return resize_fn(img)
  203. @preserve_channel_dim
  204. def scale(img: np.ndarray, scale: float, interpolation: int) -> np.ndarray:
  205. """Scale an image by a factor while preserving aspect ratio.
  206. This function scales both height and width dimensions of the image by the same factor.
  207. Args:
  208. img (np.ndarray): Input image to scale.
  209. scale (float): Scale factor. Values > 1 will enlarge the image, values < 1 will shrink it.
  210. interpolation (int): Interpolation method to use (cv2 interpolation flag).
  211. Returns:
  212. np.ndarray: Scaled image.
  213. """
  214. height, width = img.shape[:2]
  215. new_size = int(height * scale), int(width * scale)
  216. return resize(img, new_size, interpolation)
  217. @handle_empty_array("keypoints")
  218. def keypoints_scale(
  219. keypoints: np.ndarray,
  220. scale_x: float,
  221. scale_y: float,
  222. ) -> np.ndarray:
  223. """Scale keypoints by given factors.
  224. Args:
  225. keypoints (np.ndarray): Array of keypoints with shape (num_keypoints, 2+)
  226. scale_x (float): Scale factor for x coordinates
  227. scale_y (float): Scale factor for y coordinates
  228. Returns:
  229. np.ndarray: Scaled keypoints
  230. """
  231. # Extract x, y, z, angle, and scale
  232. x, y, z, angle, scale = (
  233. keypoints[:, 0],
  234. keypoints[:, 1],
  235. keypoints[:, 2],
  236. keypoints[:, 3],
  237. keypoints[:, 4],
  238. )
  239. # Scale x and y
  240. x_scaled = x * scale_x
  241. y_scaled = y * scale_y
  242. # Scale the keypoint scale by the maximum of scale_x and scale_y
  243. scale_scaled = scale * max(scale_x, scale_y)
  244. # Create the output array
  245. scaled_keypoints = np.column_stack([x_scaled, y_scaled, z, angle, scale_scaled])
  246. # If there are additional columns, preserve them
  247. if keypoints.shape[1] > NUM_KEYPOINTS_COLUMNS_IN_ALBUMENTATIONS:
  248. return np.column_stack(
  249. [scaled_keypoints, keypoints[:, NUM_KEYPOINTS_COLUMNS_IN_ALBUMENTATIONS:]],
  250. )
  251. return scaled_keypoints
  252. @preserve_channel_dim
  253. def perspective(
  254. img: np.ndarray,
  255. matrix: np.ndarray,
  256. max_width: int,
  257. max_height: int,
  258. border_val: float | list[float] | np.ndarray,
  259. border_mode: int,
  260. keep_size: bool,
  261. interpolation: int,
  262. ) -> np.ndarray:
  263. """Apply perspective transformation to an image.
  264. This function warps an image according to a perspective transformation matrix.
  265. It can either maintain the original dimensions or use the specified max dimensions.
  266. Args:
  267. img (np.ndarray): Input image to transform.
  268. matrix (np.ndarray): 3x3 perspective transformation matrix.
  269. max_width (int): Maximum width of the output image if keep_size is False.
  270. max_height (int): Maximum height of the output image if keep_size is False.
  271. border_val (float | list[float] | np.ndarray): Border value(s) to fill areas outside the transformed image.
  272. border_mode (int): OpenCV border mode (e.g., cv2.BORDER_CONSTANT, cv2.BORDER_REFLECT).
  273. keep_size (bool): If True, maintain the original image dimensions.
  274. interpolation (int): Interpolation method for resampling (cv2 interpolation flag).
  275. Returns:
  276. np.ndarray: Perspective-transformed image.
  277. """
  278. if not keep_size:
  279. perspective_func = maybe_process_in_chunks(
  280. cv2.warpPerspective,
  281. M=matrix,
  282. dsize=(max_width, max_height),
  283. borderMode=border_mode,
  284. borderValue=border_val,
  285. flags=interpolation,
  286. )
  287. else:
  288. height, width = img.shape[:2]
  289. scale_x = width / max_width
  290. scale_y = height / max_height
  291. scale_matrix = np.array([[scale_x, 0, 0], [0, scale_y, 0], [0, 0, 1]])
  292. adjusted_matrix = np.dot(scale_matrix, matrix)
  293. perspective_func = maybe_process_in_chunks(
  294. cv2.warpPerspective,
  295. M=adjusted_matrix,
  296. dsize=(width, height),
  297. borderMode=border_mode,
  298. borderValue=border_val,
  299. flags=interpolation,
  300. )
  301. return perspective_func(img)
  302. @handle_empty_array("bboxes")
  303. def perspective_bboxes(
  304. bboxes: np.ndarray,
  305. image_shape: tuple[int, int],
  306. matrix: np.ndarray,
  307. max_width: int,
  308. max_height: int,
  309. keep_size: bool,
  310. ) -> np.ndarray:
  311. """Applies perspective transformation to bounding boxes.
  312. This function transforms bounding boxes using the given perspective transformation matrix.
  313. It handles bounding boxes with additional attributes beyond the standard coordinates.
  314. Args:
  315. bboxes (np.ndarray): An array of bounding boxes with shape (num_bboxes, 4+).
  316. Each row represents a bounding box (x_min, y_min, x_max, y_max, ...).
  317. Additional columns beyond the first 4 are preserved unchanged.
  318. image_shape (tuple[int, int]): The shape of the image (height, width).
  319. matrix (np.ndarray): The perspective transformation matrix.
  320. max_width (int): The maximum width of the output image.
  321. max_height (int): The maximum height of the output image.
  322. keep_size (bool): If True, maintains the original image size after transformation.
  323. Returns:
  324. np.ndarray: An array of transformed bounding boxes with the same shape as input.
  325. The first 4 columns contain the transformed coordinates, and any
  326. additional columns are preserved from the input.
  327. Note:
  328. - This function modifies only the coordinate columns (first 4) of the input bounding boxes.
  329. - Any additional attributes (columns beyond the first 4) are kept unchanged.
  330. - The function handles denormalization and renormalization of coordinates internally.
  331. Example:
  332. >>> bboxes = np.array([[0.1, 0.1, 0.3, 0.3, 1], [0.5, 0.5, 0.8, 0.8, 2]])
  333. >>> image_shape = (100, 100)
  334. >>> matrix = np.array([[1.5, 0.2, -20], [-0.1, 1.3, -10], [0.002, 0.001, 1]])
  335. >>> transformed_bboxes = perspective_bboxes(bboxes, image_shape, matrix, 150, 150, False)
  336. """
  337. height, width = image_shape[:2]
  338. transformed_bboxes = bboxes.copy()
  339. denormalized_coords = denormalize_bboxes(bboxes[:, :4], image_shape)
  340. x_min, y_min, x_max, y_max = denormalized_coords.T
  341. points = np.array(
  342. [[x_min, y_min], [x_max, y_min], [x_max, y_max], [x_min, y_max]],
  343. ).transpose(2, 0, 1)
  344. points_reshaped = points.reshape(-1, 1, 2)
  345. transformed_points = cv2.perspectiveTransform(
  346. points_reshaped.astype(np.float32),
  347. matrix,
  348. )
  349. transformed_points = transformed_points.reshape(-1, 4, 2)
  350. new_coords = np.array(
  351. [[np.min(box[:, 0]), np.min(box[:, 1]), np.max(box[:, 0]), np.max(box[:, 1])] for box in transformed_points],
  352. )
  353. if keep_size:
  354. scale_x, scale_y = width / max_width, height / max_height
  355. new_coords[:, [0, 2]] *= scale_x
  356. new_coords[:, [1, 3]] *= scale_y
  357. output_shape = image_shape
  358. else:
  359. output_shape = (max_height, max_width)
  360. normalized_coords = normalize_bboxes(new_coords, output_shape)
  361. transformed_bboxes[:, :4] = normalized_coords
  362. return transformed_bboxes
  363. def rotation2d_matrix_to_euler_angles(matrix: np.ndarray, y_up: bool) -> float:
  364. """Args:
  365. matrix (np.ndarray): Rotation matrix
  366. y_up (bool): is Y axis looks up or down
  367. """
  368. if y_up:
  369. return np.arctan2(matrix[1, 0], matrix[0, 0])
  370. return np.arctan2(-matrix[1, 0], matrix[0, 0])
  371. @handle_empty_array("keypoints")
  372. @angle_2pi_range
  373. def perspective_keypoints(
  374. keypoints: np.ndarray,
  375. image_shape: tuple[int, int],
  376. matrix: np.ndarray,
  377. max_width: int,
  378. max_height: int,
  379. keep_size: bool,
  380. ) -> np.ndarray:
  381. """Apply perspective transformation to keypoints.
  382. Args:
  383. keypoints (np.ndarray): Array of shape (N, 5+) in format [x, y, z, angle, scale, ...]
  384. image_shape (tuple[int, int]): Original image shape (height, width)
  385. matrix (np.ndarray): 3x3 perspective transformation matrix
  386. max_width (int): Maximum width after transformation
  387. max_height (int): Maximum height after transformation
  388. keep_size (bool): Whether to keep original size
  389. Returns:
  390. np.ndarray: Transformed keypoints array with same shape as input
  391. """
  392. keypoints = keypoints.copy().astype(np.float32)
  393. height, width = image_shape[:2]
  394. x, y, z, angle, scale = (
  395. keypoints[:, 0],
  396. keypoints[:, 1],
  397. keypoints[:, 2],
  398. keypoints[:, 3],
  399. keypoints[:, 4],
  400. )
  401. # Reshape keypoints for perspective transform
  402. keypoint_vector = np.column_stack((x, y)).astype(np.float32).reshape(-1, 1, 2)
  403. # Apply perspective transform
  404. transformed_points = cv2.perspectiveTransform(keypoint_vector, matrix).squeeze()
  405. # Unsqueeze if we have a single keypoint
  406. if transformed_points.ndim == 1:
  407. transformed_points = transformed_points[np.newaxis, :]
  408. x, y = transformed_points[:, 0], transformed_points[:, 1]
  409. # Update angles
  410. angle += rotation2d_matrix_to_euler_angles(matrix[:2, :2], y_up=True)
  411. # Calculate scale factors
  412. scale_x = np.sign(matrix[0, 0]) * np.sqrt(matrix[0, 0] ** 2 + matrix[0, 1] ** 2)
  413. scale_y = np.sign(matrix[1, 1]) * np.sqrt(matrix[1, 0] ** 2 + matrix[1, 1] ** 2)
  414. scale *= max(scale_x, scale_y)
  415. if keep_size:
  416. scale_x = width / max_width
  417. scale_y = height / max_height
  418. x *= scale_x
  419. y *= scale_y
  420. scale *= max(scale_x, scale_y)
  421. # Create the output array with unchanged z coordinate
  422. transformed_keypoints = np.column_stack([x, y, z, angle, scale])
  423. # If there are additional columns, preserve them
  424. if keypoints.shape[1] > NUM_KEYPOINTS_COLUMNS_IN_ALBUMENTATIONS:
  425. return np.column_stack(
  426. [
  427. transformed_keypoints,
  428. keypoints[:, NUM_KEYPOINTS_COLUMNS_IN_ALBUMENTATIONS:],
  429. ],
  430. )
  431. return transformed_keypoints
  432. def is_identity_matrix(matrix: np.ndarray) -> bool:
  433. """Check if the given matrix is an identity matrix.
  434. Args:
  435. matrix (np.ndarray): A 3x3 affine transformation matrix.
  436. Returns:
  437. bool: True if the matrix is an identity matrix, False otherwise.
  438. """
  439. return np.allclose(matrix, np.eye(3, dtype=matrix.dtype))
  440. def warp_affine_with_value_extension(
  441. image: np.ndarray,
  442. matrix: np.ndarray,
  443. dsize: tuple[int, int],
  444. flags: int,
  445. border_mode: int,
  446. border_value: tuple[float, ...] | float,
  447. ) -> np.ndarray:
  448. """Warp affine with value extension.
  449. This function warps an image with a given affine transformation matrix.
  450. It also extends the value to a sequence of floats.
  451. Args:
  452. image (np.ndarray): The image to warp.
  453. matrix (np.ndarray): The affine transformation matrix.
  454. dsize (tuple[int, int]): The size of the output image.
  455. flags (int): The flags for the warp.
  456. border_mode (int): The border mode to use.
  457. border_value (tuple[float, ...] | float): The value to pad the image with.
  458. Returns:
  459. np.ndarray: The warped image.
  460. """
  461. num_channels = get_num_channels(image)
  462. extended_value = extend_value(border_value, num_channels)
  463. return cv2.warpAffine(
  464. image,
  465. matrix,
  466. dsize,
  467. flags=flags,
  468. borderMode=border_mode,
  469. borderValue=extended_value,
  470. )
  471. @preserve_channel_dim
  472. def warp_affine(
  473. image: np.ndarray,
  474. matrix: np.ndarray,
  475. interpolation: int,
  476. fill: tuple[float, ...] | float,
  477. border_mode: int,
  478. output_shape: tuple[int, int],
  479. ) -> np.ndarray:
  480. """Apply an affine transformation to an image.
  481. This function transforms an image using the specified affine transformation matrix.
  482. If the transformation matrix is an identity matrix, the original image is returned.
  483. Args:
  484. image (np.ndarray): Input image to transform.
  485. matrix (np.ndarray): 2x3 or 3x3 affine transformation matrix.
  486. interpolation (int): Interpolation method for resampling.
  487. fill (tuple[float, ...] | float): Border value(s) to fill areas outside the transformed image.
  488. border_mode (int): OpenCV border mode for handling pixels outside the image boundaries.
  489. output_shape (tuple[int, int]): Shape (height, width) of the output image.
  490. Returns:
  491. np.ndarray: Affine-transformed image with dimensions specified by output_shape.
  492. """
  493. if is_identity_matrix(matrix):
  494. return image
  495. height = int(np.round(output_shape[0]))
  496. width = int(np.round(output_shape[1]))
  497. cv2_matrix = matrix[:2, :]
  498. warp_fn = maybe_process_in_chunks(
  499. warp_affine_with_value_extension,
  500. matrix=cv2_matrix,
  501. dsize=(width, height),
  502. flags=interpolation,
  503. border_mode=border_mode,
  504. border_value=fill,
  505. )
  506. return warp_fn(image)
  507. @handle_empty_array("keypoints")
  508. @angle_2pi_range
  509. def keypoints_affine(
  510. keypoints: np.ndarray,
  511. matrix: np.ndarray,
  512. image_shape: tuple[int, int],
  513. scale: dict[str, float],
  514. border_mode: int,
  515. ) -> np.ndarray:
  516. """Apply an affine transformation to keypoints.
  517. This function transforms keypoints using the given affine transformation matrix.
  518. It handles reflection padding if necessary, updates coordinates, angles, and scales.
  519. Args:
  520. keypoints (np.ndarray): Array of keypoints with shape (N, 4+) where N is the number of keypoints.
  521. Each keypoint is represented as [x, y, angle, scale, ...].
  522. matrix (np.ndarray): The 2x3 or 3x3 affine transformation matrix.
  523. image_shape (tuple[int, int]): Shape of the image (height, width).
  524. scale (dict[str, float]): Dictionary containing scale factors for x and y directions.
  525. Expected keys are 'x' and 'y'.
  526. border_mode (int): Border mode for handling keypoints near image edges.
  527. Use cv2.BORDER_REFLECT_101, cv2.BORDER_REFLECT, etc.
  528. Returns:
  529. np.ndarray: Transformed keypoints array with the same shape as input.
  530. Notes:
  531. - The function applies reflection padding if the mode is in REFLECT_BORDER_MODES.
  532. - Coordinates (x, y) are transformed using the affine matrix.
  533. - Angles are adjusted based on the rotation component of the affine transformation.
  534. - Scales are multiplied by the maximum of x and y scale factors.
  535. - The @angle_2pi_range decorator ensures angles remain in the [0, 2π] range.
  536. Example:
  537. >>> keypoints = np.array([[100, 100, 0, 1]])
  538. >>> matrix = np.array([[1.5, 0, 10], [0, 1.2, 20]])
  539. >>> scale = {'x': 1.5, 'y': 1.2}
  540. >>> transformed_keypoints = keypoints_affine(keypoints, matrix, (480, 640), scale, cv2.BORDER_REFLECT_101)
  541. """
  542. keypoints = keypoints.copy().astype(np.float32)
  543. if is_identity_matrix(matrix):
  544. return keypoints
  545. if border_mode in REFLECT_BORDER_MODES:
  546. # Step 1: Compute affine transform padding
  547. pad_left, pad_right, pad_top, pad_bottom = calculate_affine_transform_padding(
  548. matrix,
  549. image_shape,
  550. )
  551. grid_dimensions = get_pad_grid_dimensions(
  552. pad_top,
  553. pad_bottom,
  554. pad_left,
  555. pad_right,
  556. image_shape,
  557. )
  558. keypoints = generate_reflected_keypoints(
  559. keypoints,
  560. grid_dimensions,
  561. image_shape,
  562. center_in_origin=True,
  563. )
  564. # Extract x, y coordinates (z is preserved)
  565. xy = keypoints[:, :2]
  566. # Ensure matrix is 2x3
  567. if matrix.shape == (3, 3):
  568. matrix = matrix[:2]
  569. # Transform x, y coordinates
  570. xy_transformed = cv2.transform(xy.reshape(-1, 1, 2), matrix).squeeze()
  571. # Calculate angle adjustment
  572. angle_adjustment = rotation2d_matrix_to_euler_angles(matrix[:2, :2], y_up=False)
  573. # Update angles (now at index 3)
  574. keypoints[:, 3] = keypoints[:, 3] + angle_adjustment
  575. # Update scales (now at index 4)
  576. max_scale = max(scale["x"], scale["y"])
  577. keypoints[:, 4] *= max_scale
  578. # Update x, y coordinates and preserve z
  579. keypoints[:, :2] = xy_transformed
  580. return keypoints
  581. @handle_empty_array("points")
  582. def apply_affine_to_points(points: np.ndarray, matrix: np.ndarray) -> np.ndarray:
  583. """Apply affine transformation to a set of points.
  584. This function handles potential division by zero by replacing zero values
  585. in the homogeneous coordinate with a small epsilon value.
  586. Args:
  587. points (np.ndarray): Array of points with shape (N, 2).
  588. matrix (np.ndarray): 3x3 affine transformation matrix.
  589. Returns:
  590. np.ndarray: Transformed points with shape (N, 2).
  591. """
  592. homogeneous_points = np.column_stack([points, np.ones(points.shape[0])])
  593. transformed_points = homogeneous_points @ matrix.T
  594. # Handle potential division by zero
  595. epsilon = np.finfo(transformed_points.dtype).eps
  596. transformed_points[:, 2] = np.where(
  597. np.abs(transformed_points[:, 2]) < epsilon,
  598. np.sign(transformed_points[:, 2]) * epsilon,
  599. transformed_points[:, 2],
  600. )
  601. return transformed_points[:, :2] / transformed_points[:, 2:]
  602. def calculate_affine_transform_padding(
  603. matrix: np.ndarray,
  604. image_shape: tuple[int, int],
  605. ) -> tuple[int, int, int, int]:
  606. """Calculate the necessary padding for an affine transformation to avoid empty spaces."""
  607. height, width = image_shape[:2]
  608. # Check for identity transform
  609. if is_identity_matrix(matrix):
  610. return (0, 0, 0, 0)
  611. # Original corners
  612. corners = np.array([[0, 0], [width, 0], [width, height], [0, height]])
  613. # Transform corners
  614. transformed_corners = apply_affine_to_points(corners, matrix)
  615. # Ensure transformed_corners is 2D
  616. transformed_corners = transformed_corners.reshape(-1, 2)
  617. # Find box that includes both original and transformed corners
  618. all_corners = np.vstack((corners, transformed_corners))
  619. min_x, min_y = all_corners.min(axis=0)
  620. max_x, max_y = all_corners.max(axis=0)
  621. # Compute the inverse transform
  622. inverse_matrix = np.linalg.inv(matrix)
  623. # Apply inverse transform to all corners of the bounding box
  624. bbox_corners = np.array(
  625. [[min_x, min_y], [max_x, min_y], [max_x, max_y], [min_x, max_y]],
  626. )
  627. inverse_corners = apply_affine_to_points(bbox_corners, inverse_matrix).reshape(
  628. -1,
  629. 2,
  630. )
  631. min_x, min_y = inverse_corners.min(axis=0)
  632. max_x, max_y = inverse_corners.max(axis=0)
  633. pad_left = max(0, math.ceil(0 - min_x))
  634. pad_right = max(0, math.ceil(max_x - width))
  635. pad_top = max(0, math.ceil(0 - min_y))
  636. pad_bottom = max(0, math.ceil(max_y - height))
  637. return pad_left, pad_right, pad_top, pad_bottom
  638. @handle_empty_array("bboxes")
  639. def bboxes_affine_largest_box(bboxes: np.ndarray, matrix: np.ndarray) -> np.ndarray:
  640. """Apply an affine transformation to bounding boxes and return the largest enclosing boxes.
  641. This function transforms each corner of every bounding box using the given affine transformation
  642. matrix, then computes the new bounding boxes that fully enclose the transformed corners.
  643. Args:
  644. bboxes (np.ndarray): An array of bounding boxes with shape (N, 4+) where N is the number of
  645. bounding boxes. Each row should contain [x_min, y_min, x_max, y_max]
  646. followed by any additional attributes (e.g., class labels).
  647. matrix (np.ndarray): The 3x3 affine transformation matrix to apply.
  648. Returns:
  649. np.ndarray: An array of transformed bounding boxes with the same shape as the input.
  650. Each row contains [new_x_min, new_y_min, new_x_max, new_y_max] followed by
  651. any additional attributes from the input bounding boxes.
  652. Note:
  653. - This function assumes that the input bounding boxes are in the format [x_min, y_min, x_max, y_max].
  654. - The resulting bounding boxes are the smallest axis-aligned boxes that completely
  655. enclose the transformed original boxes. They may be larger than the minimal possible
  656. bounding box if the original box becomes rotated.
  657. - Any additional attributes beyond the first 4 coordinates are preserved unchanged.
  658. - This method is called "largest box" because it returns the largest axis-aligned box
  659. that encloses all corners of the transformed bounding box.
  660. Example:
  661. >>> bboxes = np.array([[10, 10, 20, 20, 1], [30, 30, 40, 40, 2]]) # Two boxes with class labels
  662. >>> matrix = np.array([[2, 0, 5], [0, 2, 5], [0, 0, 1]]) # Scale by 2 and translate by (5, 5)
  663. >>> transformed_bboxes = bboxes_affine_largest_box(bboxes, matrix)
  664. >>> print(transformed_bboxes)
  665. [[ 25. 25. 45. 45. 1.]
  666. [ 65. 65. 85. 85. 2.]]
  667. """
  668. # Extract corners of all bboxes
  669. x_min, y_min, x_max, y_max = bboxes[:, 0], bboxes[:, 1], bboxes[:, 2], bboxes[:, 3]
  670. corners = (
  671. np.array([[x_min, y_min], [x_max, y_min], [x_max, y_max], [x_min, y_max]]).transpose(2, 0, 1).reshape(-1, 2)
  672. )
  673. # Transform all corners at once
  674. transformed_corners = apply_affine_to_points(corners, matrix).reshape(-1, 4, 2)
  675. # Compute new bounding boxes
  676. new_x_min = np.min(transformed_corners[:, :, 0], axis=1)
  677. new_x_max = np.max(transformed_corners[:, :, 0], axis=1)
  678. new_y_min = np.min(transformed_corners[:, :, 1], axis=1)
  679. new_y_max = np.max(transformed_corners[:, :, 1], axis=1)
  680. return np.column_stack([new_x_min, new_y_min, new_x_max, new_y_max, bboxes[:, 4:]])
  681. @handle_empty_array("bboxes")
  682. def bboxes_affine_ellipse(bboxes: np.ndarray, matrix: np.ndarray) -> np.ndarray:
  683. """Apply an affine transformation to bounding boxes using an ellipse approximation method.
  684. This function transforms bounding boxes by approximating each box with an ellipse,
  685. transforming points along the ellipse's circumference, and then computing the
  686. new bounding box that encloses the transformed ellipse.
  687. Args:
  688. bboxes (np.ndarray): An array of bounding boxes with shape (N, 4+) where N is the number of
  689. bounding boxes. Each row should contain [x_min, y_min, x_max, y_max]
  690. followed by any additional attributes (e.g., class labels).
  691. matrix (np.ndarray): The 3x3 affine transformation matrix to apply.
  692. Returns:
  693. np.ndarray: An array of transformed bounding boxes with the same shape as the input.
  694. Each row contains [new_x_min, new_y_min, new_x_max, new_y_max] followed by
  695. any additional attributes from the input bounding boxes.
  696. Note:
  697. - This function assumes that the input bounding boxes are in the format [x_min, y_min, x_max, y_max].
  698. - The ellipse approximation method can provide a tighter bounding box compared to the
  699. largest box method, especially for rotations.
  700. - 360 points are used to approximate each ellipse, which provides a good balance between
  701. accuracy and computational efficiency.
  702. - Any additional attributes beyond the first 4 coordinates are preserved unchanged.
  703. - This method may be more suitable for objects that are roughly elliptical in shape.
  704. """
  705. x_min, y_min, x_max, y_max = bboxes[:, 0], bboxes[:, 1], bboxes[:, 2], bboxes[:, 3]
  706. bbox_width = (x_max - x_min) / 2
  707. bbox_height = (y_max - y_min) / 2
  708. center_x = x_min + bbox_width
  709. center_y = y_min + bbox_height
  710. angles = np.arange(0, 360, dtype=np.float32)
  711. cos_angles = np.cos(np.radians(angles))
  712. sin_angles = np.sin(np.radians(angles))
  713. # Generate points for all ellipses at once
  714. x = bbox_width[:, np.newaxis] * sin_angles + center_x[:, np.newaxis]
  715. y = bbox_height[:, np.newaxis] * cos_angles + center_y[:, np.newaxis]
  716. points = np.stack([x, y], axis=-1).reshape(-1, 2)
  717. # Transform all points at once using the helper function
  718. transformed_points = apply_affine_to_points(points, matrix)
  719. transformed_points = transformed_points.reshape(len(bboxes), -1, 2)
  720. # Compute new bounding boxes
  721. new_x_min = np.min(transformed_points[:, :, 0], axis=1)
  722. new_x_max = np.max(transformed_points[:, :, 0], axis=1)
  723. new_y_min = np.min(transformed_points[:, :, 1], axis=1)
  724. new_y_max = np.max(transformed_points[:, :, 1], axis=1)
  725. return np.column_stack([new_x_min, new_y_min, new_x_max, new_y_max, bboxes[:, 4:]])
  726. @handle_empty_array("bboxes")
  727. def bboxes_affine(
  728. bboxes: np.ndarray,
  729. matrix: np.ndarray,
  730. rotate_method: Literal["largest_box", "ellipse"],
  731. image_shape: tuple[int, int],
  732. border_mode: int,
  733. output_shape: tuple[int, int],
  734. ) -> np.ndarray:
  735. """Apply an affine transformation to bounding boxes.
  736. For reflection border modes (cv2.BORDER_REFLECT_101, cv2.BORDER_REFLECT), this function:
  737. 1. Calculates necessary padding to avoid information loss
  738. 2. Applies padding to the bounding boxes
  739. 3. Adjusts the transformation matrix to account for padding
  740. 4. Applies the affine transformation
  741. 5. Validates the transformed bounding boxes
  742. For other border modes, it directly applies the affine transformation without padding.
  743. Args:
  744. bboxes (np.ndarray): Input bounding boxes
  745. matrix (np.ndarray): Affine transformation matrix
  746. rotate_method (str): Method for rotating bounding boxes ('largest_box' or 'ellipse')
  747. image_shape (Sequence[int]): Shape of the input image
  748. border_mode (int): OpenCV border mode
  749. output_shape (Sequence[int]): Shape of the output image
  750. Returns:
  751. np.ndarray: Transformed and normalized bounding boxes
  752. """
  753. if is_identity_matrix(matrix):
  754. return bboxes
  755. bboxes = denormalize_bboxes(bboxes, image_shape)
  756. if border_mode in REFLECT_BORDER_MODES:
  757. # Step 1: Compute affine transform padding
  758. pad_left, pad_right, pad_top, pad_bottom = calculate_affine_transform_padding(
  759. matrix,
  760. image_shape,
  761. )
  762. grid_dimensions = get_pad_grid_dimensions(
  763. pad_top,
  764. pad_bottom,
  765. pad_left,
  766. pad_right,
  767. image_shape,
  768. )
  769. bboxes = generate_reflected_bboxes(
  770. bboxes,
  771. grid_dimensions,
  772. image_shape,
  773. center_in_origin=True,
  774. )
  775. # Apply affine transform
  776. if rotate_method == "largest_box":
  777. transformed_bboxes = bboxes_affine_largest_box(bboxes, matrix)
  778. elif rotate_method == "ellipse":
  779. transformed_bboxes = bboxes_affine_ellipse(bboxes, matrix)
  780. else:
  781. raise ValueError(f"Method {rotate_method} is not a valid rotation method.")
  782. # Validate and normalize bboxes
  783. validated_bboxes = validate_bboxes(transformed_bboxes, output_shape)
  784. return normalize_bboxes(validated_bboxes, output_shape)
  785. def to_distance_maps(
  786. keypoints: np.ndarray,
  787. image_shape: tuple[int, int],
  788. inverted: bool = False,
  789. ) -> np.ndarray:
  790. """Generate a ``(H,W,N)`` array of distance maps for ``N`` keypoints.
  791. The ``n``-th distance map contains at every location ``(y, x)`` the
  792. euclidean distance to the ``n``-th keypoint.
  793. This function can be used as a helper when augmenting keypoints with a
  794. method that only supports the augmentation of images.
  795. Args:
  796. keypoints (np.ndarray): A numpy array of shape (N, 2+) where N is the number of keypoints.
  797. Each row represents a keypoint's (x, y) coordinates.
  798. image_shape (tuple[int, int]): Shape of the image (height, width)
  799. inverted (bool): If ``True``, inverted distance maps are returned where each
  800. distance value d is replaced by ``d/(d+1)``, i.e. the distance
  801. maps have values in the range ``(0.0, 1.0]`` with ``1.0`` denoting
  802. exactly the position of the respective keypoint.
  803. Returns:
  804. np.ndarray: A float32 array of shape (H, W, N) containing ``N`` distance maps for ``N``
  805. keypoints. Each location ``(y, x, n)`` in the array denotes the
  806. euclidean distance at ``(y, x)`` to the ``n``-th keypoint.
  807. If `inverted` is ``True``, the distance ``d`` is replaced
  808. by ``d/(d+1)``. The height and width of the array match the
  809. height and width in ``image_shape``.
  810. """
  811. height, width = image_shape[:2]
  812. if len(keypoints) == 0:
  813. return np.zeros((height, width, 0), dtype=np.float32)
  814. # Create coordinate grids
  815. yy, xx = np.mgrid[:height, :width]
  816. # Convert keypoints to numpy array
  817. keypoints_array = np.array(keypoints)
  818. # Compute distances for all keypoints at once
  819. distances = np.sqrt(
  820. (xx[..., np.newaxis] - keypoints_array[:, 0]) ** 2 + (yy[..., np.newaxis] - keypoints_array[:, 1]) ** 2,
  821. )
  822. if inverted:
  823. return (1 / (distances + 1)).astype(np.float32)
  824. return distances.astype(np.float32)
  825. def validate_if_not_found_coords(
  826. if_not_found_coords: Sequence[int] | dict[str, Any] | None,
  827. ) -> tuple[bool, float, float]:
  828. """Validate and process `if_not_found_coords` parameter."""
  829. if if_not_found_coords is None:
  830. return True, -1, -1
  831. if isinstance(if_not_found_coords, (tuple, list)):
  832. if len(if_not_found_coords) != PAIR:
  833. msg = "Expected tuple/list 'if_not_found_coords' to contain exactly two entries."
  834. raise ValueError(msg)
  835. return False, if_not_found_coords[0], if_not_found_coords[1]
  836. if isinstance(if_not_found_coords, dict):
  837. return False, if_not_found_coords["x"], if_not_found_coords["y"]
  838. msg = "Expected if_not_found_coords to be None, tuple, list, or dict."
  839. raise ValueError(msg)
  840. def find_keypoint(
  841. position: tuple[int, int],
  842. distance_map: np.ndarray,
  843. threshold: float | None,
  844. inverted: bool,
  845. ) -> tuple[float, float] | None:
  846. """Determine if a valid keypoint can be found at the given position."""
  847. y, x = position
  848. value = distance_map[y, x]
  849. if not inverted and threshold is not None and value >= threshold:
  850. return None
  851. if inverted and threshold is not None and value <= threshold:
  852. return None
  853. return float(x), float(y)
  854. def from_distance_maps(
  855. distance_maps: np.ndarray,
  856. inverted: bool,
  857. if_not_found_coords: Sequence[int] | dict[str, Any] | None = None,
  858. threshold: float | None = None,
  859. ) -> np.ndarray:
  860. """Convert distance maps back to keypoints coordinates.
  861. This function is the inverse of `to_distance_maps`. It takes distance maps generated for a set of keypoints
  862. and reconstructs the original keypoint coordinates. The function supports both regular and inverted distance maps,
  863. and can handle cases where keypoints are not found or fall outside a specified threshold.
  864. Args:
  865. distance_maps (np.ndarray): A 3D numpy array of shape (height, width, nb_keypoints) containing
  866. distance maps for each keypoint. Each channel represents the distance map for one keypoint.
  867. inverted (bool): If True, treats the distance maps as inverted (where higher values indicate
  868. closer proximity to keypoints). If False, treats them as regular distance maps (where lower
  869. values indicate closer proximity).
  870. if_not_found_coords (Sequence[int] | dict[str, Any] | None, optional): Coordinates to use for
  871. keypoints that are not found or fall outside the threshold. Can be:
  872. - None: Drop keypoints that are not found.
  873. - Sequence of two integers: Use these as (x, y) coordinates for not found keypoints.
  874. - Dict with 'x' and 'y' keys: Use these values for not found keypoints.
  875. Defaults to None.
  876. threshold (float | None, optional): A threshold value to determine valid keypoints. For inverted
  877. maps, values >= threshold are considered valid. For regular maps, values <= threshold are
  878. considered valid. If None, all keypoints are considered valid. Defaults to None.
  879. Returns:
  880. np.ndarray: A 2D numpy array of shape (nb_keypoints, 2) containing the (x, y) coordinates
  881. of the reconstructed keypoints. If `drop_if_not_found` is True (derived from if_not_found_coords),
  882. the output may have fewer rows than input keypoints.
  883. Raises:
  884. ValueError: If the input `distance_maps` is not a 3D array.
  885. Notes:
  886. - The function uses vectorized operations for improved performance, especially with large numbers of keypoints.
  887. - When `threshold` is None, all keypoints are considered valid, and `if_not_found_coords` is not used.
  888. - The function assumes that the input distance maps are properly normalized and scaled according to the
  889. original image dimensions.
  890. Example:
  891. >>> distance_maps = np.random.rand(100, 100, 3) # 3 keypoints
  892. >>> inverted = True
  893. >>> if_not_found_coords = [0, 0]
  894. >>> threshold = 0.5
  895. >>> keypoints = from_distance_maps(distance_maps, inverted, if_not_found_coords, threshold)
  896. >>> print(keypoints.shape)
  897. (3, 2)
  898. """
  899. if distance_maps.ndim != NUM_MULTI_CHANNEL_DIMENSIONS:
  900. msg = f"Expected three-dimensional input, got {distance_maps.ndim} dimensions and shape {distance_maps.shape}."
  901. raise ValueError(msg)
  902. height, width, nb_keypoints = distance_maps.shape
  903. drop_if_not_found, if_not_found_x, if_not_found_y = validate_if_not_found_coords(
  904. if_not_found_coords,
  905. )
  906. # Find the indices of max/min values for all keypoints at once
  907. if inverted:
  908. hitidx_flat = np.argmax(
  909. distance_maps.reshape(height * width, nb_keypoints),
  910. axis=0,
  911. )
  912. else:
  913. hitidx_flat = np.argmin(
  914. distance_maps.reshape(height * width, nb_keypoints),
  915. axis=0,
  916. )
  917. # Convert flat indices to 2D coordinates
  918. hitidx_y, hitidx_x = np.unravel_index(hitidx_flat, (height, width))
  919. # Create keypoints array
  920. keypoints = np.column_stack((hitidx_x, hitidx_y)).astype(float)
  921. if threshold is not None:
  922. # Check threshold condition
  923. if inverted:
  924. valid_mask = distance_maps[hitidx_y, hitidx_x, np.arange(nb_keypoints)] >= threshold
  925. else:
  926. valid_mask = distance_maps[hitidx_y, hitidx_x, np.arange(nb_keypoints)] <= threshold
  927. if not drop_if_not_found:
  928. # Replace invalid keypoints with if_not_found_coords
  929. keypoints[~valid_mask] = [if_not_found_x, if_not_found_y]
  930. else:
  931. # Keep only valid keypoints
  932. return keypoints[valid_mask]
  933. return keypoints
  934. def d4(img: np.ndarray, group_member: Literal["e", "r90", "r180", "r270", "v", "hvt", "h", "t"]) -> np.ndarray:
  935. """Applies a `D_4` symmetry group transformation to an image array.
  936. This function manipulates an image using transformations such as rotations and flips,
  937. corresponding to the `D_4` dihedral group symmetry operations.
  938. Each transformation is identified by a unique group member code.
  939. Args:
  940. img (np.ndarray): The input image array to transform.
  941. group_member (Literal["e", "r90", "r180", "r270", "v", "hvt", "h", "t"]): A string identifier indicating
  942. the specific transformation to apply. Valid codes include:
  943. - 'e': Identity (no transformation).
  944. - 'r90': Rotate 90 degrees counterclockwise.
  945. - 'r180': Rotate 180 degrees.
  946. - 'r270': Rotate 270 degrees counterclockwise.
  947. - 'v': Vertical flip.
  948. - 'hvt': Transpose over second diagonal
  949. - 'h': Horizontal flip.
  950. - 't': Transpose (reflect over the main diagonal).
  951. Returns:
  952. np.ndarray: The transformed image array.
  953. Raises:
  954. ValueError: If an invalid group member is specified.
  955. """
  956. transformations = {
  957. "e": lambda x: x, # Identity transformation
  958. "r90": lambda x: rot90(x, 1), # Rotate 90 degrees
  959. "r180": lambda x: rot90(x, 2), # Rotate 180 degrees
  960. "r270": lambda x: rot90(x, 3), # Rotate 270 degrees
  961. "v": vflip, # Vertical flip
  962. "hvt": lambda x: transpose(rot90(x, 2)), # Reflect over anti-diagonal
  963. "h": hflip, # Horizontal flip
  964. "t": transpose, # Transpose (reflect over main diagonal)
  965. }
  966. # Execute the appropriate transformation
  967. if group_member in transformations:
  968. return transformations[group_member](img)
  969. raise ValueError(f"Invalid group member: {group_member}")
  970. def transpose(img: np.ndarray) -> np.ndarray:
  971. """Transposes the first two dimensions of an array of any dimensionality.
  972. Retains the order of any additional dimensions.
  973. Args:
  974. img (np.ndarray): Input array.
  975. Returns:
  976. np.ndarray: Transposed array.
  977. """
  978. # Generate the new axes order
  979. new_axes = list(range(img.ndim))
  980. new_axes[0], new_axes[1] = 1, 0 # Swap the first two dimensions
  981. # Transpose the array using the new axes order
  982. return img.transpose(new_axes)
  983. def rot90(img: np.ndarray, factor: Literal[0, 1, 2, 3]) -> np.ndarray:
  984. """Rotate an image 90 degrees counterclockwise.
  985. Args:
  986. img (np.ndarray): The input image to rotate.
  987. factor (Literal[0, 1, 2, 3]): The number of 90-degree rotations to apply.
  988. Returns:
  989. np.ndarray: The rotated image.
  990. """
  991. return np.rot90(img, factor)
  992. @handle_empty_array("bboxes")
  993. def bboxes_vflip(bboxes: np.ndarray) -> np.ndarray:
  994. """Flip bounding boxes vertically.
  995. Args:
  996. bboxes (np.ndarray): Array of bounding boxes with shape (num_boxes, 4+)
  997. Returns:
  998. np.ndarray: Vertically flipped bounding boxes
  999. """
  1000. flipped_bboxes = bboxes.copy()
  1001. flipped_bboxes[:, 1] = 1 - bboxes[:, 3] # new y_min = 1 - y_max
  1002. flipped_bboxes[:, 3] = 1 - bboxes[:, 1] # new y_max = 1 - y_min
  1003. return flipped_bboxes
  1004. @handle_empty_array("bboxes")
  1005. def bboxes_hflip(bboxes: np.ndarray) -> np.ndarray:
  1006. """Flip bounding boxes horizontally.
  1007. Args:
  1008. bboxes (np.ndarray): Array of bounding boxes with shape (num_boxes, 4+)
  1009. Returns:
  1010. np.ndarray: Horizontally flipped bounding boxes
  1011. """
  1012. flipped_bboxes = bboxes.copy()
  1013. flipped_bboxes[:, 0] = 1 - bboxes[:, 2] # new x_min = 1 - x_max
  1014. flipped_bboxes[:, 2] = 1 - bboxes[:, 0] # new x_max = 1 - x_min
  1015. return flipped_bboxes
  1016. @handle_empty_array("bboxes")
  1017. def bboxes_transpose(bboxes: np.ndarray) -> np.ndarray:
  1018. """Transpose bounding boxes along the main diagonal.
  1019. Args:
  1020. bboxes (np.ndarray): Array of bounding boxes with shape (num_boxes, 4+)
  1021. Returns:
  1022. np.ndarray: Transposed bounding boxes
  1023. """
  1024. transposed_bboxes = bboxes.copy()
  1025. transposed_bboxes[:, [0, 1, 2, 3]] = bboxes[:, [1, 0, 3, 2]]
  1026. return transposed_bboxes
  1027. @handle_empty_array("keypoints")
  1028. @angle_2pi_range
  1029. def keypoints_vflip(keypoints: np.ndarray, rows: int) -> np.ndarray:
  1030. """Flip keypoints vertically.
  1031. Args:
  1032. keypoints (np.ndarray): Array of keypoints with shape (num_keypoints, 2+)
  1033. rows (int): Number of rows in the image
  1034. Returns:
  1035. np.ndarray: Vertically flipped keypoints
  1036. """
  1037. flipped_keypoints = keypoints.copy().astype(np.float32)
  1038. # Flip y-coordinates
  1039. flipped_keypoints[:, 1] = (rows - 1) - keypoints[:, 1]
  1040. # Negate angles
  1041. flipped_keypoints[:, 3] = -keypoints[:, 3]
  1042. return flipped_keypoints
  1043. @handle_empty_array("keypoints")
  1044. @angle_2pi_range
  1045. def keypoints_hflip(keypoints: np.ndarray, cols: int) -> np.ndarray:
  1046. """Flip keypoints horizontally.
  1047. Args:
  1048. keypoints (np.ndarray): Array of keypoints with shape (num_keypoints, 2+)
  1049. cols (int): Number of columns in the image
  1050. Returns:
  1051. np.ndarray: Horizontally flipped keypoints
  1052. """
  1053. flipped_keypoints = keypoints.copy().astype(np.float32)
  1054. # Flip x-coordinates
  1055. flipped_keypoints[:, 0] = (cols - 1) - keypoints[:, 0]
  1056. # Adjust angles
  1057. flipped_keypoints[:, 3] = np.pi - keypoints[:, 3]
  1058. return flipped_keypoints
  1059. @handle_empty_array("keypoints")
  1060. @angle_2pi_range
  1061. def keypoints_transpose(keypoints: np.ndarray) -> np.ndarray:
  1062. """Transpose keypoints along the main diagonal.
  1063. Args:
  1064. keypoints (np.ndarray): Array of keypoints with shape (num_keypoints, 2+)
  1065. Returns:
  1066. np.ndarray: Transposed keypoints
  1067. """
  1068. transposed_keypoints = keypoints.copy()
  1069. # Swap x and y coordinates
  1070. transposed_keypoints[:, [0, 1]] = keypoints[:, [1, 0]]
  1071. # Adjust angles to reflect the coordinate swap
  1072. angles = keypoints[:, 3]
  1073. transposed_keypoints[:, 3] = np.where(
  1074. angles <= np.pi,
  1075. np.pi / 2 - angles,
  1076. 3 * np.pi / 2 - angles,
  1077. )
  1078. return transposed_keypoints
  1079. @preserve_channel_dim
  1080. def pad(
  1081. img: np.ndarray,
  1082. min_height: int,
  1083. min_width: int,
  1084. border_mode: int,
  1085. value: tuple[float, ...] | float | None,
  1086. ) -> np.ndarray:
  1087. """Pad an image to ensure minimum dimensions.
  1088. This function adds padding to an image if its dimensions are smaller than
  1089. the specified minimum dimensions. Padding is added evenly on all sides.
  1090. Args:
  1091. img (np.ndarray): Input image to pad.
  1092. min_height (int): Minimum height of the output image.
  1093. min_width (int): Minimum width of the output image.
  1094. border_mode (int): OpenCV border mode for padding.
  1095. value (tuple[float, ...] | float | None): Value(s) to fill the border pixels.
  1096. Returns:
  1097. np.ndarray: Padded image with dimensions at least (min_height, min_width).
  1098. """
  1099. height, width = img.shape[:2]
  1100. if height < min_height:
  1101. h_pad_top = int((min_height - height) / 2.0)
  1102. h_pad_bottom = min_height - height - h_pad_top
  1103. else:
  1104. h_pad_top = 0
  1105. h_pad_bottom = 0
  1106. if width < min_width:
  1107. w_pad_left = int((min_width - width) / 2.0)
  1108. w_pad_right = min_width - width - w_pad_left
  1109. else:
  1110. w_pad_left = 0
  1111. w_pad_right = 0
  1112. img = pad_with_params(
  1113. img,
  1114. h_pad_top,
  1115. h_pad_bottom,
  1116. w_pad_left,
  1117. w_pad_right,
  1118. border_mode,
  1119. value,
  1120. )
  1121. if img.shape[:2] != (max(min_height, height), max(min_width, width)):
  1122. raise RuntimeError(
  1123. f"Invalid result shape. Got: {img.shape[:2]}. Expected: {(max(min_height, height), max(min_width, width))}",
  1124. )
  1125. return img
  1126. def extend_value(value: tuple[float, ...] | float, num_channels: int) -> Sequence[float]:
  1127. """Extend value to a sequence of floats.
  1128. This function extends a value to a sequence of floats.
  1129. It is used to pad an image with a given value.
  1130. Args:
  1131. value (tuple[float, ...] | float): The value to extend.
  1132. num_channels (int): The number of channels in the image.
  1133. Returns:
  1134. Sequence[float]: The extended value.
  1135. """
  1136. return [value] * num_channels if isinstance(value, float) else value
  1137. def copy_make_border_with_value_extension(
  1138. img: np.ndarray,
  1139. top: int,
  1140. bottom: int,
  1141. left: int,
  1142. right: int,
  1143. border_mode: int,
  1144. value: tuple[float, ...] | float,
  1145. ) -> np.ndarray:
  1146. """Copy and make border with value extension.
  1147. This function copies and makes border with value extension.
  1148. It is used to pad an image with a given value.
  1149. Args:
  1150. img (np.ndarray): The image to pad.
  1151. top (int): The amount to pad the top of the image.
  1152. bottom (int): The amount to pad the bottom of the image.
  1153. left (int): The amount to pad the left of the image.
  1154. right (int): The amount to pad the right of the image.
  1155. border_mode (int): The border mode to use.
  1156. value (tuple[float, ...] | float): The value to pad the image with.
  1157. Returns:
  1158. np.ndarray: The padded image.
  1159. """
  1160. # For 0-channel images, return empty array of correct padded size
  1161. if img.size == 0:
  1162. height, width = img.shape[:2]
  1163. return np.zeros(
  1164. (height + top + bottom, width + left + right, 0),
  1165. dtype=img.dtype,
  1166. )
  1167. num_channels = get_num_channels(img)
  1168. extended_value = extend_value(value, num_channels)
  1169. return cv2.copyMakeBorder(
  1170. img,
  1171. top,
  1172. bottom,
  1173. left,
  1174. right,
  1175. borderType=border_mode,
  1176. value=extended_value,
  1177. )
  1178. @preserve_channel_dim
  1179. def pad_with_params(
  1180. img: np.ndarray,
  1181. h_pad_top: int,
  1182. h_pad_bottom: int,
  1183. w_pad_left: int,
  1184. w_pad_right: int,
  1185. border_mode: int,
  1186. value: tuple[float, ...] | float | None,
  1187. ) -> np.ndarray:
  1188. """Pad an image with explicitly defined padding on each side.
  1189. This function adds specified amounts of padding to each side of the image.
  1190. Args:
  1191. img (np.ndarray): Input image to pad.
  1192. h_pad_top (int): Number of pixels to add at the top.
  1193. h_pad_bottom (int): Number of pixels to add at the bottom.
  1194. w_pad_left (int): Number of pixels to add on the left.
  1195. w_pad_right (int): Number of pixels to add on the right.
  1196. border_mode (int): OpenCV border mode for padding.
  1197. value (tuple[float, ...] | float | None): Value(s) to fill the border pixels.
  1198. Returns:
  1199. np.ndarray: Padded image.
  1200. """
  1201. pad_fn = maybe_process_in_chunks(
  1202. copy_make_border_with_value_extension,
  1203. top=h_pad_top,
  1204. bottom=h_pad_bottom,
  1205. left=w_pad_left,
  1206. right=w_pad_right,
  1207. border_mode=border_mode,
  1208. value=value,
  1209. )
  1210. return pad_fn(img)
  1211. def pad_images_with_params(
  1212. images: np.ndarray,
  1213. h_pad_top: int,
  1214. h_pad_bottom: int,
  1215. w_pad_left: int,
  1216. w_pad_right: int,
  1217. border_mode: int,
  1218. value: tuple[float, ...] | float | None,
  1219. ) -> np.ndarray:
  1220. """Pad a batch of images with explicitly defined padding on each side.
  1221. This function adds specified amounts of padding to each side of the image for each
  1222. image in the batch.
  1223. Args:
  1224. images (np.ndarray): Input batch of images to pad.
  1225. h_pad_top (int): Number of pixels to add at the top.
  1226. h_pad_bottom (int): Number of pixels to add at the bottom.
  1227. w_pad_left (int): Number of pixels to add on the left.
  1228. w_pad_right (int): Number of pixels to add on the right.
  1229. border_mode (int): OpenCV border mode for padding.
  1230. value (tuple[float, ...] | float | None): Value(s) to fill the border pixels.
  1231. Returns:
  1232. np.ndarray: Padded batch of images.
  1233. """
  1234. no_channel_dim = images.ndim == 3
  1235. if no_channel_dim:
  1236. images = images[..., np.newaxis]
  1237. cv2np_border_modes = {
  1238. cv2.BORDER_CONSTANT: "constant",
  1239. cv2.BORDER_REPLICATE: "edge",
  1240. cv2.BORDER_REFLECT: "symmetric",
  1241. cv2.BORDER_WRAP: "wrap",
  1242. cv2.BORDER_REFLECT_101: "reflect",
  1243. cv2.BORDER_REFLECT101: "reflect",
  1244. cv2.BORDER_DEFAULT: "reflect", # same as cv2.BORDER_REFLECT_101
  1245. }
  1246. mode = cv2np_border_modes[border_mode]
  1247. pad_width = ((0, 0), (h_pad_top, h_pad_bottom), (w_pad_left, w_pad_right), (0, 0))
  1248. if mode == "constant":
  1249. constant_values = np.array(((0, 0), (value, value), (value, value), (0, 0)), dtype=object)
  1250. kwargs = {"constant_values": constant_values}
  1251. else:
  1252. kwargs = {}
  1253. images = np.pad(images, pad_width=pad_width, mode=mode, **kwargs)
  1254. if no_channel_dim:
  1255. images = images[..., 0]
  1256. return images
  1257. @preserve_channel_dim
  1258. def remap(
  1259. img: np.ndarray,
  1260. map_x: np.ndarray,
  1261. map_y: np.ndarray,
  1262. interpolation: int,
  1263. border_mode: int,
  1264. value: tuple[float, ...] | float | None = None,
  1265. ) -> np.ndarray:
  1266. """Remap an image according to given coordinate maps.
  1267. This function applies a generic geometrical transformation using
  1268. mapping functions that specify the position of each pixel in the output image.
  1269. Args:
  1270. img (np.ndarray): Input image to transform.
  1271. map_x (np.ndarray): Map of x-coordinates with same height and width as the input image.
  1272. map_y (np.ndarray): Map of y-coordinates with same height and width as the input image.
  1273. interpolation (int): Interpolation method for resampling.
  1274. border_mode (int): OpenCV border mode for handling pixels outside the image boundaries.
  1275. value (tuple[float, ...] | float | None, optional): Border value(s) if border_mode is BORDER_CONSTANT.
  1276. Returns:
  1277. np.ndarray: Remapped image with the same shape as the input image.
  1278. """
  1279. # Combine map_x and map_y into a single map array of type CV_32FC2
  1280. map_xy = np.stack([map_x, map_y], axis=-1).astype(np.float32)
  1281. # Create remap function with chunks processing
  1282. remap_func = maybe_process_in_chunks(
  1283. cv2.remap,
  1284. map1=map_xy,
  1285. map2=None,
  1286. interpolation=interpolation,
  1287. borderMode=border_mode,
  1288. borderValue=value,
  1289. )
  1290. # Apply the remapping
  1291. return remap_func(img)
  1292. def remap_keypoints_via_mask(
  1293. keypoints: np.ndarray,
  1294. map_x: np.ndarray,
  1295. map_y: np.ndarray,
  1296. image_shape: tuple[int, int],
  1297. ) -> np.ndarray:
  1298. """Remap keypoints using mask and cv2.remap method."""
  1299. height, width = image_shape[:2]
  1300. # Handle empty keypoints array
  1301. if len(keypoints) == 0:
  1302. return np.zeros((0, 2 if keypoints.size == 0 else keypoints.shape[1]))
  1303. # Create mask where each keypoint has unique index
  1304. kp_mask = np.zeros((height, width), dtype=np.int16)
  1305. for idx, kp in enumerate(keypoints, start=1):
  1306. x, y = round(kp[0]), round(kp[1])
  1307. if 0 <= x < width and 0 <= y < height:
  1308. # Note: cv2.circle takes (x,y) coordinates
  1309. cv2.circle(kp_mask, (x, y), 1, idx, -1)
  1310. # Remap the mask
  1311. transformed_kp_mask = cv2.remap(
  1312. kp_mask,
  1313. map_x.astype(np.float32),
  1314. map_y.astype(np.float32),
  1315. cv2.INTER_NEAREST,
  1316. )
  1317. # Extract transformed keypoints
  1318. new_points = []
  1319. for idx, kp in enumerate(keypoints, start=1):
  1320. # Find points with this index
  1321. points = np.where(transformed_kp_mask == idx)
  1322. if len(points[0]) > 0:
  1323. # Convert back to (x,y) coordinates
  1324. new_points.append(np.concatenate([[points[1][0], points[0][0]], kp[2:]]))
  1325. return np.array(new_points) if new_points else np.zeros((0, keypoints.shape[1]))
  1326. @handle_empty_array("keypoints")
  1327. def remap_keypoints(
  1328. keypoints: np.ndarray,
  1329. map_x: np.ndarray,
  1330. map_y: np.ndarray,
  1331. image_shape: tuple[int, int],
  1332. ) -> np.ndarray:
  1333. """Transform keypoints using coordinate mapping functions.
  1334. This function applies the inverse of the mapping defined by map_x and map_y
  1335. to keypoint coordinates. The inverse mapping is necessary because the mapping
  1336. functions define how pixels move from the source to the destination image,
  1337. while keypoints need to be transformed from the destination back to the source.
  1338. Args:
  1339. keypoints (np.ndarray): Array of keypoints with shape (N, 2+), where
  1340. the first two columns are x and y coordinates.
  1341. map_x (np.ndarray): Map of x-coordinates with shape equal to image_shape.
  1342. map_y (np.ndarray): Map of y-coordinates with shape equal to image_shape.
  1343. image_shape (tuple[int, int]): Shape (height, width) of the original image.
  1344. Returns:
  1345. np.ndarray: Transformed keypoints with the same shape as the input keypoints.
  1346. Returns an empty array if input keypoints is empty.
  1347. """
  1348. height, width = image_shape[:2]
  1349. # Extract x and y coordinates
  1350. x, y = keypoints[:, 0], keypoints[:, 1]
  1351. # Clip coordinates to image boundaries
  1352. x = np.clip(x, 0, width - 1)
  1353. y = np.clip(y, 0, height - 1)
  1354. # Convert to integer indices
  1355. x_idx, y_idx = x.astype(int), y.astype(int)
  1356. inv_map_x, inv_map_y = generate_inverse_distortion_map(map_x, map_y, image_shape[:2])
  1357. # Apply the inverse mapping
  1358. new_x = inv_map_x[y_idx, x_idx]
  1359. new_y = inv_map_y[y_idx, x_idx]
  1360. # Clip the new coordinates to ensure they're within the image bounds
  1361. new_x = np.clip(new_x, 0, width - 1)
  1362. new_y = np.clip(new_y, 0, height - 1)
  1363. # Create the transformed keypoints array
  1364. return np.column_stack([new_x, new_y, keypoints[:, 2:]])
  1365. def generate_inverse_distortion_map(
  1366. map_x: np.ndarray,
  1367. map_y: np.ndarray,
  1368. shape: tuple[int, int],
  1369. ) -> tuple[np.ndarray, np.ndarray]:
  1370. """Generate inverse mapping for strong distortions."""
  1371. h, w = shape
  1372. # Initialize inverse maps
  1373. inv_map_x = np.zeros((h, w), dtype=np.float32)
  1374. inv_map_y = np.zeros((h, w), dtype=np.float32)
  1375. # For each source point, record where it maps to
  1376. for y in range(h):
  1377. for x in range(w):
  1378. # Get destination point
  1379. dst_x = map_x[y, x]
  1380. dst_y = map_y[y, x]
  1381. # If destination is within bounds
  1382. if 0 <= dst_x < w and 0 <= dst_y < h:
  1383. # Get neighborhood coordinates
  1384. dst_x_floor = int(np.floor(dst_x))
  1385. dst_x_ceil = min(dst_x_floor + 1, w - 1)
  1386. dst_y_floor = int(np.floor(dst_y))
  1387. dst_y_ceil = min(dst_y_floor + 1, h - 1)
  1388. # Fill neighborhood
  1389. for ny in range(dst_y_floor, dst_y_ceil + 1):
  1390. for nx in range(dst_x_floor, dst_x_ceil + 1):
  1391. # Only update if empty or closer to pixel center
  1392. if inv_map_x[ny, nx] == 0 or (
  1393. abs(nx - dst_x) + abs(ny - dst_y)
  1394. < abs(nx - inv_map_x[ny, nx]) + abs(ny - inv_map_y[ny, nx])
  1395. ):
  1396. inv_map_x[ny, nx] = x
  1397. inv_map_y[ny, nx] = y
  1398. return inv_map_x, inv_map_y
  1399. @handle_empty_array("bboxes")
  1400. def remap_bboxes(
  1401. bboxes: np.ndarray,
  1402. map_x: np.ndarray,
  1403. map_y: np.ndarray,
  1404. image_shape: tuple[int, int],
  1405. ) -> np.ndarray:
  1406. """Remap bounding boxes using displacement maps."""
  1407. # Convert bboxes to mask
  1408. bbox_masks = bboxes_to_mask(bboxes, image_shape)
  1409. # Ensure maps are float32
  1410. map_x = map_x.astype(np.float32)
  1411. map_y = map_y.astype(np.float32)
  1412. transformed_masks = remap(bbox_masks, map_x, map_y, cv2.INTER_NEAREST, cv2.BORDER_CONSTANT, value=0)
  1413. # Convert masks back to bboxes
  1414. return mask_to_bboxes(transformed_masks, bboxes)
  1415. def generate_displacement_fields(
  1416. image_shape: tuple[int, int],
  1417. alpha: float,
  1418. sigma: float,
  1419. same_dxdy: bool,
  1420. kernel_size: tuple[int, int],
  1421. random_generator: np.random.Generator,
  1422. noise_distribution: Literal["gaussian", "uniform"],
  1423. ) -> tuple[np.ndarray, np.ndarray]:
  1424. """Generate displacement fields for elastic transform.
  1425. This function generates displacement fields for elastic transform based on the provided parameters.
  1426. It generates noise either from a Gaussian or uniform distribution and normalizes it to the range [-1, 1].
  1427. Args:
  1428. image_shape (tuple[int, int]): The shape of the image as (height, width).
  1429. alpha (float): The alpha parameter for the elastic transform.
  1430. sigma (float): The sigma parameter for the elastic transform.
  1431. same_dxdy (bool): Whether to use the same displacement field for both x and y directions.
  1432. kernel_size (tuple[int, int]): The size of the kernel for the elastic transform.
  1433. random_generator (np.random.Generator): The random number generator to use.
  1434. noise_distribution (Literal["gaussian", "uniform"]): The distribution of the noise.
  1435. Returns:
  1436. tuple[np.ndarray, np.ndarray]: A tuple containing:
  1437. - fields: The displacement fields for the elastic transform.
  1438. - output_shape: The output shape of the elastic warp.
  1439. """
  1440. # Pre-allocate memory and generate noise in one step
  1441. if noise_distribution == "gaussian":
  1442. # Generate and normalize in one step, directly as float32
  1443. fields = random_generator.standard_normal(
  1444. (1 if same_dxdy else 2, *image_shape[:2]),
  1445. dtype=np.float32,
  1446. )
  1447. # Normalize inplace
  1448. max_abs = np.abs(fields, out=np.empty_like(fields)).max()
  1449. if max_abs > 1e-6:
  1450. fields /= max_abs
  1451. else: # uniform is already normalized to [-1, 1]
  1452. fields = random_generator.uniform(
  1453. -1,
  1454. 1,
  1455. size=(1 if same_dxdy else 2, *image_shape[:2]),
  1456. ).astype(np.float32)
  1457. # # Apply Gaussian blur if needed using fast OpenCV operations
  1458. # When kernel_size is (0,0) cv2.GaussianBlur uses automatic kernel size. Kernel == (0,0) is NOT a noop.
  1459. # Reshape to 2D array (combining first dimension with height)
  1460. shape = fields.shape
  1461. fields = fields.reshape(-1, shape[-1])
  1462. # Apply blur to all fields at once
  1463. cv2.GaussianBlur(
  1464. fields,
  1465. kernel_size,
  1466. sigma,
  1467. dst=fields,
  1468. borderType=cv2.BORDER_REPLICATE,
  1469. )
  1470. # Restore original shape
  1471. fields = fields.reshape(shape)
  1472. # Scale by alpha inplace
  1473. fields *= alpha
  1474. # Return views of the array to avoid copies
  1475. return (fields[0], fields[0]) if same_dxdy else (fields[0], fields[1])
  1476. @handle_empty_array("bboxes")
  1477. def pad_bboxes(
  1478. bboxes: np.ndarray,
  1479. pad_top: int,
  1480. pad_bottom: int,
  1481. pad_left: int,
  1482. pad_right: int,
  1483. border_mode: int,
  1484. image_shape: tuple[int, int],
  1485. ) -> np.ndarray:
  1486. """Pad bounding boxes by a given amount.
  1487. This function pads bounding boxes by a given amount.
  1488. It handles both reflection and padding.
  1489. Args:
  1490. bboxes (np.ndarray): The bounding boxes to pad.
  1491. pad_top (int): The amount to pad the top of the bounding boxes.
  1492. pad_bottom (int): The amount to pad the bottom of the bounding boxes.
  1493. pad_left (int): The amount to pad the left of the bounding boxes.
  1494. pad_right (int): The amount to pad the right of the bounding boxes.
  1495. border_mode (int): The border mode to use.
  1496. image_shape (tuple[int, int]): The shape of the image as (height, width).
  1497. Returns:
  1498. np.ndarray: The padded bounding boxes.
  1499. """
  1500. if border_mode not in REFLECT_BORDER_MODES:
  1501. shift_vector = np.array([pad_left, pad_top, pad_left, pad_top])
  1502. return shift_bboxes(bboxes, shift_vector)
  1503. grid_dimensions = get_pad_grid_dimensions(
  1504. pad_top,
  1505. pad_bottom,
  1506. pad_left,
  1507. pad_right,
  1508. image_shape,
  1509. )
  1510. bboxes = generate_reflected_bboxes(bboxes, grid_dimensions, image_shape)
  1511. # Calculate the number of grid cells added on each side
  1512. original_row, original_col = grid_dimensions["original_position"]
  1513. image_height, image_width = image_shape[:2]
  1514. # Subtract the offset based on the number of added grid cells
  1515. left_shift = original_col * image_width - pad_left
  1516. top_shift = original_row * image_height - pad_top
  1517. shift_vector = np.array([-left_shift, -top_shift, -left_shift, -top_shift])
  1518. bboxes = shift_bboxes(bboxes, shift_vector)
  1519. new_height = pad_top + pad_bottom + image_height
  1520. new_width = pad_left + pad_right + image_width
  1521. return validate_bboxes(bboxes, (new_height, new_width))
  1522. def validate_bboxes(bboxes: np.ndarray, image_shape: Sequence[int]) -> np.ndarray:
  1523. """Validate bounding boxes and remove invalid ones.
  1524. Args:
  1525. bboxes (np.ndarray): Array of bounding boxes with shape (n, 4) where each row is [x_min, y_min, x_max, y_max].
  1526. image_shape (tuple[int, int]): Shape of the image as (height, width).
  1527. Returns:
  1528. np.ndarray: Array of valid bounding boxes, potentially with fewer boxes than the input.
  1529. Example:
  1530. >>> bboxes = np.array([[10, 20, 30, 40], [-10, -10, 5, 5], [100, 100, 120, 120]])
  1531. >>> valid_bboxes = validate_bboxes(bboxes, (100, 100))
  1532. >>> print(valid_bboxes)
  1533. [[10 20 30 40]]
  1534. """
  1535. rows, cols = image_shape[:2]
  1536. x_min, y_min, x_max, y_max = bboxes[:, 0], bboxes[:, 1], bboxes[:, 2], bboxes[:, 3]
  1537. valid_indices = (x_max > 0) & (y_max > 0) & (x_min < cols) & (y_min < rows)
  1538. return bboxes[valid_indices]
  1539. def shift_bboxes(bboxes: np.ndarray, shift_vector: np.ndarray) -> np.ndarray:
  1540. """Shift bounding boxes by a given vector.
  1541. Args:
  1542. bboxes (np.ndarray): Array of bounding boxes with shape (n, m) where n is the number of bboxes
  1543. and m >= 4. The first 4 columns are [x_min, y_min, x_max, y_max].
  1544. shift_vector (np.ndarray): Vector to shift the bounding boxes by, with shape (4,) for
  1545. [shift_x, shift_y, shift_x, shift_y].
  1546. Returns:
  1547. np.ndarray: Shifted bounding boxes with the same shape as input.
  1548. """
  1549. # Create a copy of the input array to avoid modifying it in-place
  1550. shifted_bboxes = bboxes.copy()
  1551. # Add the shift vector to the first 4 columns
  1552. shifted_bboxes[:, :4] += shift_vector
  1553. return shifted_bboxes
  1554. def get_pad_grid_dimensions(
  1555. pad_top: int,
  1556. pad_bottom: int,
  1557. pad_left: int,
  1558. pad_right: int,
  1559. image_shape: tuple[int, int],
  1560. ) -> dict[str, tuple[int, int]]:
  1561. """Calculate the dimensions of the grid needed for reflection padding and the position of the original image.
  1562. Args:
  1563. pad_top (int): Number of pixels to pad above the image.
  1564. pad_bottom (int): Number of pixels to pad below the image.
  1565. pad_left (int): Number of pixels to pad to the left of the image.
  1566. pad_right (int): Number of pixels to pad to the right of the image.
  1567. image_shape (tuple[int, int]): Shape of the original image as (height, width).
  1568. Returns:
  1569. dict[str, tuple[int, int]]: A dictionary containing:
  1570. - 'grid_shape': A tuple (grid_rows, grid_cols) where:
  1571. - grid_rows (int): Number of times the image needs to be repeated vertically.
  1572. - grid_cols (int): Number of times the image needs to be repeated horizontally.
  1573. - 'original_position': A tuple (original_row, original_col) where:
  1574. - original_row (int): Row index of the original image in the grid.
  1575. - original_col (int): Column index of the original image in the grid.
  1576. """
  1577. rows, cols = image_shape[:2]
  1578. grid_rows = 1 + math.ceil(pad_top / rows) + math.ceil(pad_bottom / rows)
  1579. grid_cols = 1 + math.ceil(pad_left / cols) + math.ceil(pad_right / cols)
  1580. original_row = math.ceil(pad_top / rows)
  1581. original_col = math.ceil(pad_left / cols)
  1582. return {
  1583. "grid_shape": (grid_rows, grid_cols),
  1584. "original_position": (original_row, original_col),
  1585. }
  1586. def generate_reflected_bboxes(
  1587. bboxes: np.ndarray,
  1588. grid_dims: dict[str, tuple[int, int]],
  1589. image_shape: tuple[int, int],
  1590. center_in_origin: bool = False,
  1591. ) -> np.ndarray:
  1592. """Generate reflected bounding boxes for the entire reflection grid.
  1593. Args:
  1594. bboxes (np.ndarray): Original bounding boxes.
  1595. grid_dims (dict[str, tuple[int, int]]): Grid dimensions and original position.
  1596. image_shape (tuple[int, int]): Shape of the original image as (height, width).
  1597. center_in_origin (bool): If True, center the grid at the origin. Default is False.
  1598. Returns:
  1599. np.ndarray: Array of reflected and shifted bounding boxes for the entire grid.
  1600. """
  1601. rows, cols = image_shape[:2]
  1602. grid_rows, grid_cols = grid_dims["grid_shape"]
  1603. original_row, original_col = grid_dims["original_position"]
  1604. # Prepare flipped versions of bboxes
  1605. bboxes_hflipped = flip_bboxes(bboxes, flip_horizontal=True, image_shape=image_shape)
  1606. bboxes_vflipped = flip_bboxes(bboxes, flip_vertical=True, image_shape=image_shape)
  1607. bboxes_hvflipped = flip_bboxes(
  1608. bboxes,
  1609. flip_horizontal=True,
  1610. flip_vertical=True,
  1611. image_shape=image_shape,
  1612. )
  1613. # Shift all versions to the original position
  1614. shift_vector = np.array(
  1615. [
  1616. original_col * cols,
  1617. original_row * rows,
  1618. original_col * cols,
  1619. original_row * rows,
  1620. ],
  1621. )
  1622. bboxes = shift_bboxes(bboxes, shift_vector)
  1623. bboxes_hflipped = shift_bboxes(bboxes_hflipped, shift_vector)
  1624. bboxes_vflipped = shift_bboxes(bboxes_vflipped, shift_vector)
  1625. bboxes_hvflipped = shift_bboxes(bboxes_hvflipped, shift_vector)
  1626. new_bboxes = []
  1627. for grid_row in range(grid_rows):
  1628. for grid_col in range(grid_cols):
  1629. # Determine which version of bboxes to use based on grid position
  1630. if (grid_row - original_row) % 2 == 0 and (grid_col - original_col) % 2 == 0:
  1631. current_bboxes = bboxes
  1632. elif (grid_row - original_row) % 2 == 0:
  1633. current_bboxes = bboxes_hflipped
  1634. elif (grid_col - original_col) % 2 == 0:
  1635. current_bboxes = bboxes_vflipped
  1636. else:
  1637. current_bboxes = bboxes_hvflipped
  1638. # Shift to the current grid cell
  1639. cell_shift = np.array(
  1640. [
  1641. (grid_col - original_col) * cols,
  1642. (grid_row - original_row) * rows,
  1643. (grid_col - original_col) * cols,
  1644. (grid_row - original_row) * rows,
  1645. ],
  1646. )
  1647. shifted_bboxes = shift_bboxes(current_bboxes, cell_shift)
  1648. new_bboxes.append(shifted_bboxes)
  1649. result = np.vstack(new_bboxes)
  1650. return shift_bboxes(result, -shift_vector) if center_in_origin else result
  1651. @handle_empty_array("bboxes")
  1652. def flip_bboxes(
  1653. bboxes: np.ndarray,
  1654. flip_horizontal: bool = False,
  1655. flip_vertical: bool = False,
  1656. image_shape: tuple[int, int] = (0, 0),
  1657. ) -> np.ndarray:
  1658. """Flip bounding boxes horizontally and/or vertically.
  1659. Args:
  1660. bboxes (np.ndarray): Array of bounding boxes with shape (n, m) where each row is
  1661. [x_min, y_min, x_max, y_max, ...].
  1662. flip_horizontal (bool): Whether to flip horizontally.
  1663. flip_vertical (bool): Whether to flip vertically.
  1664. image_shape (tuple[int, int]): Shape of the image as (height, width).
  1665. Returns:
  1666. np.ndarray: Flipped bounding boxes.
  1667. """
  1668. rows, cols = image_shape[:2]
  1669. flipped_bboxes = bboxes.copy()
  1670. if flip_horizontal:
  1671. flipped_bboxes[:, [0, 2]] = cols - flipped_bboxes[:, [2, 0]]
  1672. if flip_vertical:
  1673. flipped_bboxes[:, [1, 3]] = rows - flipped_bboxes[:, [3, 1]]
  1674. return flipped_bboxes
  1675. @preserve_channel_dim
  1676. def distort_image(
  1677. image: np.ndarray,
  1678. generated_mesh: np.ndarray,
  1679. interpolation: int,
  1680. ) -> np.ndarray:
  1681. """Apply perspective distortion to an image based on a generated mesh.
  1682. This function applies a perspective transformation to each cell of the image defined by the
  1683. generated mesh. The distortion is applied using OpenCV's perspective transformation and
  1684. blending techniques.
  1685. Args:
  1686. image (np.ndarray): The input image to be distorted. Can be a 2D grayscale image or a
  1687. 3D color image.
  1688. generated_mesh (np.ndarray): A 2D array where each row represents a quadrilateral cell
  1689. as [x1, y1, x2, y2, dst_x1, dst_y1, dst_x2, dst_y2, dst_x3, dst_y3, dst_x4, dst_y4].
  1690. The first four values define the source rectangle, and the last eight values
  1691. define the destination quadrilateral.
  1692. interpolation (int): Interpolation method to be used in the perspective transformation.
  1693. Should be one of the OpenCV interpolation flags (e.g., cv2.INTER_LINEAR).
  1694. Returns:
  1695. np.ndarray: The distorted image with the same shape and dtype as the input image.
  1696. Note:
  1697. - The function preserves the channel dimension of the input image.
  1698. - Each cell of the generated mesh is transformed independently and then blended into the output image.
  1699. - The distortion is applied using perspective transformation, which allows for more complex
  1700. distortions compared to affine transformations.
  1701. Example:
  1702. >>> image = np.random.randint(0, 255, (100, 100, 3), dtype=np.uint8)
  1703. >>> mesh = np.array([[0, 0, 50, 50, 5, 5, 45, 5, 45, 45, 5, 45]])
  1704. >>> distorted = distort_image(image, mesh, cv2.INTER_LINEAR)
  1705. >>> distorted.shape
  1706. (100, 100, 3)
  1707. """
  1708. distorted_image = np.zeros_like(image)
  1709. for mesh in generated_mesh:
  1710. # Extract source rectangle and destination quadrilateral
  1711. x1, y1, x2, y2 = mesh[:4] # Source rectangle
  1712. dst_quad = mesh[4:].reshape(4, 2) # Destination quadrilateral
  1713. # Convert source rectangle to quadrilateral
  1714. src_quad = np.array(
  1715. [
  1716. [x1, y1], # Top-left
  1717. [x2, y1], # Top-right
  1718. [x2, y2], # Bottom-right
  1719. [x1, y2], # Bottom-left
  1720. ],
  1721. dtype=np.float32,
  1722. )
  1723. # Calculate Perspective transformation matrix
  1724. perspective_mat = cv2.getPerspectiveTransform(src_quad, dst_quad)
  1725. # Apply Perspective transformation
  1726. warped = cv2.warpPerspective(
  1727. image,
  1728. perspective_mat,
  1729. (image.shape[1], image.shape[0]),
  1730. flags=interpolation,
  1731. )
  1732. # Create mask for the transformed region
  1733. mask = np.zeros(image.shape[:2], dtype=np.uint8)
  1734. cv2.fillConvexPoly(mask, np.int32(dst_quad), 255)
  1735. # Copy only the warped quadrilateral area to the output image
  1736. distorted_image = cv2.copyTo(warped, mask, distorted_image)
  1737. return distorted_image
  1738. @handle_empty_array("bboxes")
  1739. def bbox_distort_image(
  1740. bboxes: np.ndarray,
  1741. generated_mesh: np.ndarray,
  1742. image_shape: tuple[int, int],
  1743. ) -> np.ndarray:
  1744. """Distort bounding boxes based on a generated mesh.
  1745. This function applies a perspective transformation to each bounding box based on the provided generated mesh.
  1746. It ensures that the bounding boxes are clipped to the image boundaries after transformation.
  1747. Args:
  1748. bboxes (np.ndarray): The bounding boxes to distort.
  1749. generated_mesh (np.ndarray): The generated mesh to distort the bounding boxes with.
  1750. image_shape (tuple[int, int]): The shape of the image as (height, width).
  1751. Returns:
  1752. np.ndarray: The distorted bounding boxes.
  1753. """
  1754. bboxes = bboxes.copy()
  1755. masks = masks_from_bboxes(bboxes, image_shape)
  1756. transformed_masks = cv2.merge(
  1757. [distort_image(mask, generated_mesh, cv2.INTER_NEAREST) for mask in masks],
  1758. )
  1759. if transformed_masks.ndim == NUM_MULTI_CHANNEL_DIMENSIONS:
  1760. transformed_masks = transformed_masks.transpose(2, 0, 1)
  1761. # Normalize the returned bboxes
  1762. bboxes[:, :4] = bboxes_from_masks(transformed_masks)
  1763. return bboxes
  1764. @handle_empty_array("keypoints")
  1765. def distort_image_keypoints(
  1766. keypoints: np.ndarray,
  1767. generated_mesh: np.ndarray,
  1768. image_shape: tuple[int, int],
  1769. ) -> np.ndarray:
  1770. """Distort keypoints based on a generated mesh.
  1771. This function applies a perspective transformation to each keypoint based on the provided generated mesh.
  1772. It ensures that the keypoints are clipped to the image boundaries after transformation.
  1773. Args:
  1774. keypoints (np.ndarray): The keypoints to distort.
  1775. generated_mesh (np.ndarray): The generated mesh to distort the keypoints with.
  1776. image_shape (tuple[int, int]): The shape of the image as (height, width).
  1777. Returns:
  1778. np.ndarray: The distorted keypoints.
  1779. """
  1780. distorted_keypoints = keypoints.copy()
  1781. height, width = image_shape[:2]
  1782. for mesh in generated_mesh:
  1783. x1, y1, x2, y2 = mesh[:4] # Source rectangle
  1784. dst_quad = mesh[4:].reshape(4, 2) # Destination quadrilateral
  1785. src_quad = np.array(
  1786. [
  1787. [x1, y1], # Top-left
  1788. [x2, y1], # Top-right
  1789. [x2, y2], # Bottom-right
  1790. [x1, y2], # Bottom-left
  1791. ],
  1792. dtype=np.float32,
  1793. )
  1794. perspective_mat = cv2.getPerspectiveTransform(src_quad, dst_quad)
  1795. mask = (keypoints[:, 0] >= x1) & (keypoints[:, 0] < x2) & (keypoints[:, 1] >= y1) & (keypoints[:, 1] < y2)
  1796. cell_keypoints = keypoints[mask]
  1797. if len(cell_keypoints) > 0:
  1798. # Convert to float32 before applying the transformation
  1799. points_float32 = cell_keypoints[:, :2].astype(np.float32).reshape(-1, 1, 2)
  1800. transformed_points = cv2.perspectiveTransform(
  1801. points_float32,
  1802. perspective_mat,
  1803. ).reshape(-1, 2)
  1804. # Update distorted keypoints
  1805. distorted_keypoints[mask, :2] = transformed_points
  1806. # Clip keypoints to image boundaries
  1807. distorted_keypoints[:, 0] = np.clip(
  1808. distorted_keypoints[:, 0],
  1809. 0,
  1810. width - 1,
  1811. out=distorted_keypoints[:, 0],
  1812. )
  1813. distorted_keypoints[:, 1] = np.clip(
  1814. distorted_keypoints[:, 1],
  1815. 0,
  1816. height - 1,
  1817. out=distorted_keypoints[:, 1],
  1818. )
  1819. return distorted_keypoints
  1820. def generate_distorted_grid_polygons(
  1821. dimensions: np.ndarray,
  1822. magnitude: int,
  1823. random_generator: np.random.Generator,
  1824. ) -> np.ndarray:
  1825. """Generate distorted grid polygons based on input dimensions and magnitude.
  1826. This function creates a grid of polygons and applies random distortions to the internal vertices,
  1827. while keeping the boundary vertices fixed. The distortion is applied consistently across shared
  1828. vertices to avoid gaps or overlaps in the resulting grid.
  1829. Args:
  1830. dimensions (np.ndarray): A 3D array of shape (grid_height, grid_width, 4) where each element
  1831. is [x_min, y_min, x_max, y_max] representing the dimensions of a grid cell.
  1832. magnitude (int): Maximum pixel-wise displacement for distortion. The actual displacement
  1833. will be randomly chosen in the range [-magnitude, magnitude].
  1834. random_generator (np.random.Generator): A random number generator.
  1835. Returns:
  1836. np.ndarray: A 2D array of shape (total_cells, 8) where each row represents a distorted polygon
  1837. as [x1, y1, x2, y1, x2, y2, x1, y2]. The total_cells is equal to grid_height * grid_width.
  1838. Note:
  1839. - Only internal grid points are distorted; boundary points remain fixed.
  1840. - The function ensures consistent distortion across shared vertices of adjacent cells.
  1841. - The distortion is applied to the following points of each internal cell:
  1842. * Bottom-right of the cell above and to the left
  1843. * Bottom-left of the cell above
  1844. * Top-right of the cell to the left
  1845. * Top-left of the current cell
  1846. - Each square represents a cell, and the X marks indicate the coordinates where displacement occurs.
  1847. +--+--+--+--+
  1848. | | | | |
  1849. +--X--X--X--+
  1850. | | | | |
  1851. +--X--X--X--+
  1852. | | | | |
  1853. +--X--X--X--+
  1854. | | | | |
  1855. +--+--+--+--+
  1856. - For each X, the coordinates of the left, right, top, and bottom edges
  1857. in the four adjacent cells are displaced.
  1858. Example:
  1859. >>> dimensions = np.array([[[0, 0, 50, 50], [50, 0, 100, 50]],
  1860. ... [[0, 50, 50, 100], [50, 50, 100, 100]]])
  1861. >>> distorted = generate_distorted_grid_polygons(dimensions, magnitude=10)
  1862. >>> distorted.shape
  1863. (4, 8)
  1864. """
  1865. grid_height, grid_width = dimensions.shape[:2]
  1866. total_cells = grid_height * grid_width
  1867. # Initialize polygons
  1868. polygons = np.zeros((total_cells, 8), dtype=np.float32)
  1869. polygons[:, 0:2] = dimensions.reshape(-1, 4)[:, [0, 1]] # x1, y1
  1870. polygons[:, 2:4] = dimensions.reshape(-1, 4)[:, [2, 1]] # x2, y1
  1871. polygons[:, 4:6] = dimensions.reshape(-1, 4)[:, [2, 3]] # x2, y2
  1872. polygons[:, 6:8] = dimensions.reshape(-1, 4)[:, [0, 3]] # x1, y2
  1873. # Generate displacements for internal grid points only
  1874. internal_points_height, internal_points_width = grid_height - 1, grid_width - 1
  1875. displacements = random_generator.integers(
  1876. -magnitude,
  1877. magnitude + 1,
  1878. size=(internal_points_height, internal_points_width, 2),
  1879. ).astype(np.float32)
  1880. # Apply displacements to internal polygon vertices
  1881. for i in range(1, grid_height):
  1882. for j in range(1, grid_width):
  1883. dx, dy = displacements[i - 1, j - 1]
  1884. # Bottom-right of cell (i-1, j-1)
  1885. polygons[(i - 1) * grid_width + (j - 1), 4:6] += [dx, dy]
  1886. # Bottom-left of cell (i-1, j)
  1887. polygons[(i - 1) * grid_width + j, 6:8] += [dx, dy]
  1888. # Top-right of cell (i, j-1)
  1889. polygons[i * grid_width + (j - 1), 2:4] += [dx, dy]
  1890. # Top-left of cell (i, j)
  1891. polygons[i * grid_width + j, 0:2] += [dx, dy]
  1892. return polygons
  1893. @handle_empty_array("keypoints")
  1894. def pad_keypoints(
  1895. keypoints: np.ndarray,
  1896. pad_top: int,
  1897. pad_bottom: int,
  1898. pad_left: int,
  1899. pad_right: int,
  1900. border_mode: int,
  1901. image_shape: tuple[int, int],
  1902. ) -> np.ndarray:
  1903. """Pad keypoints by a given amount.
  1904. This function pads keypoints by a given amount.
  1905. It handles both reflection and padding.
  1906. Args:
  1907. keypoints (np.ndarray): The keypoints to pad.
  1908. pad_top (int): The amount to pad the top of the keypoints.
  1909. pad_bottom (int): The amount to pad the bottom of the keypoints.
  1910. pad_left (int): The amount to pad the left of the keypoints.
  1911. pad_right (int): The amount to pad the right of the keypoints.
  1912. border_mode (int): The border mode to use.
  1913. image_shape (tuple[int, int]): The shape of the image as (height, width).
  1914. Returns:
  1915. np.ndarray: The padded keypoints.
  1916. """
  1917. if border_mode not in REFLECT_BORDER_MODES:
  1918. shift_vector = np.array([pad_left, pad_top, 0])
  1919. return shift_keypoints(keypoints, shift_vector)
  1920. grid_dimensions = get_pad_grid_dimensions(
  1921. pad_top,
  1922. pad_bottom,
  1923. pad_left,
  1924. pad_right,
  1925. image_shape,
  1926. )
  1927. keypoints = generate_reflected_keypoints(keypoints, grid_dimensions, image_shape)
  1928. rows, cols = image_shape[:2]
  1929. # Calculate the number of grid cells added on each side
  1930. original_row, original_col = grid_dimensions["original_position"]
  1931. # Subtract the offset based on the number of added grid cells
  1932. keypoints[:, 0] -= original_col * cols - pad_left # x
  1933. keypoints[:, 1] -= original_row * rows - pad_top # y
  1934. new_height = pad_top + pad_bottom + rows
  1935. new_width = pad_left + pad_right + cols
  1936. return validate_keypoints(keypoints, (new_height, new_width))
  1937. def validate_keypoints(
  1938. keypoints: np.ndarray,
  1939. image_shape: tuple[int, int],
  1940. ) -> np.ndarray:
  1941. """Validate keypoints and remove those that fall outside the image boundaries.
  1942. Args:
  1943. keypoints (np.ndarray): Array of keypoints with shape (N, M) where N is the number of keypoints
  1944. and M >= 2. The first two columns represent x and y coordinates.
  1945. image_shape (tuple[int, int]): Shape of the image as (height, width).
  1946. Returns:
  1947. np.ndarray: Array of valid keypoints that fall within the image boundaries.
  1948. Note:
  1949. This function only checks the x and y coordinates (first two columns) of the keypoints.
  1950. Any additional columns (e.g., angle, scale) are preserved for valid keypoints.
  1951. """
  1952. rows, cols = image_shape[:2]
  1953. x, y = keypoints[:, 0], keypoints[:, 1]
  1954. valid_indices = (x >= 0) & (x < cols) & (y >= 0) & (y < rows)
  1955. return keypoints[valid_indices]
  1956. def shift_keypoints(keypoints: np.ndarray, shift_vector: np.ndarray) -> np.ndarray:
  1957. """Shift keypoints by a given shift vector.
  1958. This function shifts the keypoints by a given shift vector.
  1959. It only shifts the x, y and z coordinates of the keypoints.
  1960. Args:
  1961. keypoints (np.ndarray): The keypoints to shift.
  1962. shift_vector (np.ndarray): The shift vector to apply to the keypoints.
  1963. Returns:
  1964. np.ndarray: The shifted keypoints.
  1965. """
  1966. shifted_keypoints = keypoints.copy()
  1967. shifted_keypoints[:, :3] += shift_vector[:3] # Only shift x, y and z
  1968. return shifted_keypoints
  1969. def generate_reflected_keypoints(
  1970. keypoints: np.ndarray,
  1971. grid_dims: dict[str, tuple[int, int]],
  1972. image_shape: tuple[int, int],
  1973. center_in_origin: bool = False,
  1974. ) -> np.ndarray:
  1975. """Generate reflected keypoints for the entire reflection grid.
  1976. This function creates a grid of keypoints by reflecting and shifting the original keypoints.
  1977. It handles both centered and non-centered grids based on the `center_in_origin` parameter.
  1978. Args:
  1979. keypoints (np.ndarray): Original keypoints array of shape (N, 4+), where N is the number of keypoints,
  1980. and each keypoint is represented by at least 4 values (x, y, angle, scale, ...).
  1981. grid_dims (dict[str, tuple[int, int]]): A dictionary containing grid dimensions and original position.
  1982. It should have the following keys:
  1983. - "grid_shape": tuple[int, int] representing (grid_rows, grid_cols)
  1984. - "original_position": tuple[int, int] representing (original_row, original_col)
  1985. image_shape (tuple[int, int]): Shape of the original image as (height, width).
  1986. center_in_origin (bool, optional): If True, center the grid at the origin. Default is False.
  1987. Returns:
  1988. np.ndarray: Array of reflected and shifted keypoints for the entire grid. The shape is
  1989. (N * grid_rows * grid_cols, 4+), where N is the number of original keypoints.
  1990. Note:
  1991. - The function handles keypoint flipping and shifting to create a grid of reflected keypoints.
  1992. - It preserves the angle and scale information of the keypoints during transformations.
  1993. - The resulting grid can be either centered at the origin or positioned based on the original grid.
  1994. """
  1995. grid_rows, grid_cols = grid_dims["grid_shape"]
  1996. original_row, original_col = grid_dims["original_position"]
  1997. # Prepare flipped versions of keypoints
  1998. keypoints_hflipped = flip_keypoints(
  1999. keypoints,
  2000. flip_horizontal=True,
  2001. image_shape=image_shape,
  2002. )
  2003. keypoints_vflipped = flip_keypoints(
  2004. keypoints,
  2005. flip_vertical=True,
  2006. image_shape=image_shape,
  2007. )
  2008. keypoints_hvflipped = flip_keypoints(
  2009. keypoints,
  2010. flip_horizontal=True,
  2011. flip_vertical=True,
  2012. image_shape=image_shape,
  2013. )
  2014. rows, cols = image_shape[:2]
  2015. # Shift all versions to the original position
  2016. shift_vector = np.array(
  2017. [original_col * cols, original_row * rows, 0, 0, 0],
  2018. ) # Only shift x and y
  2019. keypoints = shift_keypoints(keypoints, shift_vector)
  2020. keypoints_hflipped = shift_keypoints(keypoints_hflipped, shift_vector)
  2021. keypoints_vflipped = shift_keypoints(keypoints_vflipped, shift_vector)
  2022. keypoints_hvflipped = shift_keypoints(keypoints_hvflipped, shift_vector)
  2023. new_keypoints = []
  2024. for grid_row in range(grid_rows):
  2025. for grid_col in range(grid_cols):
  2026. # Determine which version of keypoints to use based on grid position
  2027. if (grid_row - original_row) % 2 == 0 and (grid_col - original_col) % 2 == 0:
  2028. current_keypoints = keypoints
  2029. elif (grid_row - original_row) % 2 == 0:
  2030. current_keypoints = keypoints_hflipped
  2031. elif (grid_col - original_col) % 2 == 0:
  2032. current_keypoints = keypoints_vflipped
  2033. else:
  2034. current_keypoints = keypoints_hvflipped
  2035. # Shift to the current grid cell
  2036. cell_shift = np.array(
  2037. [
  2038. (grid_col - original_col) * cols,
  2039. (grid_row - original_row) * rows,
  2040. 0,
  2041. 0,
  2042. 0,
  2043. ],
  2044. )
  2045. shifted_keypoints = shift_keypoints(current_keypoints, cell_shift)
  2046. new_keypoints.append(shifted_keypoints)
  2047. result = np.vstack(new_keypoints)
  2048. return shift_keypoints(result, -shift_vector) if center_in_origin else result
  2049. @handle_empty_array("keypoints")
  2050. def flip_keypoints(
  2051. keypoints: np.ndarray,
  2052. flip_horizontal: bool = False,
  2053. flip_vertical: bool = False,
  2054. image_shape: tuple[int, int] = (0, 0),
  2055. ) -> np.ndarray:
  2056. """Flip keypoints horizontally or vertically.
  2057. This function flips keypoints horizontally or vertically based on the provided parameters.
  2058. It also flips the angle of the keypoints when flipping horizontally.
  2059. Args:
  2060. keypoints (np.ndarray): The keypoints to flip.
  2061. flip_horizontal (bool): Whether to flip horizontally.
  2062. flip_vertical (bool): Whether to flip vertically.
  2063. image_shape (tuple[int, int]): The shape of the image as (height, width).
  2064. Returns:
  2065. np.ndarray: The flipped keypoints.
  2066. """
  2067. rows, cols = image_shape[:2]
  2068. flipped_keypoints = keypoints.copy()
  2069. if flip_horizontal:
  2070. flipped_keypoints[:, 0] = cols - flipped_keypoints[:, 0]
  2071. flipped_keypoints[:, 3] = -flipped_keypoints[:, 3] # Flip angle
  2072. if flip_vertical:
  2073. flipped_keypoints[:, 1] = rows - flipped_keypoints[:, 1]
  2074. flipped_keypoints[:, 3] = -flipped_keypoints[:, 3] # Flip angle
  2075. return flipped_keypoints
  2076. def create_affine_transformation_matrix(
  2077. translate: Mapping[str, float],
  2078. shear: dict[str, float],
  2079. scale: dict[str, float],
  2080. rotate: float,
  2081. shift: tuple[float, float],
  2082. ) -> np.ndarray:
  2083. """Create an affine transformation matrix combining translation, shear, scale, and rotation.
  2084. Args:
  2085. translate (dict[str, float]): Translation in x and y directions.
  2086. shear (dict[str, float]): Shear in x and y directions (in degrees).
  2087. scale (dict[str, float]): Scale factors for x and y directions.
  2088. rotate (float): Rotation angle in degrees.
  2089. shift (tuple[float, float]): Shift to apply before and after transformations.
  2090. Returns:
  2091. np.ndarray: The resulting 3x3 affine transformation matrix.
  2092. """
  2093. # Convert angles to radians
  2094. rotate_rad = np.deg2rad(rotate % 360)
  2095. shear_x_rad = np.deg2rad(shear["x"])
  2096. shear_y_rad = np.deg2rad(shear["y"])
  2097. # Create individual transformation matrices
  2098. # 1. Shift to top-left
  2099. m_shift_topleft = np.array([[1, 0, -shift[0]], [0, 1, -shift[1]], [0, 0, 1]])
  2100. # 2. Scale
  2101. m_scale = np.array([[scale["x"], 0, 0], [0, scale["y"], 0], [0, 0, 1]])
  2102. # 3. Rotation
  2103. m_rotate = np.array(
  2104. [
  2105. [np.cos(rotate_rad), np.sin(rotate_rad), 0],
  2106. [-np.sin(rotate_rad), np.cos(rotate_rad), 0],
  2107. [0, 0, 1],
  2108. ],
  2109. )
  2110. # 4. Shear
  2111. m_shear = np.array(
  2112. [[1, np.tan(shear_x_rad), 0], [np.tan(shear_y_rad), 1, 0], [0, 0, 1]],
  2113. )
  2114. # 5. Translation
  2115. m_translate = np.array([[1, 0, translate["x"]], [0, 1, translate["y"]], [0, 0, 1]])
  2116. # 6. Shift back to center
  2117. m_shift_center = np.array([[1, 0, shift[0]], [0, 1, shift[1]], [0, 0, 1]])
  2118. # Combine all transformations
  2119. # The order is important: transformations are applied from right to left
  2120. m = m_shift_center @ m_translate @ m_shear @ m_rotate @ m_scale @ m_shift_topleft
  2121. # Ensure the last row is exactly [0, 0, 1]
  2122. m[2] = [0, 0, 1]
  2123. return m
  2124. def compute_transformed_image_bounds(
  2125. matrix: np.ndarray,
  2126. image_shape: tuple[int, int],
  2127. ) -> tuple[np.ndarray, np.ndarray]:
  2128. """Compute the bounds of an image after applying an affine transformation.
  2129. Args:
  2130. matrix (np.ndarray): The 3x3 affine transformation matrix.
  2131. image_shape (Tuple[int, int]): The shape of the image as (height, width).
  2132. Returns:
  2133. tuple[np.ndarray, np.ndarray]: A tuple containing:
  2134. - min_coords: An array with the minimum x and y coordinates.
  2135. - max_coords: An array with the maximum x and y coordinates.
  2136. """
  2137. height, width = image_shape[:2]
  2138. # Define the corners of the image
  2139. corners = np.array([[0, 0, 1], [width, 0, 1], [width, height, 1], [0, height, 1]])
  2140. # Transform the corners
  2141. transformed_corners = corners @ matrix.T
  2142. transformed_corners = transformed_corners[:, :2] / transformed_corners[:, 2:]
  2143. # Calculate the bounding box of the transformed corners
  2144. min_coords = np.floor(transformed_corners.min(axis=0)).astype(int)
  2145. max_coords = np.ceil(transformed_corners.max(axis=0)).astype(int)
  2146. return min_coords, max_coords
  2147. def compute_affine_warp_output_shape(
  2148. matrix: np.ndarray,
  2149. input_shape: tuple[int, ...],
  2150. ) -> tuple[np.ndarray, tuple[int, int]]:
  2151. """Compute the output shape of an affine warp.
  2152. This function computes the output shape of an affine warp based on the input matrix and input shape.
  2153. It calculates the transformed image bounds and then determines the output shape based on the input shape.
  2154. Args:
  2155. matrix (np.ndarray): The 3x3 affine transformation matrix.
  2156. input_shape (tuple[int, ...]): The shape of the input image as (height, width, ...).
  2157. Returns:
  2158. tuple[np.ndarray, tuple[int, int]]: A tuple containing:
  2159. - matrix: The 3x3 affine transformation matrix.
  2160. - output_shape: The output shape of the affine warp.
  2161. """
  2162. height, width = input_shape[:2]
  2163. if height == 0 or width == 0:
  2164. return matrix, cast("tuple[int, int]", input_shape[:2])
  2165. min_coords, max_coords = compute_transformed_image_bounds(matrix, (height, width))
  2166. minc, minr = min_coords
  2167. maxc, maxr = max_coords
  2168. out_height = maxr - minr + 1
  2169. out_width = maxc - minc + 1
  2170. if len(input_shape) == NUM_MULTI_CHANNEL_DIMENSIONS:
  2171. output_shape = np.ceil((out_height, out_width, input_shape[2]))
  2172. else:
  2173. output_shape = np.ceil((out_height, out_width))
  2174. output_shape_tuple = tuple(int(v) for v in output_shape.tolist())
  2175. # fit output image in new shape
  2176. translation = np.array([[1, 0, -minc], [0, 1, -minr], [0, 0, 1]])
  2177. matrix = translation @ matrix
  2178. return matrix, cast("tuple[int, int]", output_shape_tuple)
  2179. def center(image_shape: tuple[int, int]) -> tuple[float, float]:
  2180. """Calculate the center coordinates if image. Used by images, masks and keypoints.
  2181. Args:
  2182. image_shape (tuple[int, int]): The shape of the image.
  2183. Returns:
  2184. tuple[float, float]: center_x, center_y
  2185. """
  2186. height, width = image_shape[:2]
  2187. return width / 2 - 0.5, height / 2 - 0.5
  2188. def center_bbox(image_shape: tuple[int, int]) -> tuple[float, float]:
  2189. """Calculate the center coordinates for of image for bounding boxes.
  2190. Args:
  2191. image_shape (tuple[int, int]): The shape of the image.
  2192. Returns:
  2193. tuple[float, float]: center_x, center_y
  2194. """
  2195. height, width = image_shape[:2]
  2196. return width / 2, height / 2
  2197. def generate_grid(
  2198. image_shape: tuple[int, int],
  2199. steps_x: list[float],
  2200. steps_y: list[float],
  2201. num_steps: int,
  2202. ) -> tuple[np.ndarray, np.ndarray]:
  2203. """Generate a distorted grid for image transformation based on given step sizes.
  2204. This function creates two 2D arrays (map_x and map_y) that represent a distorted version
  2205. of the original image grid. These arrays can be used with OpenCV's remap function to
  2206. apply grid distortion to an image.
  2207. Args:
  2208. image_shape (tuple[int, int]): The shape of the image as (height, width).
  2209. steps_x (list[float]): List of step sizes for the x-axis distortion. The length
  2210. should be num_steps + 1. Each value represents the relative step size for
  2211. a segment of the grid in the x direction.
  2212. steps_y (list[float]): List of step sizes for the y-axis distortion. The length
  2213. should be num_steps + 1. Each value represents the relative step size for
  2214. a segment of the grid in the y direction.
  2215. num_steps (int): The number of steps to divide each axis into. This determines
  2216. the granularity of the distortion grid.
  2217. Returns:
  2218. tuple[np.ndarray, np.ndarray]: A tuple containing two 2D numpy arrays:
  2219. - map_x: A 2D array of float32 values representing the x-coordinates
  2220. of the distorted grid.
  2221. - map_y: A 2D array of float32 values representing the y-coordinates
  2222. of the distorted grid.
  2223. Note:
  2224. - The function generates a grid where each cell can be distorted independently.
  2225. - The distortion is controlled by the steps_x and steps_y parameters, which
  2226. determine how much each grid line is shifted.
  2227. - The resulting map_x and map_y can be used directly with cv2.remap() to
  2228. apply the distortion to an image.
  2229. - The distortion is applied smoothly across each grid cell using linear
  2230. interpolation.
  2231. Example:
  2232. >>> image_shape = (100, 100)
  2233. >>> steps_x = [1.1, 0.9, 1.0, 1.2, 0.95, 1.05]
  2234. >>> steps_y = [0.9, 1.1, 1.0, 1.1, 0.9, 1.0]
  2235. >>> num_steps = 5
  2236. >>> map_x, map_y = generate_grid(image_shape, steps_x, steps_y, num_steps)
  2237. >>> distorted_image = cv2.remap(image, map_x, map_y, cv2.INTER_LINEAR)
  2238. """
  2239. height, width = image_shape[:2]
  2240. x_step = width // num_steps
  2241. xx = np.zeros(width, np.float32)
  2242. prev = 0.0
  2243. for idx, step in enumerate(steps_x):
  2244. x = idx * x_step
  2245. start = int(x)
  2246. end = min(int(x) + x_step, width)
  2247. cur = prev + x_step * step
  2248. xx[start:end] = np.linspace(prev, cur, end - start)
  2249. prev = cur
  2250. y_step = height // num_steps
  2251. yy = np.zeros(height, np.float32)
  2252. prev = 0.0
  2253. for idx, step in enumerate(steps_y):
  2254. y = idx * y_step
  2255. start = int(y)
  2256. end = min(int(y) + y_step, height)
  2257. cur = prev + y_step * step
  2258. yy[start:end] = np.linspace(prev, cur, end - start)
  2259. prev = cur
  2260. return np.meshgrid(xx, yy)
  2261. def normalize_grid_distortion_steps(
  2262. image_shape: tuple[int, int],
  2263. num_steps: int,
  2264. x_steps: list[float],
  2265. y_steps: list[float],
  2266. ) -> dict[str, np.ndarray]:
  2267. """Normalize the grid distortion steps.
  2268. This function normalizes the grid distortion steps, ensuring that the distortion never leaves the image bounds.
  2269. It compensates for smaller last steps in the source image and normalizes the steps such that the distortion
  2270. never leaves the image bounds.
  2271. Args:
  2272. image_shape (tuple[int, int]): The shape of the image as (height, width).
  2273. num_steps (int): The number of steps to divide each axis into. This determines
  2274. the granularity of the distortion grid.
  2275. x_steps (list[float]): List of step sizes for the x-axis distortion. The length
  2276. should be num_steps + 1. Each value represents the relative step size for
  2277. a segment of the grid in the x direction.
  2278. y_steps (list[float]): List of step sizes for the y-axis distortion. The length
  2279. should be num_steps + 1. Each value represents the relative step size for
  2280. a segment of the grid in the y direction.
  2281. Returns:
  2282. dict[str, np.ndarray]: A dictionary containing the normalized step sizes for the x and y axes.
  2283. """
  2284. height, width = image_shape[:2]
  2285. # compensate for smaller last steps in source image.
  2286. x_step = width // num_steps
  2287. last_x_step = min(width, ((num_steps + 1) * x_step)) - (num_steps * x_step)
  2288. x_steps[-1] *= last_x_step / x_step
  2289. y_step = height // num_steps
  2290. last_y_step = min(height, ((num_steps + 1) * y_step)) - (num_steps * y_step)
  2291. y_steps[-1] *= last_y_step / y_step
  2292. # now normalize such that distortion never leaves image bounds.
  2293. tx = width / math.floor(width / num_steps)
  2294. ty = height / math.floor(height / num_steps)
  2295. x_steps = np.array(x_steps) * (tx / np.sum(x_steps))
  2296. y_steps = np.array(y_steps) * (ty / np.sum(y_steps))
  2297. return {"steps_x": x_steps, "steps_y": y_steps}
  2298. def almost_equal_intervals(n: int, parts: int) -> np.ndarray:
  2299. """Generates an array of nearly equal integer intervals that sum up to `n`.
  2300. This function divides the number `n` into `parts` nearly equal parts. It ensures that
  2301. the sum of all parts equals `n`, and the difference between any two parts is at most one.
  2302. This is useful for distributing a total amount into nearly equal discrete parts.
  2303. Args:
  2304. n (int): The total value to be split.
  2305. parts (int): The number of parts to split into.
  2306. Returns:
  2307. np.ndarray: An array of integers where each integer represents the size of a part.
  2308. Example:
  2309. >>> almost_equal_intervals(20, 3)
  2310. array([7, 7, 6]) # Splits 20 into three parts: 7, 7, and 6
  2311. >>> almost_equal_intervals(16, 4)
  2312. array([4, 4, 4, 4]) # Splits 16 into four equal parts
  2313. """
  2314. part_size, remainder = divmod(n, parts)
  2315. # Create an array with the base part size and adjust the first `remainder` parts by adding 1
  2316. return np.array(
  2317. [part_size + 1 if i < remainder else part_size for i in range(parts)],
  2318. )
  2319. def generate_shuffled_splits(
  2320. size: int,
  2321. divisions: int,
  2322. random_generator: np.random.Generator,
  2323. ) -> np.ndarray:
  2324. """Generate shuffled splits for a given dimension size and number of divisions.
  2325. Args:
  2326. size (int): Total size of the dimension (height or width).
  2327. divisions (int): Number of divisions (rows or columns).
  2328. random_generator (np.random.Generator | None): The random generator to use for shuffling the splits.
  2329. If None, the splits are not shuffled.
  2330. Returns:
  2331. np.ndarray: Cumulative edges of the shuffled intervals.
  2332. """
  2333. intervals = almost_equal_intervals(size, divisions)
  2334. random_generator.shuffle(intervals)
  2335. return np.insert(np.cumsum(intervals), 0, 0)
  2336. def split_uniform_grid(
  2337. image_shape: tuple[int, int],
  2338. grid: tuple[int, int],
  2339. random_generator: np.random.Generator,
  2340. ) -> np.ndarray:
  2341. """Splits an image shape into a uniform grid specified by the grid dimensions.
  2342. Args:
  2343. image_shape (tuple[int, int]): The shape of the image as (height, width).
  2344. grid (tuple[int, int]): The grid size as (rows, columns).
  2345. random_generator (np.random.Generator): The random generator to use for shuffling the splits.
  2346. If None, the splits are not shuffled.
  2347. Returns:
  2348. np.ndarray: An array containing the tiles' coordinates in the format (start_y, start_x, end_y, end_x).
  2349. Note:
  2350. The function uses `generate_shuffled_splits` to generate the splits for the height and width of the image.
  2351. The splits are then used to calculate the coordinates of the tiles.
  2352. """
  2353. n_rows, n_cols = grid
  2354. height_splits = generate_shuffled_splits(
  2355. image_shape[0],
  2356. grid[0],
  2357. random_generator=random_generator,
  2358. )
  2359. width_splits = generate_shuffled_splits(
  2360. image_shape[1],
  2361. grid[1],
  2362. random_generator=random_generator,
  2363. )
  2364. # Calculate tiles coordinates
  2365. tiles = [
  2366. (height_splits[i], width_splits[j], height_splits[i + 1], width_splits[j + 1])
  2367. for i in range(n_rows)
  2368. for j in range(n_cols)
  2369. ]
  2370. return np.array(tiles, dtype=np.int16)
  2371. def generate_perspective_points(
  2372. image_shape: tuple[int, int],
  2373. scale: float,
  2374. random_generator: np.random.Generator,
  2375. ) -> np.ndarray:
  2376. """Generate perspective points for a given image shape and scale.
  2377. This function generates perspective points for a given image shape and scale.
  2378. It uses a normal distribution to generate the points, and then modulates them to be within the image bounds.
  2379. Args:
  2380. image_shape (tuple[int, int]): The shape of the image as (height, width).
  2381. scale (float): The scale of the perspective points.
  2382. random_generator (np.random.Generator): The random generator to use for generating the points.
  2383. Returns:
  2384. np.ndarray: The perspective points.
  2385. """
  2386. height, width = image_shape[:2]
  2387. points = random_generator.normal(0, scale, (4, 2))
  2388. points = np.mod(np.abs(points), 0.32)
  2389. # top left -- no changes needed, just use jitter
  2390. # top right
  2391. points[1, 0] = 1.0 - points[1, 0] # w = 1.0 - jitter
  2392. # bottom right
  2393. points[2] = 1.0 - points[2] # w = 1.0 - jitter
  2394. # bottom left
  2395. points[3, 1] = 1.0 - points[3, 1] # h = 1.0 - jitter
  2396. points[:, 0] *= width
  2397. points[:, 1] *= height
  2398. return points
  2399. def order_points(pts: np.ndarray) -> np.ndarray:
  2400. """Order points in a clockwise manner.
  2401. This function orders the points in a clockwise manner, ensuring that the points are in the correct
  2402. order for perspective transformation.
  2403. Args:
  2404. pts (np.ndarray): The points to order.
  2405. Returns:
  2406. np.ndarray: The ordered points.
  2407. """
  2408. pts = np.array(sorted(pts, key=lambda x: x[0]))
  2409. left = pts[:2] # points with smallest x coordinate - left points
  2410. right = pts[2:] # points with greatest x coordinate - right points
  2411. if left[0][1] < left[1][1]:
  2412. tl, bl = left
  2413. else:
  2414. bl, tl = left
  2415. if right[0][1] < right[1][1]:
  2416. tr, br = right
  2417. else:
  2418. br, tr = right
  2419. return np.array([tl, tr, br, bl], dtype=np.float32)
  2420. def compute_perspective_params(
  2421. points: np.ndarray,
  2422. image_shape: tuple[int, int],
  2423. ) -> tuple[np.ndarray, int, int]:
  2424. """Compute perspective transformation parameters.
  2425. This function computes the perspective transformation parameters for a given set of points.
  2426. It adjusts the points to ensure that the transformed image retains its original dimensions.
  2427. Args:
  2428. points (np.ndarray): The points to compute the perspective transformation parameters for.
  2429. image_shape (tuple[int, int]): The shape of the image.
  2430. Returns:
  2431. tuple[np.ndarray, int, int]: The perspective transformation parameters and the maximum
  2432. dimensions of the transformed image.
  2433. """
  2434. height, width = image_shape
  2435. top_left, top_right, bottom_right, bottom_left = points
  2436. def adjust_dimension(
  2437. dim1: np.ndarray,
  2438. dim2: np.ndarray,
  2439. min_size: int = 2,
  2440. ) -> float:
  2441. size = np.sqrt(np.sum((dim1 - dim2) ** 2))
  2442. if size < min_size:
  2443. step_size = (min_size - size) / 2
  2444. dim1[dim1 > dim2] += step_size
  2445. dim2[dim1 > dim2] -= step_size
  2446. dim1[dim1 <= dim2] -= step_size
  2447. dim2[dim1 <= dim2] += step_size
  2448. size = min_size
  2449. return size
  2450. max_width = max(
  2451. adjust_dimension(top_right, top_left),
  2452. adjust_dimension(bottom_right, bottom_left),
  2453. )
  2454. max_height = max(
  2455. adjust_dimension(bottom_right, top_right),
  2456. adjust_dimension(bottom_left, top_left),
  2457. )
  2458. dst = np.array([[0, 0], [width, 0], [width, height], [0, height]], dtype=np.float32)
  2459. matrix = cv2.getPerspectiveTransform(points, dst)
  2460. return matrix, int(max_width), int(max_height)
  2461. def expand_transform(
  2462. matrix: np.ndarray,
  2463. shape: tuple[int, int],
  2464. ) -> tuple[np.ndarray, int, int]:
  2465. """Expand a transformation matrix to include padding.
  2466. This function expands a transformation matrix to include padding, ensuring that the transformed
  2467. image retains its original dimensions. It first calculates the destination points of the transformed
  2468. image, then adjusts the matrix to include padding, and finally returns the expanded matrix and the
  2469. maximum dimensions of the transformed image.
  2470. Args:
  2471. matrix (np.ndarray): The transformation matrix to expand.
  2472. shape (tuple[int, int]): The shape of the image.
  2473. Returns:
  2474. tuple[np.ndarray, int, int]: The expanded matrix and the maximum dimensions of the transformed image.
  2475. """
  2476. height, width = shape[:2]
  2477. rect = np.array(
  2478. [[0, 0], [width, 0], [width, height], [0, height]],
  2479. dtype=np.float32,
  2480. )
  2481. dst = cv2.perspectiveTransform(np.array([rect]), matrix)[0]
  2482. dst -= dst.min(axis=0, keepdims=True)
  2483. dst = np.around(dst, decimals=0)
  2484. matrix_expanded = cv2.getPerspectiveTransform(rect, dst)
  2485. max_width, max_height = dst.max(axis=0)
  2486. return matrix_expanded, int(max_width), int(max_height)
  2487. def create_piecewise_affine_maps(
  2488. image_shape: tuple[int, int],
  2489. grid: tuple[int, int],
  2490. scale: float,
  2491. absolute_scale: bool,
  2492. random_generator: np.random.Generator,
  2493. ) -> tuple[np.ndarray | None, np.ndarray | None]:
  2494. """Create maps for piecewise affine transformation using OpenCV's remap function.
  2495. This function creates maps for piecewise affine transformation using OpenCV's remap function.
  2496. It generates the control points for the transformation, then uses the remap function to create
  2497. the transformation maps.
  2498. Args:
  2499. image_shape (tuple[int, int]): The shape of the image as (height, width).
  2500. grid (tuple[int, int]): The grid size as (rows, columns).
  2501. scale (float): The scale of the transformation.
  2502. absolute_scale (bool): Whether to use absolute scale.
  2503. random_generator (np.random.Generator): The random generator to use for generating the points.
  2504. Returns:
  2505. tuple[np.ndarray | None, np.ndarray | None]: The transformation maps.
  2506. """
  2507. height, width = image_shape[:2]
  2508. nb_rows, nb_cols = grid
  2509. # Input validation
  2510. if height <= 0 or width <= 0 or nb_rows <= 0 or nb_cols <= 0:
  2511. raise ValueError("Dimensions must be positive")
  2512. if scale <= 0:
  2513. return None, None
  2514. # Create source points grid
  2515. y = np.linspace(0, height - 1, nb_rows, dtype=np.float32)
  2516. x = np.linspace(0, width - 1, nb_cols, dtype=np.float32)
  2517. xx_src, yy_src = np.meshgrid(x, y)
  2518. # Initialize destination maps at full resolution
  2519. map_x = np.zeros((height, width), dtype=np.float32)
  2520. map_y = np.zeros((height, width), dtype=np.float32)
  2521. # Generate jitter for control points
  2522. jitter_scale = scale / 3 if absolute_scale else scale * min(width, height) / 3
  2523. jitter = random_generator.normal(0, jitter_scale, (nb_rows, nb_cols, 2)).astype(
  2524. np.float32,
  2525. )
  2526. # Create control points with jitter
  2527. control_points = np.zeros((nb_rows * nb_cols, 4), dtype=np.float32)
  2528. for i in range(nb_rows):
  2529. for j in range(nb_cols):
  2530. idx = i * nb_cols + j
  2531. # Source points
  2532. control_points[idx, 0] = xx_src[i, j]
  2533. control_points[idx, 1] = yy_src[i, j]
  2534. # Destination points with jitter
  2535. control_points[idx, 2] = np.clip(
  2536. xx_src[i, j] + jitter[i, j, 1],
  2537. 0,
  2538. width - 1,
  2539. )
  2540. control_points[idx, 3] = np.clip(
  2541. yy_src[i, j] + jitter[i, j, 0],
  2542. 0,
  2543. height - 1,
  2544. )
  2545. # Create full resolution maps
  2546. for i in range(height):
  2547. for j in range(width):
  2548. # Find nearest control points and interpolate
  2549. dx = j - control_points[:, 0]
  2550. dy = i - control_points[:, 1]
  2551. dist = dx * dx + dy * dy
  2552. weights = 1 / (dist + 1e-8)
  2553. weights = weights / np.sum(weights)
  2554. map_x[i, j] = np.sum(weights * control_points[:, 2])
  2555. map_y[i, j] = np.sum(weights * control_points[:, 3])
  2556. # Ensure output is within bounds
  2557. map_x = np.clip(map_x, 0, width - 1, out=map_x)
  2558. map_y = np.clip(map_y, 0, height - 1, out=map_y)
  2559. return map_x, map_y
  2560. @handle_empty_array("bboxes")
  2561. def bboxes_piecewise_affine(
  2562. bboxes: np.ndarray,
  2563. map_x: np.ndarray,
  2564. map_y: np.ndarray,
  2565. border_mode: int,
  2566. image_shape: tuple[int, int],
  2567. ) -> np.ndarray:
  2568. """Apply a piecewise affine transformation to bounding boxes.
  2569. This function applies a piecewise affine transformation to the bounding boxes of an image.
  2570. It first converts the bounding boxes to masks, then applies the transformation, and finally
  2571. converts the transformed masks back to bounding boxes.
  2572. Args:
  2573. bboxes (np.ndarray): The bounding boxes to transform.
  2574. map_x (np.ndarray): The x-coordinates of the transformation.
  2575. map_y (np.ndarray): The y-coordinates of the transformation.
  2576. border_mode (int): The border mode to use for the transformation.
  2577. image_shape (tuple[int, int]): The shape of the image.
  2578. Returns:
  2579. np.ndarray: The transformed bounding boxes.
  2580. """
  2581. masks = masks_from_bboxes(bboxes, image_shape).transpose(1, 2, 0)
  2582. map_xy = np.stack([map_x, map_y], axis=-1).astype(np.float32)
  2583. # Call remap with the combined map and empty second map
  2584. transformed_masks = cv2.remap(
  2585. masks,
  2586. map_xy,
  2587. None,
  2588. cv2.INTER_NEAREST,
  2589. borderMode=border_mode,
  2590. borderValue=0,
  2591. )
  2592. if transformed_masks.ndim == NUM_MULTI_CHANNEL_DIMENSIONS:
  2593. transformed_masks = transformed_masks.transpose(2, 0, 1)
  2594. # Normalize the returned bboxes
  2595. bboxes[:, :4] = bboxes_from_masks(transformed_masks)
  2596. return bboxes
  2597. def get_dimension_padding(
  2598. current_size: int,
  2599. min_size: int | None,
  2600. divisor: int | None,
  2601. ) -> tuple[int, int]:
  2602. """Calculate padding for a single dimension.
  2603. Args:
  2604. current_size (int): Current size of the dimension
  2605. min_size (int | None): Minimum size requirement, if any
  2606. divisor (int | None): Divisor for padding to make size divisible, if any
  2607. Returns:
  2608. tuple[int, int]: (pad_before, pad_after)
  2609. """
  2610. if min_size is not None:
  2611. if current_size < min_size:
  2612. pad_before = int((min_size - current_size) / 2.0)
  2613. pad_after = min_size - current_size - pad_before
  2614. return pad_before, pad_after
  2615. elif divisor is not None:
  2616. remainder = current_size % divisor
  2617. if remainder > 0:
  2618. total_pad = divisor - remainder
  2619. pad_before = total_pad // 2
  2620. pad_after = total_pad - pad_before
  2621. return pad_before, pad_after
  2622. return 0, 0
  2623. def get_padding_params(
  2624. image_shape: tuple[int, int],
  2625. min_height: int | None,
  2626. min_width: int | None,
  2627. pad_height_divisor: int | None,
  2628. pad_width_divisor: int | None,
  2629. ) -> tuple[int, int, int, int]:
  2630. """Calculate padding parameters based on target dimensions.
  2631. Args:
  2632. image_shape (tuple[int, int]): (height, width) of the image
  2633. min_height (int | None): Minimum height requirement, if any
  2634. min_width (int | None): Minimum width requirement, if any
  2635. pad_height_divisor (int | None): Divisor for height padding, if any
  2636. pad_width_divisor (int | None): Divisor for width padding, if any
  2637. Returns:
  2638. tuple[int, int, int, int]: (pad_top, pad_bottom, pad_left, pad_right)
  2639. """
  2640. rows, cols = image_shape[:2]
  2641. h_pad_top, h_pad_bottom = get_dimension_padding(
  2642. rows,
  2643. min_height,
  2644. pad_height_divisor,
  2645. )
  2646. w_pad_left, w_pad_right = get_dimension_padding(cols, min_width, pad_width_divisor)
  2647. return h_pad_top, h_pad_bottom, w_pad_left, w_pad_right
  2648. def adjust_padding_by_position(
  2649. h_top: int,
  2650. h_bottom: int,
  2651. w_left: int,
  2652. w_right: int,
  2653. position: Literal["center", "top_left", "top_right", "bottom_left", "bottom_right", "random"],
  2654. py_random: np.random.RandomState,
  2655. ) -> tuple[int, int, int, int]:
  2656. """Adjust padding values based on desired position."""
  2657. if position == "center":
  2658. return h_top, h_bottom, w_left, w_right
  2659. if position == "top_left":
  2660. return 0, h_top + h_bottom, 0, w_left + w_right
  2661. if position == "top_right":
  2662. return 0, h_top + h_bottom, w_left + w_right, 0
  2663. if position == "bottom_left":
  2664. return h_top + h_bottom, 0, 0, w_left + w_right
  2665. if position == "bottom_right":
  2666. return h_top + h_bottom, 0, w_left + w_right, 0
  2667. if position == "random":
  2668. h_pad = h_top + h_bottom
  2669. w_pad = w_left + w_right
  2670. h_top = py_random.randint(0, h_pad)
  2671. h_bottom = h_pad - h_top
  2672. w_left = py_random.randint(0, w_pad)
  2673. w_right = w_pad - w_left
  2674. return h_top, h_bottom, w_left, w_right
  2675. raise ValueError(f"Unknown position: {position}")
  2676. def swap_tiles_on_keypoints(
  2677. keypoints: np.ndarray,
  2678. tiles: np.ndarray,
  2679. mapping: np.ndarray,
  2680. ) -> np.ndarray:
  2681. """Swap the positions of keypoints based on a tile mapping.
  2682. This function takes a set of keypoints and repositions them according to a mapping of tile swaps.
  2683. Keypoints are moved from their original tiles to new positions in the swapped tiles.
  2684. Args:
  2685. keypoints (np.ndarray): A 2D numpy array of shape (N, 2) where N is the number of keypoints.
  2686. Each row represents a keypoint's (x, y) coordinates.
  2687. tiles (np.ndarray): A 2D numpy array of shape (M, 4) where M is the number of tiles.
  2688. Each row represents a tile's (start_y, start_x, end_y, end_x) coordinates.
  2689. mapping (np.ndarray): A 1D numpy array of shape (M,) where M is the number of tiles.
  2690. Each element i contains the index of the tile that tile i should be swapped with.
  2691. Returns:
  2692. np.ndarray: A 2D numpy array of the same shape as the input keypoints, containing the new positions
  2693. of the keypoints after the tile swap.
  2694. Raises:
  2695. RuntimeWarning: If any keypoint is not found within any tile.
  2696. Notes:
  2697. - Keypoints that do not fall within any tile will remain unchanged.
  2698. - The function assumes that the tiles do not overlap and cover the entire image space.
  2699. """
  2700. if not keypoints.size:
  2701. return keypoints
  2702. # Broadcast keypoints and tiles for vectorized comparison
  2703. kp_x = keypoints[:, 0][:, np.newaxis] # Shape: (num_keypoints, 1)
  2704. kp_y = keypoints[:, 1][:, np.newaxis] # Shape: (num_keypoints, 1)
  2705. start_y, start_x, end_y, end_x = tiles.T # Each shape: (num_tiles,)
  2706. # Check if each keypoint is inside each tile
  2707. in_tile = (kp_y >= start_y) & (kp_y < end_y) & (kp_x >= start_x) & (kp_x < end_x)
  2708. # Find which tile each keypoint belongs to
  2709. tile_indices = np.argmax(in_tile, axis=1)
  2710. # Check if any keypoint is not in any tile
  2711. not_in_any_tile = ~np.any(in_tile, axis=1)
  2712. if np.any(not_in_any_tile):
  2713. warn(
  2714. "Some keypoints are not in any tile. They will be returned unchanged. This is unexpected and should be "
  2715. "investigated.",
  2716. RuntimeWarning,
  2717. stacklevel=2,
  2718. )
  2719. # Get the new tile indices
  2720. new_tile_indices = np.array(mapping)[tile_indices]
  2721. # Calculate the offsets
  2722. old_start_x = tiles[tile_indices, 1]
  2723. old_start_y = tiles[tile_indices, 0]
  2724. new_start_x = tiles[new_tile_indices, 1]
  2725. new_start_y = tiles[new_tile_indices, 0]
  2726. # Apply the transformation
  2727. new_keypoints = keypoints.copy()
  2728. new_keypoints[:, 0] = (keypoints[:, 0] - old_start_x) + new_start_x
  2729. new_keypoints[:, 1] = (keypoints[:, 1] - old_start_y) + new_start_y
  2730. # Keep original coordinates for keypoints not in any tile
  2731. new_keypoints[not_in_any_tile] = keypoints[not_in_any_tile]
  2732. return new_keypoints
  2733. def swap_tiles_on_image(
  2734. image: np.ndarray,
  2735. tiles: np.ndarray,
  2736. mapping: list[int] | None = None,
  2737. ) -> np.ndarray:
  2738. """Swap tiles on the image according to the new format.
  2739. Args:
  2740. image (np.ndarray): Input image.
  2741. tiles (np.ndarray): Array of tiles with each tile as [start_y, start_x, end_y, end_x].
  2742. mapping (list[int] | None): list of new tile indices.
  2743. Returns:
  2744. np.ndarray: Output image with tiles swapped according to the random shuffle.
  2745. """
  2746. # If no tiles are provided, return a copy of the original image
  2747. if tiles.size == 0 or mapping is None:
  2748. return image.copy()
  2749. # Create a copy of the image to retain original for reference
  2750. new_image = np.empty_like(image)
  2751. for num, new_index in enumerate(mapping):
  2752. start_y, start_x, end_y, end_x = tiles[new_index]
  2753. start_y_orig, start_x_orig, end_y_orig, end_x_orig = tiles[num]
  2754. # Assign the corresponding tile from the original image to the new image
  2755. new_image[start_y:end_y, start_x:end_x] = image[
  2756. start_y_orig:end_y_orig,
  2757. start_x_orig:end_x_orig,
  2758. ]
  2759. return new_image
  2760. def is_valid_component(
  2761. component_area: float,
  2762. original_area: float,
  2763. min_area: float | None,
  2764. min_visibility: float | None,
  2765. ) -> bool:
  2766. """Validate if a component meets the minimum requirements."""
  2767. visibility = component_area / original_area
  2768. return (min_area is None or component_area >= min_area) and (min_visibility is None or visibility >= min_visibility)
  2769. @handle_empty_array("bboxes")
  2770. def bboxes_grid_shuffle(
  2771. bboxes: np.ndarray,
  2772. tiles: np.ndarray,
  2773. mapping: list[int],
  2774. image_shape: tuple[int, int],
  2775. min_area: float,
  2776. min_visibility: float,
  2777. ) -> np.ndarray:
  2778. """Shuffle bounding boxes according to grid mapping.
  2779. Args:
  2780. bboxes (np.ndarray): Array of bounding boxes with shape (num_boxes, 4+)
  2781. tiles (np.ndarray): Array of grid tiles
  2782. mapping (list[int]): Mapping of tile indices
  2783. image_shape (tuple[int, int]): Shape of the image (height, width)
  2784. min_area (float): Minimum area of a bounding box to keep
  2785. min_visibility (float): Minimum visibility ratio of a bounding box to keep
  2786. Returns:
  2787. np.ndarray: Shuffled bounding boxes
  2788. """
  2789. # Convert bboxes to masks
  2790. masks = masks_from_bboxes(bboxes, image_shape)
  2791. # Apply grid shuffle to each mask and handle split components
  2792. all_component_masks = []
  2793. extra_bbox_data = [] # Store additional bbox data for each component
  2794. for idx, mask in enumerate(masks):
  2795. original_area = np.sum(mask) # Get original mask area
  2796. # Shuffle the mask
  2797. shuffled_mask = swap_tiles_on_image(mask, tiles, mapping)
  2798. # Find connected components
  2799. num_components, components = cv2.connectedComponents(
  2800. shuffled_mask.astype(np.uint8),
  2801. )
  2802. # For each component, create a separate binary mask
  2803. for comp_idx in range(1, num_components): # Skip background (0)
  2804. component_mask = (components == comp_idx).astype(np.uint8)
  2805. # Calculate area and visibility ratio
  2806. component_area = np.sum(component_mask)
  2807. # Check if component meets minimum requirements
  2808. if is_valid_component(
  2809. component_area,
  2810. original_area,
  2811. min_area,
  2812. min_visibility,
  2813. ):
  2814. all_component_masks.append(component_mask)
  2815. # Append additional bbox data for this component
  2816. if bboxes.shape[1] > NUM_BBOXES_COLUMNS_IN_ALBUMENTATIONS:
  2817. extra_bbox_data.append(bboxes[idx, 4:])
  2818. # Convert all component masks to bboxes
  2819. if all_component_masks:
  2820. all_component_masks = np.array(all_component_masks)
  2821. shuffled_bboxes = bboxes_from_masks(all_component_masks)
  2822. # Add back additional bbox data if present
  2823. if extra_bbox_data:
  2824. extra_bbox_data = np.array(extra_bbox_data)
  2825. return np.column_stack([shuffled_bboxes, extra_bbox_data])
  2826. else:
  2827. # Handle case where no valid components were found
  2828. return np.zeros((0, bboxes.shape[1]), dtype=bboxes.dtype)
  2829. return shuffled_bboxes
  2830. def create_shape_groups(tiles: np.ndarray) -> dict[tuple[int, int], list[int]]:
  2831. """Groups tiles by their shape and stores the indices for each shape."""
  2832. shape_groups = defaultdict(list)
  2833. for index, (start_y, start_x, end_y, end_x) in enumerate(tiles):
  2834. shape = (end_y - start_y, end_x - start_x)
  2835. shape_groups[shape].append(index)
  2836. return shape_groups
  2837. def shuffle_tiles_within_shape_groups(
  2838. shape_groups: dict[tuple[int, int], list[int]],
  2839. random_generator: np.random.Generator,
  2840. ) -> list[int]:
  2841. """Shuffles indices within each group of similar shapes and creates a list where each
  2842. index points to the index of the tile it should be mapped to.
  2843. Args:
  2844. shape_groups (dict[tuple[int, int], list[int]]): Groups of tile indices categorized by shape.
  2845. random_generator (np.random.Generator): The random generator to use for shuffling the indices.
  2846. If None, a new random generator will be used.
  2847. Returns:
  2848. list[int]: A list where each index is mapped to the new index of the tile after shuffling.
  2849. """
  2850. # Initialize the output list with the same size as the total number of tiles, filled with -1
  2851. num_tiles = sum(len(indices) for indices in shape_groups.values())
  2852. mapping = [-1] * num_tiles
  2853. # Prepare the random number generator
  2854. for indices in shape_groups.values():
  2855. shuffled_indices = indices.copy()
  2856. random_generator.shuffle(shuffled_indices)
  2857. for old, new in zip(indices, shuffled_indices):
  2858. mapping[old] = new
  2859. return mapping
  2860. def compute_pairwise_distances(
  2861. points1: np.ndarray,
  2862. points2: np.ndarray,
  2863. ) -> np.ndarray:
  2864. """Compute pairwise distances between two sets of points.
  2865. Args:
  2866. points1 (np.ndarray): First set of points with shape (N, 2)
  2867. points2 (np.ndarray): Second set of points with shape (M, 2)
  2868. Returns:
  2869. np.ndarray: Matrix of pairwise distances with shape (N, M)
  2870. """
  2871. points1 = np.ascontiguousarray(points1, dtype=np.float32)
  2872. points2 = np.ascontiguousarray(points2, dtype=np.float32)
  2873. # Compute squared terms
  2874. p1_squared = cv2.multiply(points1, points1).sum(axis=1, keepdims=True)
  2875. p2_squared = cv2.multiply(points2, points2).sum(axis=1)[None, :]
  2876. # Compute dot product
  2877. dot_product = cv2.gemm(points1, points2.T, 1, None, 0)
  2878. return p1_squared + p2_squared - 2 * dot_product
  2879. def compute_tps_weights(
  2880. src_points: np.ndarray,
  2881. dst_points: np.ndarray,
  2882. ) -> tuple[np.ndarray, np.ndarray]:
  2883. """Compute Thin Plate Spline weights.
  2884. Args:
  2885. src_points (np.ndarray): Source control points with shape (num_points, 2)
  2886. dst_points (np.ndarray): Destination control points with shape (num_points, 2)
  2887. Returns:
  2888. tuple[np.ndarray, np.ndarray]: Tuple of (nonlinear_weights, affine_weights)
  2889. - nonlinear_weights: TPS kernel weights for nonlinear deformation (num_points, 2)
  2890. - affine_weights: Weights for affine transformation (3, 2)
  2891. [constant term, x scale/shear, y scale/shear]
  2892. Note:
  2893. The TPS interpolation is decomposed into:
  2894. 1. Nonlinear part (controlled by kernel weights)
  2895. 2. Affine part (global scaling, rotation, translation)
  2896. """
  2897. num_points = src_points.shape[0]
  2898. # Compute pairwise distances
  2899. distances = compute_pairwise_distances(src_points, src_points)
  2900. kernel_matrix = np.where(
  2901. distances > 0,
  2902. distances * distances * cv2.log(distances + 1e-6),
  2903. 0,
  2904. ).astype(np.float32)
  2905. # Build system matrix efficiently
  2906. affine_terms = np.empty((num_points, 3), dtype=np.float32)
  2907. affine_terms[:, 0] = 1
  2908. affine_terms[:, 1:] = src_points
  2909. # Construct system matrix
  2910. system_matrix = np.zeros((num_points + 3, num_points + 3), dtype=np.float32)
  2911. system_matrix[:num_points, :num_points] = kernel_matrix
  2912. system_matrix[:num_points, num_points:] = affine_terms
  2913. system_matrix[num_points:, :num_points] = affine_terms.T
  2914. # Prepare target coordinates
  2915. target = np.zeros((num_points + 3, 2), dtype=np.float32)
  2916. target[:num_points] = dst_points
  2917. weights = cv2.solve(system_matrix, target, flags=cv2.DECOMP_LU)[1]
  2918. return weights[:num_points], weights[num_points:]
  2919. def tps_transform(
  2920. target_points: np.ndarray,
  2921. control_points: np.ndarray,
  2922. nonlinear_weights: np.ndarray,
  2923. affine_weights: np.ndarray,
  2924. ) -> np.ndarray:
  2925. """Apply TPS transformation with consistent types."""
  2926. # Ensure float32 type for all inputs
  2927. target_points = np.ascontiguousarray(target_points, dtype=np.float32)
  2928. control_points = np.ascontiguousarray(control_points, dtype=np.float32)
  2929. nonlinear_weights = np.ascontiguousarray(nonlinear_weights, dtype=np.float32)
  2930. affine_weights = np.ascontiguousarray(affine_weights, dtype=np.float32)
  2931. distances = compute_pairwise_distances(target_points, control_points)
  2932. # Ensure kernel matrix is float32
  2933. kernel_matrix = np.where(
  2934. distances > 0,
  2935. distances * cv2.log(distances + 1e-6),
  2936. 0,
  2937. ).astype(np.float32)
  2938. # Prepare affine terms
  2939. num_points = len(target_points)
  2940. affine_terms = np.empty((num_points, 3), dtype=np.float32)
  2941. affine_terms[:, 0] = 1
  2942. affine_terms[:, 1:] = target_points
  2943. # Matrix multiplications with consistent float32 type
  2944. nonlinear_part = cv2.gemm(kernel_matrix, nonlinear_weights, 1, None, 0)
  2945. affine_part = cv2.gemm(affine_terms, affine_weights, 1, None, 0)
  2946. return nonlinear_part + affine_part
  2947. def get_camera_matrix_distortion_maps(
  2948. image_shape: tuple[int, int],
  2949. k: float,
  2950. ) -> tuple[np.ndarray, np.ndarray]:
  2951. """Generate distortion maps using camera matrix model.
  2952. Args:
  2953. image_shape (tuple[int, int]): Image shape (height, width)
  2954. k (float): Distortion coefficient
  2955. Returns:
  2956. tuple[np.ndarray, np.ndarray]: Tuple of (map_x, map_y) distortion maps
  2957. """
  2958. height, width = image_shape[:2]
  2959. center_x, center_y = width / 2, height / 2
  2960. camera_matrix = np.array(
  2961. [[width, 0, center_x], [0, height, center_y], [0, 0, 1]],
  2962. dtype=np.float32,
  2963. )
  2964. distortion = np.array([k, k, 0, 0, 0], dtype=np.float32)
  2965. return cv2.initUndistortRectifyMap(
  2966. camera_matrix,
  2967. distortion,
  2968. None,
  2969. None,
  2970. (width, height),
  2971. cv2.CV_32FC1,
  2972. )
  2973. def get_fisheye_distortion_maps(
  2974. image_shape: tuple[int, int],
  2975. k: float,
  2976. ) -> tuple[np.ndarray, np.ndarray]:
  2977. """Generate distortion maps using fisheye model.
  2978. Args:
  2979. image_shape (tuple[int, int]): Image shape (height, width)
  2980. k (float): Distortion coefficient
  2981. Returns:
  2982. tuple[np.ndarray, np.ndarray]: Tuple of (map_x, map_y) distortion maps
  2983. """
  2984. height, width = image_shape[:2]
  2985. center_x, center_y = width / 2, height / 2
  2986. # Create coordinate grid
  2987. y, x = np.mgrid[:height, :width].astype(np.float32)
  2988. x = x - center_x
  2989. y = y - center_y
  2990. # Calculate polar coordinates
  2991. r = np.sqrt(x * x + y * y)
  2992. theta = np.arctan2(y, x)
  2993. # Normalize radius by the maximum possible radius to keep distortion in check
  2994. max_radius = math.sqrt(max(center_x, width - center_x) ** 2 + max(center_y, height - center_y) ** 2)
  2995. r_norm = r / max_radius
  2996. # Apply fisheye distortion to normalized radius
  2997. r_dist = r * (1 + k * r_norm * r_norm)
  2998. # Convert back to cartesian coordinates
  2999. map_x = r_dist * np.cos(theta) + center_x
  3000. map_y = r_dist * np.sin(theta) + center_y
  3001. return map_x, map_y
  3002. def generate_control_points(num_control_points: int) -> np.ndarray:
  3003. """Generate control points for TPS transformation.
  3004. Args:
  3005. num_control_points (int): Number of control points per side
  3006. Returns:
  3007. np.ndarray: Control points with shape (N, 2)
  3008. """
  3009. if num_control_points == 2:
  3010. # Generate 4 corners + center point similar to Kornia
  3011. return np.array(
  3012. [
  3013. [0, 0], # top-left
  3014. [0, 1], # bottom-left
  3015. [1, 0], # top-right
  3016. [1, 1], # bottom-right
  3017. [0.5, 0.5], # center
  3018. ],
  3019. dtype=np.float32,
  3020. )
  3021. # Generate regular grid
  3022. x = np.linspace(0, 1, num_control_points)
  3023. y = np.linspace(0, 1, num_control_points)
  3024. return np.stack(np.meshgrid(x, y), axis=-1).reshape(-1, 2)
  3025. def volume_hflip(volume: np.ndarray) -> np.ndarray:
  3026. """Perform horizontal flip on a volume (numpy array).
  3027. Flips the volume along the width axis (axis=2). Handles inputs with
  3028. shapes (D, H, W) or (D, H, W, C).
  3029. Args:
  3030. volume (np.ndarray): Input volume.
  3031. Returns:
  3032. np.ndarray: Horizontally flipped volume.
  3033. """
  3034. return np.flip(volume, axis=2)
  3035. def volume_vflip(volume: np.ndarray) -> np.ndarray:
  3036. """Perform vertical flip on a volume (numpy array).
  3037. Flips the volume along the height axis (axis=1). Handles inputs with
  3038. shapes (D, H, W) or (D, H, W, C).
  3039. Args:
  3040. volume (np.ndarray): Input volume.
  3041. Returns:
  3042. np.ndarray: Vertically flipped volume.
  3043. """
  3044. return np.flip(volume, axis=1)
  3045. def volumes_hflip(volumes: np.ndarray) -> np.ndarray:
  3046. """Perform horizontal flip on a batch of volumes (numpy array).
  3047. Flips the volumes along the width axis (axis=3). Handles inputs with
  3048. shapes (B, D, H, W) or (B, D, H, W, C).
  3049. Args:
  3050. volumes (np.ndarray): Input batch of volumes.
  3051. Returns:
  3052. np.ndarray: Horizontally flipped batch of volumes.
  3053. """
  3054. # Width axis is 3 for both (B, D, H, W) and (B, D, H, W, C)
  3055. return np.flip(volumes, axis=3)
  3056. def volumes_vflip(volumes: np.ndarray) -> np.ndarray:
  3057. """Perform vertical flip on a batch of volumes (numpy array).
  3058. Flips the volumes along the height axis (axis=2). Handles inputs with
  3059. shapes (B, D, H, W) or (B, D, H, W, C).
  3060. Args:
  3061. volumes (np.ndarray): Input batch of volumes.
  3062. Returns:
  3063. np.ndarray: Vertically flipped batch of volumes.
  3064. """
  3065. # Height axis is 2 for both (B, D, H, W) and (B, D, H, W, C)
  3066. return np.flip(volumes, axis=2)
  3067. def volume_rot90(volume: np.ndarray, factor: Literal[0, 1, 2, 3]) -> np.ndarray:
  3068. """Rotate a volume 90 degrees counter-clockwise multiple times.
  3069. Rotates the volume in the height-width plane (axes 1 and 2).
  3070. Handles inputs with shapes (D, H, W) or (D, H, W, C).
  3071. Args:
  3072. volume (np.ndarray): Input volume.
  3073. factor (Literal[0, 1, 2, 3]): Number of 90-degree rotations.
  3074. Returns:
  3075. np.ndarray: Rotated volume.
  3076. """
  3077. # Axes 1 (height) and 2 (width) for rotation
  3078. return np.rot90(volume, k=factor, axes=(1, 2))
  3079. def volumes_rot90(volumes: np.ndarray, factor: Literal[0, 1, 2, 3]) -> np.ndarray:
  3080. """Rotate a batch of volumes 90 degrees counter-clockwise multiple times.
  3081. Rotates the volumes in the height-width plane (axes 2 and 3).
  3082. Handles inputs with shapes (B, D, H, W) or (B, D, H, W, C).
  3083. Args:
  3084. volumes (np.ndarray): Input batch of volumes.
  3085. factor (Literal[0, 1, 2, 3]): Number of 90-degree rotations
  3086. Returns:
  3087. np.ndarray: Rotated batch of volumes.
  3088. """
  3089. # Axes 2 (height) and 3 (width) for rotation
  3090. return np.rot90(volumes, k=factor, axes=(2, 3))
  3091. @preserve_channel_dim
  3092. def erode(img: np.ndarray, kernel: np.ndarray) -> np.ndarray:
  3093. """Apply erosion to an image.
  3094. This function applies erosion to an image using the cv2.erode function.
  3095. Args:
  3096. img (np.ndarray): Input image as a numpy array.
  3097. kernel (np.ndarray): Kernel as a numpy array.
  3098. Returns:
  3099. np.ndarray: The eroded image.
  3100. """
  3101. return cv2.erode(img, kernel, iterations=1)
  3102. @preserve_channel_dim
  3103. def dilate(img: np.ndarray, kernel: np.ndarray) -> np.ndarray:
  3104. """Apply dilation to an image.
  3105. This function applies dilation to an image using the cv2.dilate function.
  3106. Args:
  3107. img (np.ndarray): Input image as a numpy array.
  3108. kernel (np.ndarray): Kernel as a numpy array.
  3109. Returns:
  3110. np.ndarray: The dilated image.
  3111. """
  3112. return cv2.dilate(img, kernel, iterations=1)
  3113. def morphology(
  3114. img: np.ndarray,
  3115. kernel: np.ndarray,
  3116. operation: Literal["dilation", "erosion"],
  3117. ) -> np.ndarray:
  3118. """Apply morphology to an image.
  3119. This function applies morphology to an image using the cv2.morphologyEx function.
  3120. Args:
  3121. img (np.ndarray): Input image as a numpy array.
  3122. kernel (np.ndarray): Kernel as a numpy array.
  3123. operation (Literal["dilation", "erosion"]): The operation to apply.
  3124. Returns:
  3125. np.ndarray: The morphology applied to the image.
  3126. """
  3127. if operation == "dilation":
  3128. return dilate(img, kernel)
  3129. if operation == "erosion":
  3130. return erode(img, kernel)
  3131. raise ValueError(f"Unsupported operation: {operation}")
  3132. @handle_empty_array("bboxes")
  3133. def bboxes_morphology(
  3134. bboxes: np.ndarray,
  3135. kernel: np.ndarray,
  3136. operation: Literal["dilation", "erosion"],
  3137. image_shape: tuple[int, int],
  3138. ) -> np.ndarray:
  3139. """Apply morphology to bounding boxes.
  3140. This function applies morphology to bounding boxes by first converting the bounding
  3141. boxes to a mask and then applying the morphology to the mask.
  3142. Args:
  3143. bboxes (np.ndarray): Bounding boxes as a numpy array.
  3144. kernel (np.ndarray): Kernel as a numpy array.
  3145. operation (Literal["dilation", "erosion"]): The operation to apply.
  3146. image_shape (tuple[int, int]): The shape of the image.
  3147. Returns:
  3148. np.ndarray: The morphology applied to the bounding boxes.
  3149. """
  3150. bboxes = bboxes.copy()
  3151. masks = masks_from_bboxes(bboxes, image_shape)
  3152. masks = morphology(masks, kernel, operation)
  3153. bboxes[:, :4] = bboxes_from_masks(masks)
  3154. return bboxes