support yolov8-obb python inference

support yolov8-obb python inference
pull/93/merge
triple-mu 3 months ago committed by GitHub
commit 13014de258
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
  1. 4
      .gitignore
  2. 383
      config.py
  3. 2
      csrc/cls/normal/cmake/FindTensorRT.cmake
  4. 2
      csrc/cls/normal/cmake/Function.cmake
  5. 2
      csrc/detect/end2end/cmake/FindTensorRT.cmake
  6. 2
      csrc/detect/end2end/cmake/Function.cmake
  7. 2
      csrc/detect/normal/cmake/FindTensorRT.cmake
  8. 2
      csrc/detect/normal/cmake/Function.cmake
  9. 2
      csrc/pose/normal/cmake/FindTensorRT.cmake
  10. 2
      csrc/pose/normal/cmake/Function.cmake
  11. 119
      docs/Obb.md
  12. 6
      infer-cls-without-torch.py
  13. 6
      infer-cls.py
  14. 9
      infer-det-without-torch.py
  15. 9
      infer-det.py
  16. 98
      infer-obb-without-torch.py
  17. 94
      infer-obb.py
  18. 19
      models/torch_utils.py
  19. 50
      models/utils.py

4
.gitignore vendored

@ -5,8 +5,11 @@
*.pth
*.onnx
*.jpg
*.jpeg
*.png
*.bmp
*.plan
.clang-format
# Byte-compiled / optimized / DLL files
__pycache__/
@ -19,6 +22,7 @@ __pycache__/
# Distribution / packaging
.Python
build/
cmake-build-debug
develop-eggs/
dist/
downloads/

@ -5,156 +5,232 @@ import numpy as np
random.seed(0)
# classification model classes
CLASSES_CLS = (
['tench', 'goldfish', 'great white shark', 'tiger shark', 'hammerhead shark', 'electric ray', 'stingray', 'cock',
'hen', 'ostrich', 'brambling', 'goldfinch', 'house finch', 'junco', 'indigo bunting', 'American robin', 'bulbul',
'jay', 'magpie', 'chickadee', 'American dipper', 'kite', 'bald eagle', 'vulture', 'great grey owl',
'fire salamander', 'smooth newt', 'newt', 'spotted salamander', 'axolotl', 'American bullfrog', 'tree frog',
'tailed frog', 'loggerhead sea turtle', 'leatherback sea turtle', 'mud turtle', 'terrapin', 'box turtle',
'banded gecko', 'green iguana', 'Carolina anole', 'desert grassland whiptail lizard', 'agama',
'frilled-necked lizard', 'alligator lizard', 'Gila monster', 'European green lizard', 'chameleon', 'Komodo dragon',
'Nile crocodile', 'American alligator', 'triceratops', 'worm snake', 'ring-necked snake',
'eastern hog-nosed snake', 'smooth green snake', 'kingsnake', 'garter snake', 'water snake', 'vine snake',
'night snake', 'boa constrictor', 'African rock python', 'Indian cobra', 'green mamba', 'sea snake',
'Saharan horned viper', 'eastern diamondback rattlesnake', 'sidewinder', 'trilobite', 'harvestman', 'scorpion',
'yellow garden spider', 'barn spider', 'European garden spider', 'southern black widow', 'tarantula',
'wolf spider', 'tick', 'centipede', 'black grouse', 'ptarmigan', 'ruffed grouse', 'prairie grouse', 'peacock',
'quail', 'partridge', 'grey parrot', 'macaw', 'sulphur-crested cockatoo', 'lorikeet', 'coucal', 'bee eater',
'hornbill', 'hummingbird', 'jacamar', 'toucan', 'duck', 'red-breasted merganser', 'goose', 'black swan', 'tusker',
'echidna', 'platypus', 'wallaby', 'koala', 'wombat', 'jellyfish', 'sea anemone', 'brain coral', 'flatworm',
'nematode', 'conch', 'snail', 'slug', 'sea slug', 'chiton', 'chambered nautilus', 'Dungeness crab', 'rock crab',
'fiddler crab', 'red king crab', 'American lobster', 'spiny lobster', 'crayfish', 'hermit crab', 'isopod',
'white stork', 'black stork', 'spoonbill', 'flamingo', 'little blue heron', 'great egret', 'bittern',
'crane (bird)', 'limpkin', 'common gallinule', 'American coot', 'bustard', 'ruddy turnstone', 'dunlin',
'common redshank', 'dowitcher', 'oystercatcher', 'pelican', 'king penguin', 'albatross', 'grey whale',
'killer whale', 'dugong', 'sea lion', 'Chihuahua', 'Japanese Chin', 'Maltese', 'Pekingese', 'Shih Tzu',
'King Charles Spaniel', 'Papillon', 'toy terrier', 'Rhodesian Ridgeback', 'Afghan Hound', 'Basset Hound', 'Beagle',
'Bloodhound', 'Bluetick Coonhound', 'Black and Tan Coonhound', 'Treeing Walker Coonhound', 'English foxhound',
'Redbone Coonhound', 'borzoi', 'Irish Wolfhound', 'Italian Greyhound', 'Whippet', 'Ibizan Hound',
'Norwegian Elkhound', 'Otterhound', 'Saluki', 'Scottish Deerhound', 'Weimaraner', 'Staffordshire Bull Terrier',
'American Staffordshire Terrier', 'Bedlington Terrier', 'Border Terrier', 'Kerry Blue Terrier', 'Irish Terrier',
'Norfolk Terrier', 'Norwich Terrier', 'Yorkshire Terrier', 'Wire Fox Terrier', 'Lakeland Terrier',
'Sealyham Terrier', 'Airedale Terrier', 'Cairn Terrier', 'Australian Terrier', 'Dandie Dinmont Terrier',
'Boston Terrier', 'Miniature Schnauzer', 'Giant Schnauzer', 'Standard Schnauzer', 'Scottish Terrier',
'Tibetan Terrier', 'Australian Silky Terrier', 'Soft-coated Wheaten Terrier', 'West Highland White Terrier',
'Lhasa Apso', 'Flat-Coated Retriever', 'Curly-coated Retriever', 'Golden Retriever', 'Labrador Retriever',
'Chesapeake Bay Retriever', 'German Shorthaired Pointer', 'Vizsla', 'English Setter', 'Irish Setter',
'Gordon Setter', 'Brittany', 'Clumber Spaniel', 'English Springer Spaniel', 'Welsh Springer Spaniel',
'Cocker Spaniels', 'Sussex Spaniel', 'Irish Water Spaniel', 'Kuvasz', 'Schipperke', 'Groenendael', 'Malinois',
'Briard', 'Australian Kelpie', 'Komondor', 'Old English Sheepdog', 'Shetland Sheepdog', 'collie', 'Border Collie',
'Bouvier des Flandres', 'Rottweiler', 'German Shepherd Dog', 'Dobermann', 'Miniature Pinscher',
'Greater Swiss Mountain Dog', 'Bernese Mountain Dog', 'Appenzeller Sennenhund', 'Entlebucher Sennenhund', 'Boxer',
'Bullmastiff', 'Tibetan Mastiff', 'French Bulldog', 'Great Dane', 'St. Bernard', 'husky', 'Alaskan Malamute',
'Siberian Husky', 'Dalmatian', 'Affenpinscher', 'Basenji', 'pug', 'Leonberger', 'Newfoundland',
'Pyrenean Mountain Dog', 'Samoyed', 'Pomeranian', 'Chow Chow', 'Keeshond', 'Griffon Bruxellois',
'Pembroke Welsh Corgi', 'Cardigan Welsh Corgi', 'Toy Poodle', 'Miniature Poodle', 'Standard Poodle',
'Mexican hairless dog', 'grey wolf', 'Alaskan tundra wolf', 'red wolf', 'coyote', 'dingo', 'dhole',
'African wild dog', 'hyena', 'red fox', 'kit fox', 'Arctic fox', 'grey fox', 'tabby cat', 'tiger cat',
'Persian cat', 'Siamese cat', 'Egyptian Mau', 'cougar', 'lynx', 'leopard', 'snow leopard', 'jaguar', 'lion',
'tiger', 'cheetah', 'brown bear', 'American black bear', 'polar bear', 'sloth bear', 'mongoose', 'meerkat',
'tiger beetle', 'ladybug', 'ground beetle', 'longhorn beetle', 'leaf beetle', 'dung beetle', 'rhinoceros beetle',
'weevil', 'fly', 'bee', 'ant', 'grasshopper', 'cricket', 'stick insect', 'cockroach', 'mantis', 'cicada',
'leafhopper', 'lacewing', 'dragonfly', 'damselfly', 'red admiral', 'ringlet', 'monarch butterfly', 'small white',
'sulphur butterfly', 'gossamer-winged butterfly', 'starfish', 'sea urchin', 'sea cucumber', 'cottontail rabbit',
'hare', 'Angora rabbit', 'hamster', 'porcupine', 'fox squirrel', 'marmot', 'beaver', 'guinea pig', 'common sorrel',
'zebra', 'pig', 'wild boar', 'warthog', 'hippopotamus', 'ox', 'water buffalo', 'bison', 'ram', 'bighorn sheep',
'Alpine ibex', 'hartebeest', 'impala', 'gazelle', 'dromedary', 'llama', 'weasel', 'mink', 'European polecat',
'black-footed ferret', 'otter', 'skunk', 'badger', 'armadillo', 'three-toed sloth', 'orangutan', 'gorilla',
'chimpanzee', 'gibbon', 'siamang', 'guenon', 'patas monkey', 'baboon', 'macaque', 'langur',
'black-and-white colobus', 'proboscis monkey', 'marmoset', 'white-headed capuchin', 'howler monkey', 'titi',
"Geoffroy's spider monkey", 'common squirrel monkey', 'ring-tailed lemur', 'indri', 'Asian elephant',
'African bush elephant', 'red panda', 'giant panda', 'snoek', 'eel', 'coho salmon', 'rock beauty', 'clownfish',
'sturgeon', 'garfish', 'lionfish', 'pufferfish', 'abacus', 'abaya', 'academic gown', 'accordion',
'acoustic guitar', 'aircraft carrier', 'airliner', 'airship', 'altar', 'ambulance', 'amphibious vehicle',
'analog clock', 'apiary', 'apron', 'waste container', 'assault rifle', 'backpack', 'bakery', 'balance beam',
'balloon', 'ballpoint pen', 'Band-Aid', 'banjo', 'baluster', 'barbell', 'barber chair', 'barbershop', 'barn',
'barometer', 'barrel', 'wheelbarrow', 'baseball', 'basketball', 'bassinet', 'bassoon', 'swimming cap',
'bath towel', 'bathtub', 'station wagon', 'lighthouse', 'beaker', 'military cap', 'beer bottle', 'beer glass',
'bell-cot', 'bib', 'tandem bicycle', 'bikini', 'ring binder', 'binoculars', 'birdhouse', 'boathouse', 'bobsleigh',
'bolo tie', 'poke bonnet', 'bookcase', 'bookstore', 'bottle cap', 'bow', 'bow tie', 'brass', 'bra', 'breakwater',
'breastplate', 'broom', 'bucket', 'buckle', 'bulletproof vest', 'high-speed train', 'butcher shop', 'taxicab',
'cauldron', 'candle', 'cannon', 'canoe', 'can opener', 'cardigan', 'car mirror', 'carousel', 'tool kit', 'carton',
'car wheel', 'automated teller machine', 'cassette', 'cassette player', 'castle', 'catamaran', 'CD player',
'cello', 'mobile phone', 'chain', 'chain-link fence', 'chain mail', 'chainsaw', 'chest', 'chiffonier', 'chime',
'china cabinet', 'Christmas stocking', 'church', 'movie theater', 'cleaver', 'cliff dwelling', 'cloak', 'clogs',
'cocktail shaker', 'coffee mug', 'coffeemaker', 'coil', 'combination lock', 'computer keyboard',
'confectionery store', 'container ship', 'convertible', 'corkscrew', 'cornet', 'cowboy boot', 'cowboy hat',
'cradle', 'crane (machine)', 'crash helmet', 'crate', 'infant bed', 'Crock Pot', 'croquet ball', 'crutch',
'cuirass', 'dam', 'desk', 'desktop computer', 'rotary dial telephone', 'diaper', 'digital clock', 'digital watch',
'dining table', 'dishcloth', 'dishwasher', 'disc brake', 'dock', 'dog sled', 'dome', 'doormat', 'drilling rig',
'drum', 'drumstick', 'dumbbell', 'Dutch oven', 'electric fan', 'electric guitar', 'electric locomotive',
'entertainment center', 'envelope', 'espresso machine', 'face powder', 'feather boa', 'filing cabinet', 'fireboat',
'fire engine', 'fire screen sheet', 'flagpole', 'flute', 'folding chair', 'football helmet', 'forklift',
'fountain', 'fountain pen', 'four-poster bed', 'freight car', 'French horn', 'frying pan', 'fur coat',
'garbage truck', 'gas mask', 'gas pump', 'goblet', 'go-kart', 'golf ball', 'golf cart', 'gondola', 'gong', 'gown',
'grand piano', 'greenhouse', 'grille', 'grocery store', 'guillotine', 'barrette', 'hair spray', 'half-track',
'hammer', 'hamper', 'hair dryer', 'hand-held computer', 'handkerchief', 'hard disk drive', 'harmonica', 'harp',
'harvester', 'hatchet', 'holster', 'home theater', 'honeycomb', 'hook', 'hoop skirt', 'horizontal bar',
'horse-drawn vehicle', 'hourglass', 'iPod', 'clothes iron', "jack-o'-lantern", 'jeans', 'jeep', 'T-shirt',
'jigsaw puzzle', 'pulled rickshaw', 'joystick', 'kimono', 'knee pad', 'knot', 'lab coat', 'ladle', 'lampshade',
'laptop computer', 'lawn mower', 'lens cap', 'paper knife', 'library', 'lifeboat', 'lighter', 'limousine',
'ocean liner', 'lipstick', 'slip-on shoe', 'lotion', 'speaker', 'loupe', 'sawmill', 'magnetic compass', 'mail bag',
'mailbox', 'tights', 'tank suit', 'manhole cover', 'maraca', 'marimba', 'mask', 'match', 'maypole', 'maze',
'measuring cup', 'medicine chest', 'megalith', 'microphone', 'microwave oven', 'military uniform', 'milk can',
'minibus', 'miniskirt', 'minivan', 'missile', 'mitten', 'mixing bowl', 'mobile home', 'Model T', 'modem',
'monastery', 'monitor', 'moped', 'mortar', 'square academic cap', 'mosque', 'mosquito net', 'scooter',
'mountain bike', 'tent', 'computer mouse', 'mousetrap', 'moving van', 'muzzle', 'nail', 'neck brace', 'necklace',
'nipple', 'notebook computer', 'obelisk', 'oboe', 'ocarina', 'odometer', 'oil filter', 'organ', 'oscilloscope',
'overskirt', 'bullock cart', 'oxygen mask', 'packet', 'paddle', 'paddle wheel', 'padlock', 'paintbrush', 'pajamas',
'palace', 'pan flute', 'paper towel', 'parachute', 'parallel bars', 'park bench', 'parking meter', 'passenger car',
'patio', 'payphone', 'pedestal', 'pencil case', 'pencil sharpener', 'perfume', 'Petri dish', 'photocopier',
'plectrum', 'Pickelhaube', 'picket fence', 'pickup truck', 'pier', 'piggy bank', 'pill bottle', 'pillow',
'ping-pong ball', 'pinwheel', 'pirate ship', 'pitcher', 'hand plane', 'planetarium', 'plastic bag', 'plate rack',
'plow', 'plunger', 'Polaroid camera', 'pole', 'police van', 'poncho', 'billiard table', 'soda bottle', 'pot',
"potter's wheel", 'power drill', 'prayer rug', 'printer', 'prison', 'projectile', 'projector', 'hockey puck',
'punching bag', 'purse', 'quill', 'quilt', 'race car', 'racket', 'radiator', 'radio', 'radio telescope',
'rain barrel', 'recreational vehicle', 'reel', 'reflex camera', 'refrigerator', 'remote control', 'restaurant',
'revolver', 'rifle', 'rocking chair', 'rotisserie', 'eraser', 'rugby ball', 'ruler', 'running shoe', 'safe',
'safety pin', 'salt shaker', 'sandal', 'sarong', 'saxophone', 'scabbard', 'weighing scale', 'school bus',
'schooner', 'scoreboard', 'CRT screen', 'screw', 'screwdriver', 'seat belt', 'sewing machine', 'shield',
'shoe store', 'shoji', 'shopping basket', 'shopping cart', 'shovel', 'shower cap', 'shower curtain', 'ski',
'ski mask', 'sleeping bag', 'slide rule', 'sliding door', 'slot machine', 'snorkel', 'snowmobile', 'snowplow',
'soap dispenser', 'soccer ball', 'sock', 'solar thermal collector', 'sombrero', 'soup bowl', 'space bar',
'space heater', 'space shuttle', 'spatula', 'motorboat', 'spider web', 'spindle', 'sports car', 'spotlight',
'stage', 'steam locomotive', 'through arch bridge', 'steel drum', 'stethoscope', 'scarf', 'stone wall',
'stopwatch', 'stove', 'strainer', 'tram', 'stretcher', 'couch', 'stupa', 'submarine', 'suit', 'sundial',
'sunglass', 'sunglasses', 'sunscreen', 'suspension bridge', 'mop', 'sweatshirt', 'swimsuit', 'swing', 'switch',
'syringe', 'table lamp', 'tank', 'tape player', 'teapot', 'teddy bear', 'television', 'tennis ball',
'thatched roof', 'front curtain', 'thimble', 'threshing machine', 'throne', 'tile roof', 'toaster', 'tobacco shop',
'toilet seat', 'torch', 'totem pole', 'tow truck', 'toy store', 'tractor', 'semi-trailer truck', 'tray',
'trench coat', 'tricycle', 'trimaran', 'tripod', 'triumphal arch', 'trolleybus', 'trombone', 'tub', 'turnstile',
'typewriter keyboard', 'umbrella', 'unicycle', 'upright piano', 'vacuum cleaner', 'vase', 'vault', 'velvet',
'vending machine', 'vestment', 'viaduct', 'violin', 'volleyball', 'waffle iron', 'wall clock', 'wallet',
'wardrobe', 'military aircraft', 'sink', 'washing machine', 'water bottle', 'water jug', 'water tower',
'whiskey jug', 'whistle', 'wig', 'window screen', 'window shade', 'Windsor tie', 'wine bottle', 'wing', 'wok',
'wooden spoon', 'wool', 'split-rail fence', 'shipwreck', 'yawl', 'yurt', 'website', 'comic book', 'crossword',
'traffic sign', 'traffic light', 'dust jacket', 'menu', 'plate', 'guacamole', 'consomme', 'hot pot', 'trifle',
'ice cream', 'ice pop', 'baguette', 'bagel', 'pretzel', 'cheeseburger', 'hot dog', 'mashed potato', 'cabbage',
'broccoli', 'cauliflower', 'zucchini', 'spaghetti squash', 'acorn squash', 'butternut squash', 'cucumber',
'artichoke', 'bell pepper', 'cardoon', 'mushroom', 'Granny Smith', 'strawberry', 'orange', 'lemon', 'fig',
'pineapple', 'banana', 'jackfruit', 'custard apple', 'pomegranate', 'hay', 'carbonara', 'chocolate syrup', 'dough',
'meatloaf', 'pizza', 'pot pie', 'burrito', 'red wine', 'espresso', 'cup', 'eggnog', 'alp', 'bubble', 'cliff',
'coral reef', 'geyser', 'lakeshore', 'promontory', 'shoal', 'seashore', 'valley', 'volcano', 'baseball player',
'bridegroom', 'scuba diver', 'rapeseed', 'daisy', "yellow lady's slipper", 'corn', 'acorn', 'rose hip',
'horse chestnut seed', 'coral fungus', 'agaric', 'gyromitra', 'stinkhorn mushroom', 'earth star',
'hen-of-the-woods', 'bolete', 'ear', 'toilet paper']
)
CLASSES_CLS = ([
'tench', 'goldfish', 'great white shark', 'tiger shark',
'hammerhead shark', 'electric ray', 'stingray', 'cock', 'hen', 'ostrich',
'brambling', 'goldfinch', 'house finch', 'junco', 'indigo bunting',
'American robin', 'bulbul', 'jay', 'magpie', 'chickadee',
'American dipper', 'kite', 'bald eagle', 'vulture', 'great grey owl',
'fire salamander', 'smooth newt', 'newt', 'spotted salamander', 'axolotl',
'American bullfrog', 'tree frog', 'tailed frog', 'loggerhead sea turtle',
'leatherback sea turtle', 'mud turtle', 'terrapin', 'box turtle',
'banded gecko', 'green iguana', 'Carolina anole',
'desert grassland whiptail lizard', 'agama', 'frilled-necked lizard',
'alligator lizard', 'Gila monster', 'European green lizard', 'chameleon',
'Komodo dragon', 'Nile crocodile', 'American alligator', 'triceratops',
'worm snake', 'ring-necked snake', 'eastern hog-nosed snake',
'smooth green snake', 'kingsnake', 'garter snake', 'water snake',
'vine snake', 'night snake', 'boa constrictor', 'African rock python',
'Indian cobra', 'green mamba', 'sea snake', 'Saharan horned viper',
'eastern diamondback rattlesnake', 'sidewinder', 'trilobite', 'harvestman',
'scorpion', 'yellow garden spider', 'barn spider',
'European garden spider', 'southern black widow', 'tarantula',
'wolf spider', 'tick', 'centipede', 'black grouse', 'ptarmigan',
'ruffed grouse', 'prairie grouse', 'peacock', 'quail', 'partridge',
'grey parrot', 'macaw', 'sulphur-crested cockatoo', 'lorikeet', 'coucal',
'bee eater', 'hornbill', 'hummingbird', 'jacamar', 'toucan', 'duck',
'red-breasted merganser', 'goose', 'black swan', 'tusker', 'echidna',
'platypus', 'wallaby', 'koala', 'wombat', 'jellyfish', 'sea anemone',
'brain coral', 'flatworm', 'nematode', 'conch', 'snail', 'slug',
'sea slug', 'chiton', 'chambered nautilus', 'Dungeness crab', 'rock crab',
'fiddler crab', 'red king crab', 'American lobster', 'spiny lobster',
'crayfish', 'hermit crab', 'isopod', 'white stork', 'black stork',
'spoonbill', 'flamingo', 'little blue heron', 'great egret', 'bittern',
'crane (bird)', 'limpkin', 'common gallinule', 'American coot', 'bustard',
'ruddy turnstone', 'dunlin', 'common redshank', 'dowitcher',
'oystercatcher', 'pelican', 'king penguin', 'albatross', 'grey whale',
'killer whale', 'dugong', 'sea lion', 'Chihuahua', 'Japanese Chin',
'Maltese', 'Pekingese', 'Shih Tzu', 'King Charles Spaniel', 'Papillon',
'toy terrier', 'Rhodesian Ridgeback', 'Afghan Hound', 'Basset Hound',
'Beagle', 'Bloodhound', 'Bluetick Coonhound', 'Black and Tan Coonhound',
'Treeing Walker Coonhound', 'English foxhound', 'Redbone Coonhound',
'borzoi', 'Irish Wolfhound', 'Italian Greyhound', 'Whippet',
'Ibizan Hound', 'Norwegian Elkhound', 'Otterhound', 'Saluki',
'Scottish Deerhound', 'Weimaraner', 'Staffordshire Bull Terrier',
'American Staffordshire Terrier', 'Bedlington Terrier', 'Border Terrier',
'Kerry Blue Terrier', 'Irish Terrier', 'Norfolk Terrier',
'Norwich Terrier', 'Yorkshire Terrier', 'Wire Fox Terrier',
'Lakeland Terrier', 'Sealyham Terrier', 'Airedale Terrier',
'Cairn Terrier', 'Australian Terrier', 'Dandie Dinmont Terrier',
'Boston Terrier', 'Miniature Schnauzer', 'Giant Schnauzer',
'Standard Schnauzer', 'Scottish Terrier', 'Tibetan Terrier',
'Australian Silky Terrier', 'Soft-coated Wheaten Terrier',
'West Highland White Terrier', 'Lhasa Apso', 'Flat-Coated Retriever',
'Curly-coated Retriever', 'Golden Retriever', 'Labrador Retriever',
'Chesapeake Bay Retriever', 'German Shorthaired Pointer', 'Vizsla',
'English Setter', 'Irish Setter', 'Gordon Setter', 'Brittany',
'Clumber Spaniel', 'English Springer Spaniel', 'Welsh Springer Spaniel',
'Cocker Spaniels', 'Sussex Spaniel', 'Irish Water Spaniel', 'Kuvasz',
'Schipperke', 'Groenendael', 'Malinois', 'Briard', 'Australian Kelpie',
'Komondor', 'Old English Sheepdog', 'Shetland Sheepdog', 'collie',
'Border Collie', 'Bouvier des Flandres', 'Rottweiler',
'German Shepherd Dog', 'Dobermann', 'Miniature Pinscher',
'Greater Swiss Mountain Dog', 'Bernese Mountain Dog',
'Appenzeller Sennenhund', 'Entlebucher Sennenhund', 'Boxer', 'Bullmastiff',
'Tibetan Mastiff', 'French Bulldog', 'Great Dane', 'St. Bernard', 'husky',
'Alaskan Malamute', 'Siberian Husky', 'Dalmatian', 'Affenpinscher',
'Basenji', 'pug', 'Leonberger', 'Newfoundland', 'Pyrenean Mountain Dog',
'Samoyed', 'Pomeranian', 'Chow Chow', 'Keeshond', 'Griffon Bruxellois',
'Pembroke Welsh Corgi', 'Cardigan Welsh Corgi', 'Toy Poodle',
'Miniature Poodle', 'Standard Poodle', 'Mexican hairless dog', 'grey wolf',
'Alaskan tundra wolf', 'red wolf', 'coyote', 'dingo', 'dhole',
'African wild dog', 'hyena', 'red fox', 'kit fox', 'Arctic fox',
'grey fox', 'tabby cat', 'tiger cat', 'Persian cat', 'Siamese cat',
'Egyptian Mau', 'cougar', 'lynx', 'leopard', 'snow leopard', 'jaguar',
'lion', 'tiger', 'cheetah', 'brown bear', 'American black bear',
'polar bear', 'sloth bear', 'mongoose', 'meerkat', 'tiger beetle',
'ladybug', 'ground beetle', 'longhorn beetle', 'leaf beetle',
'dung beetle', 'rhinoceros beetle', 'weevil', 'fly', 'bee', 'ant',
'grasshopper', 'cricket', 'stick insect', 'cockroach', 'mantis', 'cicada',
'leafhopper', 'lacewing', 'dragonfly', 'damselfly', 'red admiral',
'ringlet', 'monarch butterfly', 'small white', 'sulphur butterfly',
'gossamer-winged butterfly', 'starfish', 'sea urchin', 'sea cucumber',
'cottontail rabbit', 'hare', 'Angora rabbit', 'hamster', 'porcupine',
'fox squirrel', 'marmot', 'beaver', 'guinea pig', 'common sorrel', 'zebra',
'pig', 'wild boar', 'warthog', 'hippopotamus', 'ox', 'water buffalo',
'bison', 'ram', 'bighorn sheep', 'Alpine ibex', 'hartebeest', 'impala',
'gazelle', 'dromedary', 'llama', 'weasel', 'mink', 'European polecat',
'black-footed ferret', 'otter', 'skunk', 'badger', 'armadillo',
'three-toed sloth', 'orangutan', 'gorilla', 'chimpanzee', 'gibbon',
'siamang', 'guenon', 'patas monkey', 'baboon', 'macaque', 'langur',
'black-and-white colobus', 'proboscis monkey', 'marmoset',
'white-headed capuchin', 'howler monkey', 'titi',
"Geoffroy's spider monkey", 'common squirrel monkey', 'ring-tailed lemur',
'indri', 'Asian elephant', 'African bush elephant', 'red panda',
'giant panda', 'snoek', 'eel', 'coho salmon', 'rock beauty', 'clownfish',
'sturgeon', 'garfish', 'lionfish', 'pufferfish', 'abacus', 'abaya',
'academic gown', 'accordion', 'acoustic guitar', 'aircraft carrier',
'airliner', 'airship', 'altar', 'ambulance', 'amphibious vehicle',
'analog clock', 'apiary', 'apron', 'waste container', 'assault rifle',
'backpack', 'bakery', 'balance beam', 'balloon', 'ballpoint pen',
'Band-Aid', 'banjo', 'baluster', 'barbell', 'barber chair', 'barbershop',
'barn', 'barometer', 'barrel', 'wheelbarrow', 'baseball', 'basketball',
'bassinet', 'bassoon', 'swimming cap', 'bath towel', 'bathtub',
'station wagon', 'lighthouse', 'beaker', 'military cap', 'beer bottle',
'beer glass', 'bell-cot', 'bib', 'tandem bicycle', 'bikini', 'ring binder',
'binoculars', 'birdhouse', 'boathouse', 'bobsleigh', 'bolo tie',
'poke bonnet', 'bookcase', 'bookstore', 'bottle cap', 'bow', 'bow tie',
'brass', 'bra', 'breakwater', 'breastplate', 'broom', 'bucket', 'buckle',
'bulletproof vest', 'high-speed train', 'butcher shop', 'taxicab',
'cauldron', 'candle', 'cannon', 'canoe', 'can opener', 'cardigan',
'car mirror', 'carousel', 'tool kit', 'carton', 'car wheel',
'automated teller machine', 'cassette', 'cassette player', 'castle',
'catamaran', 'CD player', 'cello', 'mobile phone', 'chain',
'chain-link fence', 'chain mail', 'chainsaw', 'chest', 'chiffonier',
'chime', 'china cabinet', 'Christmas stocking', 'church', 'movie theater',
'cleaver', 'cliff dwelling', 'cloak', 'clogs', 'cocktail shaker',
'coffee mug', 'coffeemaker', 'coil', 'combination lock',
'computer keyboard', 'confectionery store', 'container ship',
'convertible', 'corkscrew', 'cornet', 'cowboy boot', 'cowboy hat',
'cradle', 'crane (machine)', 'crash helmet', 'crate', 'infant bed',
'Crock Pot', 'croquet ball', 'crutch', 'cuirass', 'dam', 'desk',
'desktop computer', 'rotary dial telephone', 'diaper', 'digital clock',
'digital watch', 'dining table', 'dishcloth', 'dishwasher', 'disc brake',
'dock', 'dog sled', 'dome', 'doormat', 'drilling rig', 'drum', 'drumstick',
'dumbbell', 'Dutch oven', 'electric fan', 'electric guitar',
'electric locomotive', 'entertainment center', 'envelope',
'espresso machine', 'face powder', 'feather boa', 'filing cabinet',
'fireboat', 'fire engine', 'fire screen sheet', 'flagpole', 'flute',
'folding chair', 'football helmet', 'forklift', 'fountain', 'fountain pen',
'four-poster bed', 'freight car', 'French horn', 'frying pan', 'fur coat',
'garbage truck', 'gas mask', 'gas pump', 'goblet', 'go-kart', 'golf ball',
'golf cart', 'gondola', 'gong', 'gown', 'grand piano', 'greenhouse',
'grille', 'grocery store', 'guillotine', 'barrette', 'hair spray',
'half-track', 'hammer', 'hamper', 'hair dryer', 'hand-held computer',
'handkerchief', 'hard disk drive', 'harmonica', 'harp', 'harvester',
'hatchet', 'holster', 'home theater', 'honeycomb', 'hook', 'hoop skirt',
'horizontal bar', 'horse-drawn vehicle', 'hourglass', 'iPod',
'clothes iron', "jack-o'-lantern", 'jeans', 'jeep', 'T-shirt',
'jigsaw puzzle', 'pulled rickshaw', 'joystick', 'kimono', 'knee pad',
'knot', 'lab coat', 'ladle', 'lampshade', 'laptop computer', 'lawn mower',
'lens cap', 'paper knife', 'library', 'lifeboat', 'lighter', 'limousine',
'ocean liner', 'lipstick', 'slip-on shoe', 'lotion', 'speaker', 'loupe',
'sawmill', 'magnetic compass', 'mail bag', 'mailbox', 'tights',
'tank suit', 'manhole cover', 'maraca', 'marimba', 'mask', 'match',
'maypole', 'maze', 'measuring cup', 'medicine chest', 'megalith',
'microphone', 'microwave oven', 'military uniform', 'milk can', 'minibus',
'miniskirt', 'minivan', 'missile', 'mitten', 'mixing bowl', 'mobile home',
'Model T', 'modem', 'monastery', 'monitor', 'moped', 'mortar',
'square academic cap', 'mosque', 'mosquito net', 'scooter',
'mountain bike', 'tent', 'computer mouse', 'mousetrap', 'moving van',
'muzzle', 'nail', 'neck brace', 'necklace', 'nipple', 'notebook computer',
'obelisk', 'oboe', 'ocarina', 'odometer', 'oil filter', 'organ',
'oscilloscope', 'overskirt', 'bullock cart', 'oxygen mask', 'packet',
'paddle', 'paddle wheel', 'padlock', 'paintbrush', 'pajamas', 'palace',
'pan flute', 'paper towel', 'parachute', 'parallel bars', 'park bench',
'parking meter', 'passenger car', 'patio', 'payphone', 'pedestal',
'pencil case', 'pencil sharpener', 'perfume', 'Petri dish', 'photocopier',
'plectrum', 'Pickelhaube', 'picket fence', 'pickup truck', 'pier',
'piggy bank', 'pill bottle', 'pillow', 'ping-pong ball', 'pinwheel',
'pirate ship', 'pitcher', 'hand plane', 'planetarium', 'plastic bag',
'plate rack', 'plow', 'plunger', 'Polaroid camera', 'pole', 'police van',
'poncho', 'billiard table', 'soda bottle', 'pot', "potter's wheel",
'power drill', 'prayer rug', 'printer', 'prison', 'projectile',
'projector', 'hockey puck', 'punching bag', 'purse', 'quill', 'quilt',
'race car', 'racket', 'radiator', 'radio', 'radio telescope',
'rain barrel', 'recreational vehicle', 'reel', 'reflex camera',
'refrigerator', 'remote control', 'restaurant', 'revolver', 'rifle',
'rocking chair', 'rotisserie', 'eraser', 'rugby ball', 'ruler',
'running shoe', 'safe', 'safety pin', 'salt shaker', 'sandal', 'sarong',
'saxophone', 'scabbard', 'weighing scale', 'school bus', 'schooner',
'scoreboard', 'CRT screen', 'screw', 'screwdriver', 'seat belt',
'sewing machine', 'shield', 'shoe store', 'shoji', 'shopping basket',
'shopping cart', 'shovel', 'shower cap', 'shower curtain', 'ski',
'ski mask', 'sleeping bag', 'slide rule', 'sliding door', 'slot machine',
'snorkel', 'snowmobile', 'snowplow', 'soap dispenser', 'soccer ball',
'sock', 'solar thermal collector', 'sombrero', 'soup bowl', 'space bar',
'space heater', 'space shuttle', 'spatula', 'motorboat', 'spider web',
'spindle', 'sports car', 'spotlight', 'stage', 'steam locomotive',
'through arch bridge', 'steel drum', 'stethoscope', 'scarf', 'stone wall',
'stopwatch', 'stove', 'strainer', 'tram', 'stretcher', 'couch', 'stupa',
'submarine', 'suit', 'sundial', 'sunglass', 'sunglasses', 'sunscreen',
'suspension bridge', 'mop', 'sweatshirt', 'swimsuit', 'swing', 'switch',
'syringe', 'table lamp', 'tank', 'tape player', 'teapot', 'teddy bear',
'television', 'tennis ball', 'thatched roof', 'front curtain', 'thimble',
'threshing machine', 'throne', 'tile roof', 'toaster', 'tobacco shop',
'toilet seat', 'torch', 'totem pole', 'tow truck', 'toy store', 'tractor',
'semi-trailer truck', 'tray', 'trench coat', 'tricycle', 'trimaran',
'tripod', 'triumphal arch', 'trolleybus', 'trombone', 'tub', 'turnstile',
'typewriter keyboard', 'umbrella', 'unicycle', 'upright piano',
'vacuum cleaner', 'vase', 'vault', 'velvet', 'vending machine', 'vestment',
'viaduct', 'violin', 'volleyball', 'waffle iron', 'wall clock', 'wallet',
'wardrobe', 'military aircraft', 'sink', 'washing machine', 'water bottle',
'water jug', 'water tower', 'whiskey jug', 'whistle', 'wig',
'window screen', 'window shade', 'Windsor tie', 'wine bottle', 'wing',
'wok', 'wooden spoon', 'wool', 'split-rail fence', 'shipwreck', 'yawl',
'yurt', 'website', 'comic book', 'crossword', 'traffic sign',
'traffic light', 'dust jacket', 'menu', 'plate', 'guacamole', 'consomme',
'hot pot', 'trifle', 'ice cream', 'ice pop', 'baguette', 'bagel',
'pretzel', 'cheeseburger', 'hot dog', 'mashed potato', 'cabbage',
'broccoli', 'cauliflower', 'zucchini', 'spaghetti squash', 'acorn squash',
'butternut squash', 'cucumber', 'artichoke', 'bell pepper', 'cardoon',
'mushroom', 'Granny Smith', 'strawberry', 'orange', 'lemon', 'fig',
'pineapple', 'banana', 'jackfruit', 'custard apple', 'pomegranate', 'hay',
'carbonara', 'chocolate syrup', 'dough', 'meatloaf', 'pizza', 'pot pie',
'burrito', 'red wine', 'espresso', 'cup', 'eggnog', 'alp', 'bubble',
'cliff', 'coral reef', 'geyser', 'lakeshore', 'promontory', 'shoal',
'seashore', 'valley', 'volcano', 'baseball player', 'bridegroom',
'scuba diver', 'rapeseed', 'daisy', "yellow lady's slipper", 'corn',
'acorn', 'rose hip', 'horse chestnut seed', 'coral fungus', 'agaric',
'gyromitra', 'stinkhorn mushroom', 'earth star', 'hen-of-the-woods',
'bolete', 'ear', 'toilet paper'
])
# detection model classes
CLASSES_DET = ('person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus',
'train', 'truck', 'boat', 'traffic light', 'fire hydrant',
'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog',
'horse', 'sheep', 'cow', 'elephant', 'bear', 'zebra', 'giraffe',
'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee',
'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat',
'baseball glove', 'skateboard', 'surfboard', 'tennis racket',
'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl',
'banana', 'apple', 'sandwich', 'orange', 'broccoli', 'carrot',
'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch',
'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop',
'mouse', 'remote', 'keyboard', 'cell phone', 'microwave', 'oven',
'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase',
'scissors', 'teddy bear', 'hair drier', 'toothbrush')
'train', 'truck', 'boat', 'traffic light', 'fire hydrant',
'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog',
'horse', 'sheep', 'cow', 'elephant', 'bear', 'zebra', 'giraffe',
'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee',
'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat',
'baseball glove', 'skateboard', 'surfboard', 'tennis racket',
'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl',
'banana', 'apple', 'sandwich', 'orange', 'broccoli', 'carrot',
'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch',
'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop',
'mouse', 'remote', 'keyboard', 'cell phone', 'microwave',
'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock',
'vase', 'scissors', 'teddy bear', 'hair drier', 'toothbrush')
# colors for per classes
COLORS = {
@ -192,3 +268,16 @@ LIMB_COLORS = [[51, 153, 255], [51, 153, 255], [51, 153, 255], [51, 153, 255],
# alpha for segment masks
ALPHA = 0.5
# obb model classes
CLASSES_OBB = ('plane', 'ship', 'storage tank', 'baseball diamond',
'tennis court', 'basketball court', 'ground track field',
'harbor', 'bridge', 'large vehicle', 'small vehicle',
'helicopter', 'roundabout', 'soccer ball field',
'swimming pool')
# colors for obb classes
COLORS_OBB = {
cls: [random.randint(0, 255) for _ in range(3)]
for i, cls in enumerate(CLASSES_OBB)
}

@ -135,4 +135,4 @@ if(TensorRT_FOUND)
endif()
target_link_libraries(TensorRT INTERFACE TensorRT::nvinfer_plugin)
endif()
endif()
endif()

@ -11,4 +11,4 @@ function(print_var var)
set(value "${value}\n")
endif()
message(STATUS "${var}:\n ${value}")
endfunction()
endfunction()

@ -135,4 +135,4 @@ if(TensorRT_FOUND)
endif()
target_link_libraries(TensorRT INTERFACE TensorRT::nvinfer_plugin)
endif()
endif()
endif()

@ -11,4 +11,4 @@ function(print_var var)
set(value "${value}\n")
endif()
message(STATUS "${var}:\n ${value}")
endfunction()
endfunction()

@ -135,4 +135,4 @@ if(TensorRT_FOUND)
endif()
target_link_libraries(TensorRT INTERFACE TensorRT::nvinfer_plugin)
endif()
endif()
endif()

@ -11,4 +11,4 @@ function(print_var var)
set(value "${value}\n")
endif()
message(STATUS "${var}:\n ${value}")
endfunction()
endfunction()

@ -135,4 +135,4 @@ if(TensorRT_FOUND)
endif()
target_link_libraries(TensorRT INTERFACE TensorRT::nvinfer_plugin)
endif()
endif()
endif()

@ -11,4 +11,4 @@ function(print_var var)
set(value "${value}\n")
endif()
message(STATUS "${var}:\n ${value}")
endfunction()
endfunction()

@ -0,0 +1,119 @@
# YOLOv8-obb Model with TensorRT
The yolov8-obb model conversion route is :
YOLOv8 PyTorch model -> ONNX -> TensorRT Engine
***Notice !!!*** We don't support TensorRT API building !!!
# Export Orin ONNX model by ultralytics
You can leave this repo and use the original `ultralytics` repo for onnx export.
### 1. ONNX -> TensorRT
You can export your onnx model by `ultralytics` API.
``` shell
yolo export model=yolov8s-obb.pt format=onnx opset=11 simplify=True
```
or run this python script:
```python
from ultralytics import YOLO
# Load a model
model = YOLO("yolov8s-obb.pt") # load a pretrained model (recommended for training)
success = model.export(format="onnx", opset=11, simplify=True) # export the model to onnx format
assert success
```
Then build engine by Trtexec Tools.
You can export TensorRT engine by [`trtexec`](https://github.com/NVIDIA/TensorRT/tree/main/samples/trtexec) tools.
Usage:
``` shell
/usr/src/tensorrt/bin/trtexec \
--onnx=yolov8s-obb.onnx \
--saveEngine=yolov8s-obb.engine \
--fp16
```
### 2. Direct to TensorRT (NOT RECOMMAND!!)
Usage:
```shell
yolo export model=yolov8s-obb.pt format=engine device=0
```
or run python script:
```python
from ultralytics import YOLO
# Load a model
model = YOLO("yolov8s-obb.pt") # load a pretrained model (recommended for training)
success = model.export(format="engine", device=0) # export the model to engine format
assert success
```
After executing the above script, you will get an engine named `yolov8s-obb.engine` .
# Inference
## Infer with python script
You can infer images with the engine by [`infer-obb.py`](../infer-obb.py) .
Usage:
``` shell
python3 infer-obb.py \
--engine yolov8s-obb.engine \
--imgs data \
--show \
--out-dir outputs \
--device cuda:0
```
#### Description of all arguments
- `--engine` : The Engine you export.
- `--imgs` : The images path you want to detect.
- `--show` : Whether to show detection results.
- `--out-dir` : Where to save detection results images. It will not work when use `--show` flag.
- `--device` : The CUDA deivce you use.
## Inference with c++ (Under Construction)
You can infer with c++ in [`csrc/obb/normal`](../csrc/obb/normal) .
### Build:
Please set you own librarys in [`CMakeLists.txt`](../csrc/obb/normal/CMakeLists.txt) and modify `CLASS_NAMES` in [`main.cpp`](../csrc/obb/normal/main.cpp).
And build:
``` shell
export root=${PWD}
cd src/obb/normal
mkdir build
cmake ..
make
mv yolov8-obb ${root}
cd ${root}
```
Usage:
``` shell
# infer image
./yolov8-obb yolov8s-obb.engine data/bus.jpg
# infer images
./yolov8-obb yolov8s-obb.engine data
# infer video
./yolov8-obb yolov8s-obb.engine data/test.mp4 # the video path
```

@ -45,8 +45,10 @@ def main(args: argparse.Namespace) -> None:
(_w, _h), _bl = cv2.getTextSize(text, cv2.FONT_HERSHEY_SIMPLEX, 0.8, 1)
_y1 = min(10, draw.shape[0])
cv2.rectangle(draw, (10, _y1), (10 + _w, _y1 + _h + _bl), (0, 0, 255), -1)
cv2.putText(draw, text, (10, _y1 + _h), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (255, 255, 255), 2)
cv2.rectangle(draw, (10, _y1), (10 + _w, _y1 + _h + _bl), (0, 0, 255),
-1)
cv2.putText(draw, text, (10, _y1 + _h), cv2.FONT_HERSHEY_SIMPLEX, 0.75,
(255, 255, 255), 2)
if args.show:
cv2.imshow('result', draw)

@ -40,8 +40,10 @@ def main(args: argparse.Namespace) -> None:
(_w, _h), _bl = cv2.getTextSize(text, cv2.FONT_HERSHEY_SIMPLEX, 0.8, 1)
_y1 = min(10, draw.shape[0])
cv2.rectangle(draw, (10, _y1), (10 + _w, _y1 + _h + _bl), (0, 0, 255), -1)
cv2.putText(draw, text, (10, _y1 + _h), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (255, 255, 255), 2)
cv2.rectangle(draw, (10, _y1), (10 + _w, _y1 + _h + _bl), (0, 0, 255),
-1)
cv2.putText(draw, text, (10, _y1 + _h), cv2.FONT_HERSHEY_SIMPLEX, 0.75,
(255, 255, 255), 2)
if args.show:
cv2.imshow('result', draw)

@ -54,12 +54,15 @@ def main(args: argparse.Namespace) -> None:
text = f'{cls}:{score:.3f}'
x1, y1, x2, y2 = bbox
(_w, _h), _bl = cv2.getTextSize(text, cv2.FONT_HERSHEY_SIMPLEX, 0.8, 1)
(_w, _h), _bl = cv2.getTextSize(text, cv2.FONT_HERSHEY_SIMPLEX,
0.8, 1)
_y1 = min(y1 + 1, draw.shape[0])
cv2.rectangle(draw, (x1, y1), (x2, y2), color, 2)
cv2.rectangle(draw, (x1, _y1), (x1 + _w, _y1 + _h + _bl), (0, 0, 255), -1)
cv2.putText(draw, text, (x1, _y1 + _h), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (255, 255, 255), 2)
cv2.rectangle(draw, (x1, _y1), (x1 + _w, _y1 + _h + _bl),
(0, 0, 255), -1)
cv2.putText(draw, text, (x1, _y1 + _h), cv2.FONT_HERSHEY_SIMPLEX,
0.75, (255, 255, 255), 2)
if args.show:
cv2.imshow('result', draw)

@ -53,12 +53,15 @@ def main(args: argparse.Namespace) -> None:
text = f'{cls}:{score:.3f}'
x1, y1, x2, y2 = bbox
(_w, _h), _bl = cv2.getTextSize(text, cv2.FONT_HERSHEY_SIMPLEX, 0.8, 1)
(_w, _h), _bl = cv2.getTextSize(text, cv2.FONT_HERSHEY_SIMPLEX,
0.8, 1)
_y1 = min(y1 + 1, draw.shape[0])
cv2.rectangle(draw, (x1, y1), (x2, y2), color, 2)
cv2.rectangle(draw, (x1, _y1), (x1 + _w, _y1 + _h + _bl), (0, 0, 255), -1)
cv2.putText(draw, text, (x1, _y1 + _h), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (255, 255, 255), 2)
cv2.rectangle(draw, (x1, _y1), (x1 + _w, _y1 + _h + _bl),
(0, 0, 255), -1)
cv2.putText(draw, text, (x1, _y1 + _h), cv2.FONT_HERSHEY_SIMPLEX,
0.75, (255, 255, 255), 2)
if args.show:
cv2.imshow('result', draw)

@ -0,0 +1,98 @@
import argparse
from pathlib import Path
import cv2
import numpy as np
from config import CLASSES_OBB, COLORS_OBB
from models.utils import blob, letterbox, obb_postprocess, path_to_list
def main(args: argparse.Namespace) -> None:
if args.method == 'cudart':
from models.cudart_api import TRTEngine
elif args.method == 'pycuda':
from models.pycuda_api import TRTEngine
else:
raise NotImplementedError
Engine = TRTEngine(args.engine)
H, W = Engine.inp_info[0].shape[-2:]
images = path_to_list(args.imgs)
save_path = Path(args.out_dir)
if not args.show and not save_path.exists():
save_path.mkdir(parents=True, exist_ok=True)
for image in images:
save_image = save_path / image.name
bgr = cv2.imread(str(image))
draw = bgr.copy()
bgr, ratio, dwdh = letterbox(bgr, (W, H))
rgb = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)
tensor = blob(rgb, return_seg=False)
dwdh = np.array(dwdh, dtype=np.float32)
tensor = np.ascontiguousarray(tensor)
# inference
data = Engine(tensor)
points, scores, labels = obb_postprocess(data, args.conf_thres,
args.iou_thres)
if points.size == 0:
# if no points
print(f'{image}: no object!')
continue
points -= dwdh
points /= ratio
for (point, score, label) in zip(points, scores, labels):
point = point.round().astype(np.int32)
label = int(label)
score = float(score)
cls = CLASSES_OBB[label]
color = COLORS_OBB[cls]
cv2.polylines(draw, [point], True, color, 2)
cv2.putText(draw,
f'{cls}:{score:.3f}', (point[0, 0], point[0, 1] - 2),
cv2.FONT_HERSHEY_SIMPLEX,
0.75, [225, 255, 255],
thickness=2)
if args.show:
cv2.imshow('result', draw)
cv2.waitKey(0)
else:
cv2.imwrite(str(save_image), draw)
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--engine', type=str, help='Engine file')
parser.add_argument('--imgs', type=str, help='Images file')
parser.add_argument('--show',
action='store_true',
help='Show the detection results')
parser.add_argument('--out-dir',
type=str,
default='./output',
help='Path to output file')
parser.add_argument('--conf-thres',
type=float,
default=0.25,
help='Confidence threshold')
parser.add_argument('--iou-thres',
type=float,
default=0.65,
help='Confidence threshold')
parser.add_argument('--method',
type=str,
default='cudart',
help='CUDART pipeline')
args = parser.parse_args()
return args
if __name__ == '__main__':
args = parse_args()
main(args)

@ -0,0 +1,94 @@
from models import TRTModule # isort:skip
import argparse
from pathlib import Path
import cv2
import torch
from config import CLASSES_OBB, COLORS_OBB
from models.torch_utils import obb_postprocess
from models.utils import blob, letterbox, path_to_list
def main(args: argparse.Namespace) -> None:
device = torch.device(args.device)
Engine = TRTModule(args.engine, device)
H, W = Engine.inp_info[0].shape[-2:]
images = path_to_list(args.imgs)
save_path = Path(args.out_dir)
if not args.show and not save_path.exists():
save_path.mkdir(parents=True, exist_ok=True)
for image in images:
save_image = save_path / image.name
bgr = cv2.imread(str(image))
draw = bgr.copy()
bgr, ratio, dwdh = letterbox(bgr, (W, H))
rgb = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)
tensor = blob(rgb, return_seg=False)
dwdh = torch.asarray(dwdh, dtype=torch.float32, device=device)
tensor = torch.asarray(tensor, device=device)
# inference
data = Engine(tensor)
points, scores, labels = obb_postprocess(data, args.conf_thres,
args.iou_thres)
if points.numel() == 0:
# if no points
print(f'{image}: no object!')
continue
points -= dwdh
points /= ratio
for (point, score, label) in zip(points, scores, labels):
point = point.round().int().cpu().numpy()
label = int(label)
score = float(score)
cls = CLASSES_OBB[label]
color = COLORS_OBB[cls]
cv2.polylines(draw, [point], True, color, 2)
cv2.putText(draw,
f'{cls}:{score:.3f}', (point[0, 0], point[0, 1] - 2),
cv2.FONT_HERSHEY_SIMPLEX,
0.75, [225, 255, 255],
thickness=2)
if args.show:
cv2.imshow('result', draw)
cv2.waitKey(0)
else:
cv2.imwrite(str(save_image), draw)
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser()
parser.add_argument('--engine', type=str, help='Engine file')
parser.add_argument('--imgs', type=str, help='Images file')
parser.add_argument('--show',
action='store_true',
help='Show the detection results')
parser.add_argument('--out-dir',
type=str,
default='./output',
help='Path to output file')
parser.add_argument('--conf-thres',
type=float,
default=0.25,
help='Confidence threshold')
parser.add_argument('--iou-thres',
type=float,
default=0.65,
help='Confidence threshold')
parser.add_argument('--device',
type=str,
default='cuda:0',
help='TensorRT infer device')
args = parser.parse_args()
return args
if __name__ == '__main__':
args = parse_args()
main(args)

@ -5,6 +5,8 @@ import torch.nn.functional as F
from torch import Tensor
from torchvision.ops import batched_nms, nms
from .utils import obb_postprocess as np_obb_postprocess
def seg_postprocess(
data: Tuple[Tensor],
@ -61,7 +63,7 @@ def pose_postprocess(
def det_postprocess(data: Tuple[Tensor, Tensor, Tensor, Tensor]):
assert len(data) == 4
iou_thres: float = 0.65
iou_thres: float = 0.65 # noqa F841
num_dets, bboxes, scores, labels = data[0][0], data[1][0], data[2][
0], data[3][0]
nums = num_dets.item()
@ -77,6 +79,21 @@ def det_postprocess(data: Tuple[Tensor, Tensor, Tensor, Tensor]):
return bboxes, scores, labels
def obb_postprocess(
data: Union[Tuple, Tensor],
conf_thres: float = 0.25,
iou_thres: float = 0.65) \
-> Tuple[Tensor, Tensor, Tensor]:
if isinstance(data, tuple):
assert len(data) == 1
data = data[0]
device = data.device
points, scores, labels = np_obb_postprocess(data.cpu().numpy(), conf_thres,
iou_thres)
return torch.from_numpy(points).to(device), torch.from_numpy(scores).to(
device), torch.from_numpy(labels).to(device)
def crop_mask(masks: Tensor, bboxes: Tensor) -> Tensor:
n, h, w = masks.shape
x1, y1, x2, y2 = torch.chunk(bboxes[:, :, None], 4, 1) # x1 shape(1,1,n)

@ -9,6 +9,9 @@ from numpy import ndarray
SUFFIXS = ('.bmp', '.dng', '.jpeg', '.jpg', '.mpo', '.png', '.tif', '.tiff',
'.webp', '.pfm')
# angle scale
ANGLE_SCALE = 1 / np.pi * 180.0
def letterbox(im: ndarray,
new_shape: Union[Tuple, List] = (640, 640),
@ -93,17 +96,16 @@ def box_iou(box1: ndarray, box2: ndarray) -> float:
x2 = min(x21, x22)
y2 = min(y21, y22)
inter_area = max(0, x2 - x1) * max(0, y2 - y1)
union_area = (x21 - x11) * (y21 - y11) + (x22 - x12) * (y22 - y12) - inter_area
union_area = (x21 - x11) * (y21 - y11) + (x22 - x12) * (y22 -
y12) - inter_area
return max(0, inter_area / union_area)
def NMSBoxes(
boxes: ndarray,
scores: ndarray,
labels: ndarray,
iou_thres: float,
agnostic: bool = False
):
def NMSBoxes(boxes: ndarray,
scores: ndarray,
labels: ndarray,
iou_thres: float,
agnostic: bool = False):
num_boxes = boxes.shape[0]
order = np.argsort(scores)[::-1]
boxes = boxes[order]
@ -135,7 +137,7 @@ def det_postprocess(data: Tuple[ndarray, ndarray, ndarray, ndarray]):
nums = num_dets.item()
if nums == 0:
return np.empty((0, 4), dtype=np.float32), np.empty(
(0,), dtype=np.float32), np.empty((0,), dtype=np.int32)
(0, ), dtype=np.float32), np.empty((0, ), dtype=np.int32)
# check score negative
scores[scores < 0] = 1 + scores[scores < 0]
bboxes = bboxes[:nums]
@ -200,7 +202,7 @@ def pose_postprocess(
idx = scores > conf_thres
if not idx.any(): # no bounding boxes or seg were created
return np.empty((0, 4), dtype=np.float32), np.empty(
(0,), dtype=np.float32), np.empty((0, 0, 0), dtype=np.float32)
(0, ), dtype=np.float32), np.empty((0, 0, 0), dtype=np.float32)
bboxes, scores, kpts = bboxes[idx], scores[idx], kpts[idx]
xycenter, wh = np.split(bboxes, [
2,
@ -210,3 +212,31 @@ def pose_postprocess(
cvbboxes, scores, kpts = cvbboxes[idx], scores[idx], kpts[idx]
cvbboxes[:, 2:] += cvbboxes[:, :2]
return cvbboxes, scores, kpts.reshape(idx.shape[0], -1, 3)
def obb_postprocess(
data: Union[Tuple, ndarray],
conf_thres: float = 0.25,
iou_thres: float = 0.65) \
-> Tuple[ndarray, ndarray, ndarray]:
if isinstance(data, tuple):
assert len(data) == 1
data = data[0]
outputs = np.transpose(data[0], (1, 0))
num_cls = outputs.shape[-1] - 5
bboxes, scores, angles = np.split(outputs, [4, num_cls + 4], 1)
scores, labels = scores.max(-1), scores.argmax(-1)
scores, labels, angles = scores.squeeze(), labels.squeeze(
), angles.squeeze()
idx = scores > conf_thres
if not idx.any(): # no obbs were created
return np.empty((0, 4, 2), dtype=np.float32), np.empty(
(0, ), dtype=np.float32), np.empty((0, ), dtype=np.int32)
bboxes, scores, labels, angles = bboxes[idx], scores[idx], labels[
idx], angles[idx] * ANGLE_SCALE
cvrbboxes = [[(xc, yc), (w, h), a]
for (xc, yc, w, h), a in zip(bboxes, angles)]
idx = cv2.dnn.NMSBoxesRotated(cvrbboxes, scores, conf_thres, iou_thres)
points = np.array([cv2.boxPoints(cvrbboxes[i]) for i in idx],
dtype=np.float32)
return points, scores, labels

Loading…
Cancel
Save