├── .gitignore ├── LICENSE ├── README.md ├── images ├── demo.jpg ├── imagenet1k_label_list.txt └── n01440764_9780.JPEG ├── pp_lcnet.py ├── pretrained_models └── README.md ├── pytorch_lcnet.py ├── requirements.txt └── utils.py /.gitignore: -------------------------------------------------------------------------------- 1 | .vscode 2 | __pycache__/ 3 | *.pyc -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | #### 2021-11-11 update 2 | - 添加基于pytorch的推理代码,并可以得到正确结果 3 | - 结果示例: 4 | ```python 5 | # 运行pp_lcnet.py 6 | python pp_lcnet.py 7 | 8 | # 结果: 9 | # 0 tench, Tinca tinca: 0.9202795624732971 10 | 11 | # 运行pytorch_lcnet.py 12 | python pytorch_lcnet.py 13 | 14 | # 结果: 15 | # 0 tench, Tinca tinca: 0.9877434968948364 16 | ``` 17 | 18 | #### 2021-11-10 update 19 | - 基于paddlepaddle框架可以正确推理,并得到正确结果 20 | 21 | #### 2021-11-05 update 22 | - 整个PP-LCNet跑通,可以正常跑 23 | 24 | #### 参考资料 25 | - [ngnquan/PP-LCNet](https://github.com/ngnquan/PP-LCNet) 26 | - [frotms/PP-LCNet-Pytorch](https://github.com/frotms/PP-LCNet-Pytorch) -------------------------------------------------------------------------------- /images/demo.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SWHL/PPLCNet2PyTorch/ed6abf9c5af25c163bc27e0eaada4516889bd925/images/demo.jpg -------------------------------------------------------------------------------- /images/imagenet1k_label_list.txt: -------------------------------------------------------------------------------- 1 | 0 tench, Tinca tinca 2 | 1 goldfish, Carassius auratus 3 | 2 great white shark, white shark, man-eater, man-eating shark, Carcharodon carcharias 4 | 3 tiger shark, Galeocerdo cuvieri 5 | 4 hammerhead, hammerhead shark 6 | 5 electric ray, crampfish, numbfish, torpedo 7 | 6 stingray 8 | 7 cock 9 | 8 hen 10 | 9 ostrich, Struthio camelus 11 | 10 brambling, Fringilla montifringilla 12 | 11 goldfinch, Carduelis carduelis 13 | 12 house finch, linnet, Carpodacus mexicanus 14 | 13 junco, snowbird 15 | 14 indigo bunting, indigo finch, indigo bird, Passerina cyanea 16 | 15 robin, American robin, Turdus migratorius 17 | 16 bulbul 18 | 17 jay 19 | 18 magpie 20 | 19 chickadee 21 | 20 water ouzel, dipper 22 | 21 kite 23 | 22 bald eagle, American eagle, Haliaeetus leucocephalus 24 | 23 vulture 25 | 24 great grey owl, great gray owl, Strix nebulosa 26 | 25 European fire salamander, Salamandra salamandra 27 | 26 common newt, Triturus vulgaris 28 | 27 eft 29 | 28 spotted salamander, Ambystoma maculatum 30 | 29 axolotl, mud puppy, Ambystoma mexicanum 31 | 30 bullfrog, Rana catesbeiana 32 | 31 tree frog, tree-frog 33 | 32 tailed frog, bell toad, ribbed toad, tailed toad, Ascaphus trui 34 | 33 loggerhead, loggerhead turtle, Caretta caretta 35 | 34 leatherback turtle, leatherback, leathery turtle, Dermochelys coriacea 36 | 35 mud turtle 37 | 36 terrapin 38 | 37 box turtle, box tortoise 39 | 38 banded gecko 40 | 39 common iguana, iguana, Iguana iguana 41 | 40 American chameleon, anole, Anolis carolinensis 42 | 41 whiptail, whiptail lizard 43 | 42 agama 44 | 43 frilled lizard, Chlamydosaurus kingi 45 | 44 alligator lizard 46 | 45 Gila monster, Heloderma suspectum 47 | 46 green lizard, Lacerta viridis 48 | 47 African chameleon, Chamaeleo chamaeleon 49 | 48 Komodo dragon, Komodo lizard, dragon lizard, giant lizard, Varanus komodoensis 50 | 49 African crocodile, Nile crocodile, Crocodylus niloticus 51 | 50 American alligator, Alligator mississipiensis 52 | 51 triceratops 53 | 52 thunder snake, worm snake, Carphophis amoenus 54 | 53 ringneck snake, ring-necked snake, ring snake 55 | 54 hognose snake, puff adder, sand viper 56 | 55 green snake, grass snake 57 | 56 king snake, kingsnake 58 | 57 garter snake, grass snake 59 | 58 water snake 60 | 59 vine snake 61 | 60 night snake, Hypsiglena torquata 62 | 61 boa constrictor, Constrictor constrictor 63 | 62 rock python, rock snake, Python sebae 64 | 63 Indian cobra, Naja naja 65 | 64 green mamba 66 | 65 sea snake 67 | 66 horned viper, cerastes, sand viper, horned asp, Cerastes cornutus 68 | 67 diamondback, diamondback rattlesnake, Crotalus adamanteus 69 | 68 sidewinder, horned rattlesnake, Crotalus cerastes 70 | 69 trilobite 71 | 70 harvestman, daddy longlegs, Phalangium opilio 72 | 71 scorpion 73 | 72 black and gold garden spider, Argiope aurantia 74 | 73 barn spider, Araneus cavaticus 75 | 74 garden spider, Aranea diademata 76 | 75 black widow, Latrodectus mactans 77 | 76 tarantula 78 | 77 wolf spider, hunting spider 79 | 78 tick 80 | 79 centipede 81 | 80 black grouse 82 | 81 ptarmigan 83 | 82 ruffed grouse, partridge, Bonasa umbellus 84 | 83 prairie chicken, prairie grouse, prairie fowl 85 | 84 peacock 86 | 85 quail 87 | 86 partridge 88 | 87 African grey, African gray, Psittacus erithacus 89 | 88 macaw 90 | 89 sulphur-crested cockatoo, Kakatoe galerita, Cacatua galerita 91 | 90 lorikeet 92 | 91 coucal 93 | 92 bee eater 94 | 93 hornbill 95 | 94 hummingbird 96 | 95 jacamar 97 | 96 toucan 98 | 97 drake 99 | 98 red-breasted merganser, Mergus serrator 100 | 99 goose 101 | 100 black swan, Cygnus atratus 102 | 101 tusker 103 | 102 echidna, spiny anteater, anteater 104 | 103 platypus, duckbill, duckbilled platypus, duck-billed platypus, Ornithorhynchus anatinus 105 | 104 wallaby, brush kangaroo 106 | 105 koala, koala bear, kangaroo bear, native bear, Phascolarctos cinereus 107 | 106 wombat 108 | 107 jellyfish 109 | 108 sea anemone, anemone 110 | 109 brain coral 111 | 110 flatworm, platyhelminth 112 | 111 nematode, nematode worm, roundworm 113 | 112 conch 114 | 113 snail 115 | 114 slug 116 | 115 sea slug, nudibranch 117 | 116 chiton, coat-of-mail shell, sea cradle, polyplacophore 118 | 117 chambered nautilus, pearly nautilus, nautilus 119 | 118 Dungeness crab, Cancer magister 120 | 119 rock crab, Cancer irroratus 121 | 120 fiddler crab 122 | 121 king crab, Alaska crab, Alaskan king crab, Alaska king crab, Paralithodes camtschatica 123 | 122 American lobster, Northern lobster, Maine lobster, Homarus americanus 124 | 123 spiny lobster, langouste, rock lobster, crawfish, crayfish, sea crawfish 125 | 124 crayfish, crawfish, crawdad, crawdaddy 126 | 125 hermit crab 127 | 126 isopod 128 | 127 white stork, Ciconia ciconia 129 | 128 black stork, Ciconia nigra 130 | 129 spoonbill 131 | 130 flamingo 132 | 131 little blue heron, Egretta caerulea 133 | 132 American egret, great white heron, Egretta albus 134 | 133 bittern 135 | 134 crane 136 | 135 limpkin, Aramus pictus 137 | 136 European gallinule, Porphyrio porphyrio 138 | 137 American coot, marsh hen, mud hen, water hen, Fulica americana 139 | 138 bustard 140 | 139 ruddy turnstone, Arenaria interpres 141 | 140 red-backed sandpiper, dunlin, Erolia alpina 142 | 141 redshank, Tringa totanus 143 | 142 dowitcher 144 | 143 oystercatcher, oyster catcher 145 | 144 pelican 146 | 145 king penguin, Aptenodytes patagonica 147 | 146 albatross, mollymawk 148 | 147 grey whale, gray whale, devilfish, Eschrichtius gibbosus, Eschrichtius robustus 149 | 148 killer whale, killer, orca, grampus, sea wolf, Orcinus orca 150 | 149 dugong, Dugong dugon 151 | 150 sea lion 152 | 151 Chihuahua 153 | 152 Japanese spaniel 154 | 153 Maltese dog, Maltese terrier, Maltese 155 | 154 Pekinese, Pekingese, Peke 156 | 155 Shih-Tzu 157 | 156 Blenheim spaniel 158 | 157 papillon 159 | 158 toy terrier 160 | 159 Rhodesian ridgeback 161 | 160 Afghan hound, Afghan 162 | 161 basset, basset hound 163 | 162 beagle 164 | 163 bloodhound, sleuthhound 165 | 164 bluetick 166 | 165 black-and-tan coonhound 167 | 166 Walker hound, Walker foxhound 168 | 167 English foxhound 169 | 168 redbone 170 | 169 borzoi, Russian wolfhound 171 | 170 Irish wolfhound 172 | 171 Italian greyhound 173 | 172 whippet 174 | 173 Ibizan hound, Ibizan Podenco 175 | 174 Norwegian elkhound, elkhound 176 | 175 otterhound, otter hound 177 | 176 Saluki, gazelle hound 178 | 177 Scottish deerhound, deerhound 179 | 178 Weimaraner 180 | 179 Staffordshire bullterrier, Staffordshire bull terrier 181 | 180 American Staffordshire terrier, Staffordshire terrier, American pit bull terrier, pit bull terrier 182 | 181 Bedlington terrier 183 | 182 Border terrier 184 | 183 Kerry blue terrier 185 | 184 Irish terrier 186 | 185 Norfolk terrier 187 | 186 Norwich terrier 188 | 187 Yorkshire terrier 189 | 188 wire-haired fox terrier 190 | 189 Lakeland terrier 191 | 190 Sealyham terrier, Sealyham 192 | 191 Airedale, Airedale terrier 193 | 192 cairn, cairn terrier 194 | 193 Australian terrier 195 | 194 Dandie Dinmont, Dandie Dinmont terrier 196 | 195 Boston bull, Boston terrier 197 | 196 miniature schnauzer 198 | 197 giant schnauzer 199 | 198 standard schnauzer 200 | 199 Scotch terrier, Scottish terrier, Scottie 201 | 200 Tibetan terrier, chrysanthemum dog 202 | 201 silky terrier, Sydney silky 203 | 202 soft-coated wheaten terrier 204 | 203 West Highland white terrier 205 | 204 Lhasa, Lhasa apso 206 | 205 flat-coated retriever 207 | 206 curly-coated retriever 208 | 207 golden retriever 209 | 208 Labrador retriever 210 | 209 Chesapeake Bay retriever 211 | 210 German short-haired pointer 212 | 211 vizsla, Hungarian pointer 213 | 212 English setter 214 | 213 Irish setter, red setter 215 | 214 Gordon setter 216 | 215 Brittany spaniel 217 | 216 clumber, clumber spaniel 218 | 217 English springer, English springer spaniel 219 | 218 Welsh springer spaniel 220 | 219 cocker spaniel, English cocker spaniel, cocker 221 | 220 Sussex spaniel 222 | 221 Irish water spaniel 223 | 222 kuvasz 224 | 223 schipperke 225 | 224 groenendael 226 | 225 malinois 227 | 226 briard 228 | 227 kelpie 229 | 228 komondor 230 | 229 Old English sheepdog, bobtail 231 | 230 Shetland sheepdog, Shetland sheep dog, Shetland 232 | 231 collie 233 | 232 Border collie 234 | 233 Bouvier des Flandres, Bouviers des Flandres 235 | 234 Rottweiler 236 | 235 German shepherd, German shepherd dog, German police dog, alsatian 237 | 236 Doberman, Doberman pinscher 238 | 237 miniature pinscher 239 | 238 Greater Swiss Mountain dog 240 | 239 Bernese mountain dog 241 | 240 Appenzeller 242 | 241 EntleBucher 243 | 242 boxer 244 | 243 bull mastiff 245 | 244 Tibetan mastiff 246 | 245 French bulldog 247 | 246 Great Dane 248 | 247 Saint Bernard, St Bernard 249 | 248 Eskimo dog, husky 250 | 249 malamute, malemute, Alaskan malamute 251 | 250 Siberian husky 252 | 251 dalmatian, coach dog, carriage dog 253 | 252 affenpinscher, monkey pinscher, monkey dog 254 | 253 basenji 255 | 254 pug, pug-dog 256 | 255 Leonberg 257 | 256 Newfoundland, Newfoundland dog 258 | 257 Great Pyrenees 259 | 258 Samoyed, Samoyede 260 | 259 Pomeranian 261 | 260 chow, chow chow 262 | 261 keeshond 263 | 262 Brabancon griffon 264 | 263 Pembroke, Pembroke Welsh corgi 265 | 264 Cardigan, Cardigan Welsh corgi 266 | 265 toy poodle 267 | 266 miniature poodle 268 | 267 standard poodle 269 | 268 Mexican hairless 270 | 269 timber wolf, grey wolf, gray wolf, Canis lupus 271 | 270 white wolf, Arctic wolf, Canis lupus tundrarum 272 | 271 red wolf, maned wolf, Canis rufus, Canis niger 273 | 272 coyote, prairie wolf, brush wolf, Canis latrans 274 | 273 dingo, warrigal, warragal, Canis dingo 275 | 274 dhole, Cuon alpinus 276 | 275 African hunting dog, hyena dog, Cape hunting dog, Lycaon pictus 277 | 276 hyena, hyaena 278 | 277 red fox, Vulpes vulpes 279 | 278 kit fox, Vulpes macrotis 280 | 279 Arctic fox, white fox, Alopex lagopus 281 | 280 grey fox, gray fox, Urocyon cinereoargenteus 282 | 281 tabby, tabby cat 283 | 282 tiger cat 284 | 283 Persian cat 285 | 284 Siamese cat, Siamese 286 | 285 Egyptian cat 287 | 286 cougar, puma, catamount, mountain lion, painter, panther, Felis concolor 288 | 287 lynx, catamount 289 | 288 leopard, Panthera pardus 290 | 289 snow leopard, ounce, Panthera uncia 291 | 290 jaguar, panther, Panthera onca, Felis onca 292 | 291 lion, king of beasts, Panthera leo 293 | 292 tiger, Panthera tigris 294 | 293 cheetah, chetah, Acinonyx jubatus 295 | 294 brown bear, bruin, Ursus arctos 296 | 295 American black bear, black bear, Ursus americanus, Euarctos americanus 297 | 296 ice bear, polar bear, Ursus Maritimus, Thalarctos maritimus 298 | 297 sloth bear, Melursus ursinus, Ursus ursinus 299 | 298 mongoose 300 | 299 meerkat, mierkat 301 | 300 tiger beetle 302 | 301 ladybug, ladybeetle, lady beetle, ladybird, ladybird beetle 303 | 302 ground beetle, carabid beetle 304 | 303 long-horned beetle, longicorn, longicorn beetle 305 | 304 leaf beetle, chrysomelid 306 | 305 dung beetle 307 | 306 rhinoceros beetle 308 | 307 weevil 309 | 308 fly 310 | 309 bee 311 | 310 ant, emmet, pismire 312 | 311 grasshopper, hopper 313 | 312 cricket 314 | 313 walking stick, walkingstick, stick insect 315 | 314 cockroach, roach 316 | 315 mantis, mantid 317 | 316 cicada, cicala 318 | 317 leafhopper 319 | 318 lacewing, lacewing fly 320 | 319 dragonfly, darning needle, devil's darning needle, sewing needle, snake feeder, snake doctor, mosquito hawk, skeeter hawk 321 | 320 damselfly 322 | 321 admiral 323 | 322 ringlet, ringlet butterfly 324 | 323 monarch, monarch butterfly, milkweed butterfly, Danaus plexippus 325 | 324 cabbage butterfly 326 | 325 sulphur butterfly, sulfur butterfly 327 | 326 lycaenid, lycaenid butterfly 328 | 327 starfish, sea star 329 | 328 sea urchin 330 | 329 sea cucumber, holothurian 331 | 330 wood rabbit, cottontail, cottontail rabbit 332 | 331 hare 333 | 332 Angora, Angora rabbit 334 | 333 hamster 335 | 334 porcupine, hedgehog 336 | 335 fox squirrel, eastern fox squirrel, Sciurus niger 337 | 336 marmot 338 | 337 beaver 339 | 338 guinea pig, Cavia cobaya 340 | 339 sorrel 341 | 340 zebra 342 | 341 hog, pig, grunter, squealer, Sus scrofa 343 | 342 wild boar, boar, Sus scrofa 344 | 343 warthog 345 | 344 hippopotamus, hippo, river horse, Hippopotamus amphibius 346 | 345 ox 347 | 346 water buffalo, water ox, Asiatic buffalo, Bubalus bubalis 348 | 347 bison 349 | 348 ram, tup 350 | 349 bighorn, bighorn sheep, cimarron, Rocky Mountain bighorn, Rocky Mountain sheep, Ovis canadensis 351 | 350 ibex, Capra ibex 352 | 351 hartebeest 353 | 352 impala, Aepyceros melampus 354 | 353 gazelle 355 | 354 Arabian camel, dromedary, Camelus dromedarius 356 | 355 llama 357 | 356 weasel 358 | 357 mink 359 | 358 polecat, fitch, foulmart, foumart, Mustela putorius 360 | 359 black-footed ferret, ferret, Mustela nigripes 361 | 360 otter 362 | 361 skunk, polecat, wood pussy 363 | 362 badger 364 | 363 armadillo 365 | 364 three-toed sloth, ai, Bradypus tridactylus 366 | 365 orangutan, orang, orangutang, Pongo pygmaeus 367 | 366 gorilla, Gorilla gorilla 368 | 367 chimpanzee, chimp, Pan troglodytes 369 | 368 gibbon, Hylobates lar 370 | 369 siamang, Hylobates syndactylus, Symphalangus syndactylus 371 | 370 guenon, guenon monkey 372 | 371 patas, hussar monkey, Erythrocebus patas 373 | 372 baboon 374 | 373 macaque 375 | 374 langur 376 | 375 colobus, colobus monkey 377 | 376 proboscis monkey, Nasalis larvatus 378 | 377 marmoset 379 | 378 capuchin, ringtail, Cebus capucinus 380 | 379 howler monkey, howler 381 | 380 titi, titi monkey 382 | 381 spider monkey, Ateles geoffroyi 383 | 382 squirrel monkey, Saimiri sciureus 384 | 383 Madagascar cat, ring-tailed lemur, Lemur catta 385 | 384 indri, indris, Indri indri, Indri brevicaudatus 386 | 385 Indian elephant, Elephas maximus 387 | 386 African elephant, Loxodonta africana 388 | 387 lesser panda, red panda, panda, bear cat, cat bear, Ailurus fulgens 389 | 388 giant panda, panda, panda bear, coon bear, Ailuropoda melanoleuca 390 | 389 barracouta, snoek 391 | 390 eel 392 | 391 coho, cohoe, coho salmon, blue jack, silver salmon, Oncorhynchus kisutch 393 | 392 rock beauty, Holocanthus tricolor 394 | 393 anemone fish 395 | 394 sturgeon 396 | 395 gar, garfish, garpike, billfish, Lepisosteus osseus 397 | 396 lionfish 398 | 397 puffer, pufferfish, blowfish, globefish 399 | 398 abacus 400 | 399 abaya 401 | 400 academic gown, academic robe, judge's robe 402 | 401 accordion, piano accordion, squeeze box 403 | 402 acoustic guitar 404 | 403 aircraft carrier, carrier, flattop, attack aircraft carrier 405 | 404 airliner 406 | 405 airship, dirigible 407 | 406 altar 408 | 407 ambulance 409 | 408 amphibian, amphibious vehicle 410 | 409 analog clock 411 | 410 apiary, bee house 412 | 411 apron 413 | 412 ashcan, trash can, garbage can, wastebin, ash bin, ash-bin, ashbin, dustbin, trash barrel, trash bin 414 | 413 assault rifle, assault gun 415 | 414 backpack, back pack, knapsack, packsack, rucksack, haversack 416 | 415 bakery, bakeshop, bakehouse 417 | 416 balance beam, beam 418 | 417 balloon 419 | 418 ballpoint, ballpoint pen, ballpen, Biro 420 | 419 Band Aid 421 | 420 banjo 422 | 421 bannister, banister, balustrade, balusters, handrail 423 | 422 barbell 424 | 423 barber chair 425 | 424 barbershop 426 | 425 barn 427 | 426 barometer 428 | 427 barrel, cask 429 | 428 barrow, garden cart, lawn cart, wheelbarrow 430 | 429 baseball 431 | 430 basketball 432 | 431 bassinet 433 | 432 bassoon 434 | 433 bathing cap, swimming cap 435 | 434 bath towel 436 | 435 bathtub, bathing tub, bath, tub 437 | 436 beach wagon, station wagon, wagon, estate car, beach waggon, station waggon, waggon 438 | 437 beacon, lighthouse, beacon light, pharos 439 | 438 beaker 440 | 439 bearskin, busby, shako 441 | 440 beer bottle 442 | 441 beer glass 443 | 442 bell cote, bell cot 444 | 443 bib 445 | 444 bicycle-built-for-two, tandem bicycle, tandem 446 | 445 bikini, two-piece 447 | 446 binder, ring-binder 448 | 447 binoculars, field glasses, opera glasses 449 | 448 birdhouse 450 | 449 boathouse 451 | 450 bobsled, bobsleigh, bob 452 | 451 bolo tie, bolo, bola tie, bola 453 | 452 bonnet, poke bonnet 454 | 453 bookcase 455 | 454 bookshop, bookstore, bookstall 456 | 455 bottlecap 457 | 456 bow 458 | 457 bow tie, bow-tie, bowtie 459 | 458 brass, memorial tablet, plaque 460 | 459 brassiere, bra, bandeau 461 | 460 breakwater, groin, groyne, mole, bulwark, seawall, jetty 462 | 461 breastplate, aegis, egis 463 | 462 broom 464 | 463 bucket, pail 465 | 464 buckle 466 | 465 bulletproof vest 467 | 466 bullet train, bullet 468 | 467 butcher shop, meat market 469 | 468 cab, hack, taxi, taxicab 470 | 469 caldron, cauldron 471 | 470 candle, taper, wax light 472 | 471 cannon 473 | 472 canoe 474 | 473 can opener, tin opener 475 | 474 cardigan 476 | 475 car mirror 477 | 476 carousel, carrousel, merry-go-round, roundabout, whirligig 478 | 477 carpenter's kit, tool kit 479 | 478 carton 480 | 479 car wheel 481 | 480 cash machine, cash dispenser, automated teller machine, automatic teller machine, automated teller, automatic teller, ATM 482 | 481 cassette 483 | 482 cassette player 484 | 483 castle 485 | 484 catamaran 486 | 485 CD player 487 | 486 cello, violoncello 488 | 487 cellular telephone, cellular phone, cellphone, cell, mobile phone 489 | 488 chain 490 | 489 chainlink fence 491 | 490 chain mail, ring mail, mail, chain armor, chain armour, ring armor, ring armour 492 | 491 chain saw, chainsaw 493 | 492 chest 494 | 493 chiffonier, commode 495 | 494 chime, bell, gong 496 | 495 china cabinet, china closet 497 | 496 Christmas stocking 498 | 497 church, church building 499 | 498 cinema, movie theater, movie theatre, movie house, picture palace 500 | 499 cleaver, meat cleaver, chopper 501 | 500 cliff dwelling 502 | 501 cloak 503 | 502 clog, geta, patten, sabot 504 | 503 cocktail shaker 505 | 504 coffee mug 506 | 505 coffeepot 507 | 506 coil, spiral, volute, whorl, helix 508 | 507 combination lock 509 | 508 computer keyboard, keypad 510 | 509 confectionery, confectionary, candy store 511 | 510 container ship, containership, container vessel 512 | 511 convertible 513 | 512 corkscrew, bottle screw 514 | 513 cornet, horn, trumpet, trump 515 | 514 cowboy boot 516 | 515 cowboy hat, ten-gallon hat 517 | 516 cradle 518 | 517 crane 519 | 518 crash helmet 520 | 519 crate 521 | 520 crib, cot 522 | 521 Crock Pot 523 | 522 croquet ball 524 | 523 crutch 525 | 524 cuirass 526 | 525 dam, dike, dyke 527 | 526 desk 528 | 527 desktop computer 529 | 528 dial telephone, dial phone 530 | 529 diaper, nappy, napkin 531 | 530 digital clock 532 | 531 digital watch 533 | 532 dining table, board 534 | 533 dishrag, dishcloth 535 | 534 dishwasher, dish washer, dishwashing machine 536 | 535 disk brake, disc brake 537 | 536 dock, dockage, docking facility 538 | 537 dogsled, dog sled, dog sleigh 539 | 538 dome 540 | 539 doormat, welcome mat 541 | 540 drilling platform, offshore rig 542 | 541 drum, membranophone, tympan 543 | 542 drumstick 544 | 543 dumbbell 545 | 544 Dutch oven 546 | 545 electric fan, blower 547 | 546 electric guitar 548 | 547 electric locomotive 549 | 548 entertainment center 550 | 549 envelope 551 | 550 espresso maker 552 | 551 face powder 553 | 552 feather boa, boa 554 | 553 file, file cabinet, filing cabinet 555 | 554 fireboat 556 | 555 fire engine, fire truck 557 | 556 fire screen, fireguard 558 | 557 flagpole, flagstaff 559 | 558 flute, transverse flute 560 | 559 folding chair 561 | 560 football helmet 562 | 561 forklift 563 | 562 fountain 564 | 563 fountain pen 565 | 564 four-poster 566 | 565 freight car 567 | 566 French horn, horn 568 | 567 frying pan, frypan, skillet 569 | 568 fur coat 570 | 569 garbage truck, dustcart 571 | 570 gasmask, respirator, gas helmet 572 | 571 gas pump, gasoline pump, petrol pump, island dispenser 573 | 572 goblet 574 | 573 go-kart 575 | 574 golf ball 576 | 575 golfcart, golf cart 577 | 576 gondola 578 | 577 gong, tam-tam 579 | 578 gown 580 | 579 grand piano, grand 581 | 580 greenhouse, nursery, glasshouse 582 | 581 grille, radiator grille 583 | 582 grocery store, grocery, food market, market 584 | 583 guillotine 585 | 584 hair slide 586 | 585 hair spray 587 | 586 half track 588 | 587 hammer 589 | 588 hamper 590 | 589 hand blower, blow dryer, blow drier, hair dryer, hair drier 591 | 590 hand-held computer, hand-held microcomputer 592 | 591 handkerchief, hankie, hanky, hankey 593 | 592 hard disc, hard disk, fixed disk 594 | 593 harmonica, mouth organ, harp, mouth harp 595 | 594 harp 596 | 595 harvester, reaper 597 | 596 hatchet 598 | 597 holster 599 | 598 home theater, home theatre 600 | 599 honeycomb 601 | 600 hook, claw 602 | 601 hoopskirt, crinoline 603 | 602 horizontal bar, high bar 604 | 603 horse cart, horse-cart 605 | 604 hourglass 606 | 605 iPod 607 | 606 iron, smoothing iron 608 | 607 jack-o'-lantern 609 | 608 jean, blue jean, denim 610 | 609 jeep, landrover 611 | 610 jersey, T-shirt, tee shirt 612 | 611 jigsaw puzzle 613 | 612 jinrikisha, ricksha, rickshaw 614 | 613 joystick 615 | 614 kimono 616 | 615 knee pad 617 | 616 knot 618 | 617 lab coat, laboratory coat 619 | 618 ladle 620 | 619 lampshade, lamp shade 621 | 620 laptop, laptop computer 622 | 621 lawn mower, mower 623 | 622 lens cap, lens cover 624 | 623 letter opener, paper knife, paperknife 625 | 624 library 626 | 625 lifeboat 627 | 626 lighter, light, igniter, ignitor 628 | 627 limousine, limo 629 | 628 liner, ocean liner 630 | 629 lipstick, lip rouge 631 | 630 Loafer 632 | 631 lotion 633 | 632 loudspeaker, speaker, speaker unit, loudspeaker system, speaker system 634 | 633 loupe, jeweler's loupe 635 | 634 lumbermill, sawmill 636 | 635 magnetic compass 637 | 636 mailbag, postbag 638 | 637 mailbox, letter box 639 | 638 maillot 640 | 639 maillot, tank suit 641 | 640 manhole cover 642 | 641 maraca 643 | 642 marimba, xylophone 644 | 643 mask 645 | 644 matchstick 646 | 645 maypole 647 | 646 maze, labyrinth 648 | 647 measuring cup 649 | 648 medicine chest, medicine cabinet 650 | 649 megalith, megalithic structure 651 | 650 microphone, mike 652 | 651 microwave, microwave oven 653 | 652 military uniform 654 | 653 milk can 655 | 654 minibus 656 | 655 miniskirt, mini 657 | 656 minivan 658 | 657 missile 659 | 658 mitten 660 | 659 mixing bowl 661 | 660 mobile home, manufactured home 662 | 661 Model T 663 | 662 modem 664 | 663 monastery 665 | 664 monitor 666 | 665 moped 667 | 666 mortar 668 | 667 mortarboard 669 | 668 mosque 670 | 669 mosquito net 671 | 670 motor scooter, scooter 672 | 671 mountain bike, all-terrain bike, off-roader 673 | 672 mountain tent 674 | 673 mouse, computer mouse 675 | 674 mousetrap 676 | 675 moving van 677 | 676 muzzle 678 | 677 nail 679 | 678 neck brace 680 | 679 necklace 681 | 680 nipple 682 | 681 notebook, notebook computer 683 | 682 obelisk 684 | 683 oboe, hautboy, hautbois 685 | 684 ocarina, sweet potato 686 | 685 odometer, hodometer, mileometer, milometer 687 | 686 oil filter 688 | 687 organ, pipe organ 689 | 688 oscilloscope, scope, cathode-ray oscilloscope, CRO 690 | 689 overskirt 691 | 690 oxcart 692 | 691 oxygen mask 693 | 692 packet 694 | 693 paddle, boat paddle 695 | 694 paddlewheel, paddle wheel 696 | 695 padlock 697 | 696 paintbrush 698 | 697 pajama, pyjama, pj's, jammies 699 | 698 palace 700 | 699 panpipe, pandean pipe, syrinx 701 | 700 paper towel 702 | 701 parachute, chute 703 | 702 parallel bars, bars 704 | 703 park bench 705 | 704 parking meter 706 | 705 passenger car, coach, carriage 707 | 706 patio, terrace 708 | 707 pay-phone, pay-station 709 | 708 pedestal, plinth, footstall 710 | 709 pencil box, pencil case 711 | 710 pencil sharpener 712 | 711 perfume, essence 713 | 712 Petri dish 714 | 713 photocopier 715 | 714 pick, plectrum, plectron 716 | 715 pickelhaube 717 | 716 picket fence, paling 718 | 717 pickup, pickup truck 719 | 718 pier 720 | 719 piggy bank, penny bank 721 | 720 pill bottle 722 | 721 pillow 723 | 722 ping-pong ball 724 | 723 pinwheel 725 | 724 pirate, pirate ship 726 | 725 pitcher, ewer 727 | 726 plane, carpenter's plane, woodworking plane 728 | 727 planetarium 729 | 728 plastic bag 730 | 729 plate rack 731 | 730 plow, plough 732 | 731 plunger, plumber's helper 733 | 732 Polaroid camera, Polaroid Land camera 734 | 733 pole 735 | 734 police van, police wagon, paddy wagon, patrol wagon, wagon, black Maria 736 | 735 poncho 737 | 736 pool table, billiard table, snooker table 738 | 737 pop bottle, soda bottle 739 | 738 pot, flowerpot 740 | 739 potter's wheel 741 | 740 power drill 742 | 741 prayer rug, prayer mat 743 | 742 printer 744 | 743 prison, prison house 745 | 744 projectile, missile 746 | 745 projector 747 | 746 puck, hockey puck 748 | 747 punching bag, punch bag, punching ball, punchball 749 | 748 purse 750 | 749 quill, quill pen 751 | 750 quilt, comforter, comfort, puff 752 | 751 racer, race car, racing car 753 | 752 racket, racquet 754 | 753 radiator 755 | 754 radio, wireless 756 | 755 radio telescope, radio reflector 757 | 756 rain barrel 758 | 757 recreational vehicle, RV, R.V. 759 | 758 reel 760 | 759 reflex camera 761 | 760 refrigerator, icebox 762 | 761 remote control, remote 763 | 762 restaurant, eating house, eating place, eatery 764 | 763 revolver, six-gun, six-shooter 765 | 764 rifle 766 | 765 rocking chair, rocker 767 | 766 rotisserie 768 | 767 rubber eraser, rubber, pencil eraser 769 | 768 rugby ball 770 | 769 rule, ruler 771 | 770 running shoe 772 | 771 safe 773 | 772 safety pin 774 | 773 saltshaker, salt shaker 775 | 774 sandal 776 | 775 sarong 777 | 776 sax, saxophone 778 | 777 scabbard 779 | 778 scale, weighing machine 780 | 779 school bus 781 | 780 schooner 782 | 781 scoreboard 783 | 782 screen, CRT screen 784 | 783 screw 785 | 784 screwdriver 786 | 785 seat belt, seatbelt 787 | 786 sewing machine 788 | 787 shield, buckler 789 | 788 shoe shop, shoe-shop, shoe store 790 | 789 shoji 791 | 790 shopping basket 792 | 791 shopping cart 793 | 792 shovel 794 | 793 shower cap 795 | 794 shower curtain 796 | 795 ski 797 | 796 ski mask 798 | 797 sleeping bag 799 | 798 slide rule, slipstick 800 | 799 sliding door 801 | 800 slot, one-armed bandit 802 | 801 snorkel 803 | 802 snowmobile 804 | 803 snowplow, snowplough 805 | 804 soap dispenser 806 | 805 soccer ball 807 | 806 sock 808 | 807 solar dish, solar collector, solar furnace 809 | 808 sombrero 810 | 809 soup bowl 811 | 810 space bar 812 | 811 space heater 813 | 812 space shuttle 814 | 813 spatula 815 | 814 speedboat 816 | 815 spider web, spider's web 817 | 816 spindle 818 | 817 sports car, sport car 819 | 818 spotlight, spot 820 | 819 stage 821 | 820 steam locomotive 822 | 821 steel arch bridge 823 | 822 steel drum 824 | 823 stethoscope 825 | 824 stole 826 | 825 stone wall 827 | 826 stopwatch, stop watch 828 | 827 stove 829 | 828 strainer 830 | 829 streetcar, tram, tramcar, trolley, trolley car 831 | 830 stretcher 832 | 831 studio couch, day bed 833 | 832 stupa, tope 834 | 833 submarine, pigboat, sub, U-boat 835 | 834 suit, suit of clothes 836 | 835 sundial 837 | 836 sunglass 838 | 837 sunglasses, dark glasses, shades 839 | 838 sunscreen, sunblock, sun blocker 840 | 839 suspension bridge 841 | 840 swab, swob, mop 842 | 841 sweatshirt 843 | 842 swimming trunks, bathing trunks 844 | 843 swing 845 | 844 switch, electric switch, electrical switch 846 | 845 syringe 847 | 846 table lamp 848 | 847 tank, army tank, armored combat vehicle, armoured combat vehicle 849 | 848 tape player 850 | 849 teapot 851 | 850 teddy, teddy bear 852 | 851 television, television system 853 | 852 tennis ball 854 | 853 thatch, thatched roof 855 | 854 theater curtain, theatre curtain 856 | 855 thimble 857 | 856 thresher, thrasher, threshing machine 858 | 857 throne 859 | 858 tile roof 860 | 859 toaster 861 | 860 tobacco shop, tobacconist shop, tobacconist 862 | 861 toilet seat 863 | 862 torch 864 | 863 totem pole 865 | 864 tow truck, tow car, wrecker 866 | 865 toyshop 867 | 866 tractor 868 | 867 trailer truck, tractor trailer, trucking rig, rig, articulated lorry, semi 869 | 868 tray 870 | 869 trench coat 871 | 870 tricycle, trike, velocipede 872 | 871 trimaran 873 | 872 tripod 874 | 873 triumphal arch 875 | 874 trolleybus, trolley coach, trackless trolley 876 | 875 trombone 877 | 876 tub, vat 878 | 877 turnstile 879 | 878 typewriter keyboard 880 | 879 umbrella 881 | 880 unicycle, monocycle 882 | 881 upright, upright piano 883 | 882 vacuum, vacuum cleaner 884 | 883 vase 885 | 884 vault 886 | 885 velvet 887 | 886 vending machine 888 | 887 vestment 889 | 888 viaduct 890 | 889 violin, fiddle 891 | 890 volleyball 892 | 891 waffle iron 893 | 892 wall clock 894 | 893 wallet, billfold, notecase, pocketbook 895 | 894 wardrobe, closet, press 896 | 895 warplane, military plane 897 | 896 washbasin, handbasin, washbowl, lavabo, wash-hand basin 898 | 897 washer, automatic washer, washing machine 899 | 898 water bottle 900 | 899 water jug 901 | 900 water tower 902 | 901 whiskey jug 903 | 902 whistle 904 | 903 wig 905 | 904 window screen 906 | 905 window shade 907 | 906 Windsor tie 908 | 907 wine bottle 909 | 908 wing 910 | 909 wok 911 | 910 wooden spoon 912 | 911 wool, woolen, woollen 913 | 912 worm fence, snake fence, snake-rail fence, Virginia fence 914 | 913 wreck 915 | 914 yawl 916 | 915 yurt 917 | 916 web site, website, internet site, site 918 | 917 comic book 919 | 918 crossword puzzle, crossword 920 | 919 street sign 921 | 920 traffic light, traffic signal, stoplight 922 | 921 book jacket, dust cover, dust jacket, dust wrapper 923 | 922 menu 924 | 923 plate 925 | 924 guacamole 926 | 925 consomme 927 | 926 hot pot, hotpot 928 | 927 trifle 929 | 928 ice cream, icecream 930 | 929 ice lolly, lolly, lollipop, popsicle 931 | 930 French loaf 932 | 931 bagel, beigel 933 | 932 pretzel 934 | 933 cheeseburger 935 | 934 hotdog, hot dog, red hot 936 | 935 mashed potato 937 | 936 head cabbage 938 | 937 broccoli 939 | 938 cauliflower 940 | 939 zucchini, courgette 941 | 940 spaghetti squash 942 | 941 acorn squash 943 | 942 butternut squash 944 | 943 cucumber, cuke 945 | 944 artichoke, globe artichoke 946 | 945 bell pepper 947 | 946 cardoon 948 | 947 mushroom 949 | 948 Granny Smith 950 | 949 strawberry 951 | 950 orange 952 | 951 lemon 953 | 952 fig 954 | 953 pineapple, ananas 955 | 954 banana 956 | 955 jackfruit, jak, jack 957 | 956 custard apple 958 | 957 pomegranate 959 | 958 hay 960 | 959 carbonara 961 | 960 chocolate sauce, chocolate syrup 962 | 961 dough 963 | 962 meat loaf, meatloaf 964 | 963 pizza, pizza pie 965 | 964 potpie 966 | 965 burrito 967 | 966 red wine 968 | 967 espresso 969 | 968 cup 970 | 969 eggnog 971 | 970 alp 972 | 971 bubble 973 | 972 cliff, drop, drop-off 974 | 973 coral reef 975 | 974 geyser 976 | 975 lakeside, lakeshore 977 | 976 promontory, headland, head, foreland 978 | 977 sandbar, sand bar 979 | 978 seashore, coast, seacoast, sea-coast 980 | 979 valley, vale 981 | 980 volcano 982 | 981 ballplayer, baseball player 983 | 982 groom, bridegroom 984 | 983 scuba diver 985 | 984 rapeseed 986 | 985 daisy 987 | 986 yellow lady's slipper, yellow lady-slipper, Cypripedium calceolus, Cypripedium parviflorum 988 | 987 corn 989 | 988 acorn 990 | 989 hip, rose hip, rosehip 991 | 990 buckeye, horse chestnut, conker 992 | 991 coral fungus 993 | 992 agaric 994 | 993 gyromitra 995 | 994 stinkhorn, carrion fungus 996 | 995 earthstar 997 | 996 hen-of-the-woods, hen of the woods, Polyporus frondosus, Grifola frondosa 998 | 997 bolete 999 | 998 ear, spike, capitulum 1000 | 999 toilet tissue, toilet paper, bathroom tissue 1001 | -------------------------------------------------------------------------------- /images/n01440764_9780.JPEG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SWHL/PPLCNet2PyTorch/ed6abf9c5af25c163bc27e0eaada4516889bd925/images/n01440764_9780.JPEG -------------------------------------------------------------------------------- /pp_lcnet.py: -------------------------------------------------------------------------------- 1 | # copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | from __future__ import absolute_import, division, print_function 15 | 16 | import os 17 | 18 | import paddle 19 | import paddle.nn as nn 20 | import paddle.nn.functional as F 21 | import six 22 | from paddle import ParamAttr 23 | from paddle.nn import AdaptiveAvgPool2D, BatchNorm, Conv2D, Dropout, Linear 24 | from paddle.nn.initializer import KaimingNormal 25 | from paddle.regularizer import L2Decay 26 | 27 | from utils import (CropImage, DecodeImage, NormalizeImage, ResizeImage, 28 | ToCHWImage) 29 | 30 | MODEL_URLS = { 31 | "PPLCNet_x0_25": 32 | "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/legendary_models/PPLCNet_x0_25_pretrained.pdparams", 33 | "PPLCNet_x0_35": 34 | "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/legendary_models/PPLCNet_x0_35_pretrained.pdparams", 35 | "PPLCNet_x0_5": 36 | "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/legendary_models/PPLCNet_x0_5_pretrained.pdparams", 37 | "PPLCNet_x0_75": 38 | "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/legendary_models/PPLCNet_x0_75_pretrained.pdparams", 39 | "PPLCNet_x1_0": 40 | "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/legendary_models/PPLCNet_x1_0_pretrained.pdparams", 41 | "PPLCNet_x1_5": 42 | "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/legendary_models/PPLCNet_x1_5_pretrained.pdparams", 43 | "PPLCNet_x2_0": 44 | "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/legendary_models/PPLCNet_x2_0_pretrained.pdparams", 45 | "PPLCNet_x2_5": 46 | "https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/legendary_models/PPLCNet_x2_5_pretrained.pdparams" 47 | } 48 | 49 | __all__ = list(MODEL_URLS.keys()) 50 | 51 | # Each element(list) represents a depthwise block, which is composed of k, in_c, out_c, s, use_se. 52 | # k: kernel_size 53 | # in_c: input channel number in depthwise block 54 | # out_c: output channel number in depthwise block 55 | # s: stride in depthwise block 56 | # use_se: whether to use SE block 57 | 58 | NET_CONFIG = { 59 | # k, in_c, out_c, s, use_se 60 | "blocks2": [[3, 16, 32, 1, False]], 61 | "blocks3": [[3, 32, 64, 2, False], [3, 64, 64, 1, False]], 62 | "blocks4": [[3, 64, 128, 2, False], [3, 128, 128, 1, False]], 63 | "blocks5": [[3, 128, 256, 2, False], [5, 256, 256, 1, False], 64 | [5, 256, 256, 1, False], [5, 256, 256, 1, False], 65 | [5, 256, 256, 1, False], [5, 256, 256, 1, False]], 66 | "blocks6": [[5, 256, 512, 2, True], [5, 512, 512, 1, True]] 67 | } 68 | 69 | 70 | def load_dygraph_pretrain(model, path=None): 71 | if not (os.path.isdir(path) or os.path.exists(path + '.pdparams')): 72 | raise ValueError("Model pretrain path {} does not " 73 | "exists.".format(path)) 74 | param_state_dict = paddle.load(path + ".pdparams") 75 | model.set_dict(param_state_dict) 76 | return 77 | 78 | 79 | def make_divisible(v, divisor=8, min_value=None): 80 | if min_value is None: 81 | min_value = divisor 82 | 83 | new_v = max(min_value, int(v + divisor / 2) // divisor * divisor) 84 | if new_v < 0.9 * v: 85 | new_v += divisor 86 | return new_v 87 | 88 | 89 | class ConvBNLayer(nn.Layer): 90 | def __init__(self, 91 | num_channels, 92 | filter_size, 93 | num_filters, 94 | stride, 95 | num_groups=1): 96 | super().__init__() 97 | 98 | self.conv = Conv2D( 99 | in_channels=num_channels, 100 | out_channels=num_filters, 101 | kernel_size=filter_size, 102 | stride=stride, 103 | padding=(filter_size - 1) // 2, 104 | groups=num_groups, 105 | weight_attr=ParamAttr(initializer=KaimingNormal()), 106 | bias_attr=False) 107 | 108 | self.bn = BatchNorm( 109 | num_filters, 110 | param_attr=ParamAttr(regularizer=L2Decay(0.0)), 111 | bias_attr=ParamAttr(regularizer=L2Decay(0.0))) 112 | self.hardswish = nn.Hardswish() 113 | 114 | def forward(self, x): 115 | # x.shape: 1x16x112x112 116 | x = self.conv(x) 117 | # x.shape 1x32x112x112 118 | x = self.bn(x) 119 | x = self.hardswish(x) 120 | return x 121 | 122 | 123 | class DepthwiseSeparable(nn.Layer): 124 | def __init__(self, 125 | num_channels, 126 | num_filters, 127 | stride, 128 | dw_size=3, 129 | use_se=False): 130 | super().__init__() 131 | self.use_se = use_se 132 | self.dw_conv = ConvBNLayer( 133 | num_channels=num_channels, 134 | num_filters=num_channels, 135 | filter_size=dw_size, 136 | stride=stride, 137 | num_groups=num_channels) 138 | if use_se: 139 | self.se = SEModule(num_channels) 140 | self.pw_conv = ConvBNLayer( 141 | num_channels=num_channels, 142 | filter_size=1, 143 | num_filters=num_filters, 144 | stride=1) 145 | 146 | def forward(self, x): 147 | x = self.dw_conv(x) 148 | 149 | if self.use_se: 150 | x = self.se(x) 151 | 152 | x = self.pw_conv(x) 153 | return x 154 | 155 | 156 | class SEModule(nn.Layer): 157 | def __init__(self, channel, reduction=4): 158 | super().__init__() 159 | self.avg_pool = AdaptiveAvgPool2D(1) 160 | self.conv1 = Conv2D( 161 | in_channels=channel, 162 | out_channels=channel // reduction, 163 | kernel_size=1, 164 | stride=1, 165 | padding=0) 166 | self.relu = nn.ReLU() 167 | self.conv2 = Conv2D( 168 | in_channels=channel // reduction, 169 | out_channels=channel, 170 | kernel_size=1, 171 | stride=1, 172 | padding=0) 173 | self.hardsigmoid = nn.Hardsigmoid() 174 | 175 | def forward(self, x): 176 | identity = x 177 | x = self.avg_pool(x) 178 | x = self.conv1(x) 179 | x = self.relu(x) 180 | x = self.conv2(x) 181 | x = self.hardsigmoid(x) 182 | x = paddle.multiply(x=identity, y=x) 183 | return x 184 | 185 | 186 | class PPLCNet(nn.Layer): 187 | def __init__(self, 188 | scale=1.0, 189 | class_num=1000, 190 | dropout_prob=0.2, 191 | class_expand=1280): 192 | super().__init__() 193 | self.scale = scale 194 | self.class_expand = class_expand 195 | 196 | self.conv1 = ConvBNLayer( 197 | num_channels=3, 198 | filter_size=3, 199 | num_filters=make_divisible(16 * scale), 200 | stride=2) 201 | 202 | self.blocks2 = nn.Sequential(*[ 203 | DepthwiseSeparable( 204 | num_channels=make_divisible(in_c * scale), 205 | num_filters=make_divisible(out_c * scale), 206 | dw_size=k, 207 | stride=s, 208 | use_se=se) 209 | for i, (k, in_c, out_c, s, se) in enumerate(NET_CONFIG["blocks2"]) 210 | ]) 211 | 212 | self.blocks3 = nn.Sequential(*[ 213 | DepthwiseSeparable( 214 | num_channels=make_divisible(in_c * scale), 215 | num_filters=make_divisible(out_c * scale), 216 | dw_size=k, 217 | stride=s, 218 | use_se=se) 219 | for i, (k, in_c, out_c, s, se) in enumerate(NET_CONFIG["blocks3"]) 220 | ]) 221 | 222 | self.blocks4 = nn.Sequential(*[ 223 | DepthwiseSeparable( 224 | num_channels=make_divisible(in_c * scale), 225 | num_filters=make_divisible(out_c * scale), 226 | dw_size=k, 227 | stride=s, 228 | use_se=se) 229 | for i, (k, in_c, out_c, s, se) in enumerate(NET_CONFIG["blocks4"]) 230 | ]) 231 | 232 | self.blocks5 = nn.Sequential(*[ 233 | DepthwiseSeparable( 234 | num_channels=make_divisible(in_c * scale), 235 | num_filters=make_divisible(out_c * scale), 236 | dw_size=k, 237 | stride=s, 238 | use_se=se) 239 | for i, (k, in_c, out_c, s, se) in enumerate(NET_CONFIG["blocks5"]) 240 | ]) 241 | 242 | self.blocks6 = nn.Sequential(*[ 243 | DepthwiseSeparable( 244 | num_channels=make_divisible(in_c * scale), 245 | num_filters=make_divisible(out_c * scale), 246 | dw_size=k, 247 | stride=s, 248 | use_se=se) 249 | for i, (k, in_c, out_c, s, se) in enumerate(NET_CONFIG["blocks6"]) 250 | ]) 251 | 252 | self.avg_pool = AdaptiveAvgPool2D(1) 253 | 254 | self.last_conv = Conv2D( 255 | in_channels=make_divisible(NET_CONFIG["blocks6"][-1][2] * scale), 256 | out_channels=self.class_expand, 257 | kernel_size=1, 258 | stride=1, 259 | padding=0, 260 | bias_attr=False) 261 | 262 | self.hardswish = nn.Hardswish() 263 | self.dropout = Dropout(p=dropout_prob, mode="downscale_in_infer") 264 | self.flatten = nn.Flatten(start_axis=1, stop_axis=-1) 265 | 266 | self.fc = Linear(self.class_expand, class_num) 267 | 268 | def forward(self, x): 269 | x = self.conv1(x) 270 | 271 | x = self.blocks2(x) 272 | x = self.blocks3(x) 273 | x = self.blocks4(x) 274 | x = self.blocks5(x) 275 | x = self.blocks6(x) 276 | 277 | x = self.avg_pool(x) 278 | x = self.last_conv(x) 279 | x = self.hardswish(x) 280 | x = self.dropout(x) 281 | x = self.flatten(x) 282 | x = self.fc(x) 283 | return x 284 | 285 | 286 | def _load_pretrained(pretrained, model, *args): 287 | if isinstance(pretrained, str): 288 | load_dygraph_pretrain(model, pretrained) 289 | else: 290 | raise RuntimeError( 291 | "pretrained type is not available. Please use `string` or `boolean` type." 292 | ) 293 | 294 | 295 | def PPLCNet_x0_25(pretrained=False, use_ssld=False, **kwargs): 296 | """ 297 | PPLCNet_x0_25 298 | Args: 299 | pretrained: bool=False or str. If `True` load pretrained parameters, `False` otherwise. 300 | If str, means the path of the pretrained model. 301 | use_ssld: bool=False. Whether using distillation pretrained model when pretrained=True. 302 | Returns: 303 | model: nn.Layer. Specific `PPLCNet_x0_25` model depends on args. 304 | """ 305 | model = PPLCNet(scale=0.25, **kwargs) 306 | _load_pretrained(pretrained, model, MODEL_URLS["PPLCNet_x0_25"], use_ssld) 307 | return model 308 | 309 | 310 | def PPLCNet_x0_35(pretrained=False, use_ssld=False, **kwargs): 311 | """ 312 | PPLCNet_x0_35 313 | Args: 314 | pretrained: bool=False or str. If `True` load pretrained parameters, `False` otherwise. 315 | If str, means the path of the pretrained model. 316 | use_ssld: bool=False. Whether using distillation pretrained model when pretrained=True. 317 | Returns: 318 | model: nn.Layer. Specific `PPLCNet_x0_35` model depends on args. 319 | """ 320 | model = PPLCNet(scale=0.35, **kwargs) 321 | _load_pretrained(pretrained, model, MODEL_URLS["PPLCNet_x0_35"], use_ssld) 322 | return model 323 | 324 | 325 | def PPLCNet_x0_5(pretrained=False, use_ssld=False, **kwargs): 326 | """ 327 | PPLCNet_x0_5 328 | Args: 329 | pretrained: bool=False or str. If `True` load pretrained parameters, `False` otherwise. 330 | If str, means the path of the pretrained model. 331 | use_ssld: bool=False. Whether using distillation pretrained model when pretrained=True. 332 | Returns: 333 | model: nn.Layer. Specific `PPLCNet_x0_5` model depends on args. 334 | """ 335 | model = PPLCNet(scale=0.5, **kwargs) 336 | _load_pretrained(pretrained, model, MODEL_URLS["PPLCNet_x0_5"], use_ssld) 337 | return model 338 | 339 | 340 | def PPLCNet_x0_75(pretrained=False, use_ssld=False, **kwargs): 341 | """ 342 | PPLCNet_x0_75 343 | Args: 344 | pretrained: bool=False or str. If `True` load pretrained parameters, `False` otherwise. 345 | If str, means the path of the pretrained model. 346 | use_ssld: bool=False. Whether using distillation pretrained model when pretrained=True. 347 | Returns: 348 | model: nn.Layer. Specific `PPLCNet_x0_75` model depends on args. 349 | """ 350 | model = PPLCNet(scale=0.75, **kwargs) 351 | _load_pretrained(pretrained, model, MODEL_URLS["PPLCNet_x0_75"], use_ssld) 352 | return model 353 | 354 | 355 | def PPLCNet_x1_0(pretrained=False, use_ssld=False, **kwargs): 356 | """ 357 | PPLCNet_x1_0 358 | Args: 359 | pretrained: bool=False or str. If `True` load pretrained parameters, `False` otherwise. 360 | If str, means the path of the pretrained model. 361 | use_ssld: bool=False. Whether using distillation pretrained model when pretrained=True. 362 | Returns: 363 | model: nn.Layer. Specific `PPLCNet_x1_0` model depends on args. 364 | """ 365 | model = PPLCNet(scale=1.0, **kwargs) 366 | _load_pretrained(pretrained, model, MODEL_URLS["PPLCNet_x1_0"], use_ssld) 367 | return model 368 | 369 | 370 | def PPLCNet_x1_5(pretrained=False, use_ssld=False, **kwargs): 371 | """ 372 | PPLCNet_x1_5 373 | Args: 374 | pretrained: bool=False or str. If `True` load pretrained parameters, `False` otherwise. 375 | If str, means the path of the pretrained model. 376 | use_ssld: bool=False. Whether using distillation pretrained model when pretrained=True. 377 | Returns: 378 | model: nn.Layer. Specific `PPLCNet_x1_5` model depends on args. 379 | """ 380 | model = PPLCNet(scale=1.5, **kwargs) 381 | _load_pretrained(pretrained, model, MODEL_URLS["PPLCNet_x1_5"], use_ssld) 382 | return model 383 | 384 | 385 | def PPLCNet_x2_0(pretrained=False, use_ssld=False, **kwargs): 386 | """ 387 | PPLCNet_x2_0 388 | Args: 389 | pretrained: bool=False or str. If `True` load pretrained parameters, `False` otherwise. 390 | If str, means the path of the pretrained model. 391 | use_ssld: bool=False. Whether using distillation pretrained model when pretrained=True. 392 | Returns: 393 | model: nn.Layer. Specific `PPLCNet_x2_0` model depends on args. 394 | """ 395 | model = PPLCNet(scale=2.0, **kwargs) 396 | _load_pretrained(pretrained, model, MODEL_URLS["PPLCNet_x2_0"], use_ssld) 397 | return model 398 | 399 | 400 | def PPLCNet_x2_5(pretrained=False, use_ssld=False, **kwargs): 401 | """ 402 | PPLCNet_x2_5 403 | Args: 404 | pretrained: bool=False or str. If `True` load pretrained parameters, `False` otherwise. 405 | If str, means the path of the pretrained model. 406 | use_ssld: bool=False. Whether using distillation pretrained model when pretrained=True. 407 | Returns: 408 | model: nn.Layer. Specific `PPLCNet_x2_5` model depends on args. 409 | """ 410 | model = PPLCNet(scale=2.5, **kwargs) 411 | _load_pretrained(pretrained, model, MODEL_URLS["PPLCNet_x2_5"], use_ssld) 412 | return model 413 | 414 | 415 | 416 | if __name__ == '__main__': 417 | decode_img = DecodeImage(to_rgb=True, channel_first=False) 418 | resize_img = ResizeImage(resize_short=256) 419 | crop_img = CropImage(size=224) 420 | 421 | scale = 1 / 255.0 422 | mean = [0.485, 0.456, 0.406] 423 | std = [0.229, 0.224, 0.225] 424 | 425 | normalize_img = NormalizeImage(scale, mean, std, order='') 426 | 427 | to_chw_img = ToCHWImage() 428 | 429 | img_path = 'images/n01440764_9780.JPEG' 430 | with open(img_path, 'rb') as f: 431 | x = f.read() 432 | 433 | x = decode_img(x) 434 | x = resize_img(x) 435 | x = crop_img(x) 436 | x = normalize_img(x) 437 | x = to_chw_img(x) 438 | 439 | batch_data = [] 440 | batch_data.append(x) 441 | batch_tensor = paddle.to_tensor(batch_data) 442 | 443 | with open('images/imagenet1k_label_list.txt', 'r', encoding='utf-8') as f: 444 | label_list = f.readlines() 445 | 446 | model_path = 'pretrained_models/PPLCNet_x1_0_pretrained' 447 | model = PPLCNet_x1_0(pretrained=model_path) 448 | model.eval() 449 | 450 | y = model(batch_tensor) 451 | y = F.softmax(y, axis=-1) 452 | 453 | y = y.numpy() 454 | probs = y[0] 455 | index = probs.argsort(axis=0)[-1:][::-1][0] 456 | score = probs[index] 457 | print(f'{label_list[index].strip()}: {score}') 458 | -------------------------------------------------------------------------------- /pretrained_models/README.md: -------------------------------------------------------------------------------- 1 | #### PP-LCNet模型下载来自官网 2 | - [PPLCNet_x1_0](https://paddle-imagenet-models-name.bj.bcebos.com/dygraph/legendary_models/PPLCNet_x1_0_pretrained.pdparams) 3 | - 其他类型模型下载可以参考`pp_lcnet.py`中的`MODEL_URLS` 4 | 5 | #### PyTorch-LCNet模型下载 6 | - [frotms/PP-LCNet-Pytorch](https://github.com/frotms/PP-LCNet-Pytorch)中的[Google Drive](https://drive.google.com/drive/folders/1mEgUtok2cUmBIp50Lg35gQU8-XPa8C-d?usp=sharing) -------------------------------------------------------------------------------- /pytorch_lcnet.py: -------------------------------------------------------------------------------- 1 | # -*- encoding: utf-8 -*- 2 | # @Author: SWHL 3 | # @Contact: liekkaskono@163.com 4 | import numpy as np 5 | import torch 6 | import torch.nn as nn 7 | import torch.nn.functional as F 8 | 9 | from utils import (CropImage, DecodeImage, NormalizeImage, ResizeImage, 10 | ToCHWImage) 11 | 12 | NET_CONFIG = { 13 | # k, in_c, out_c, s, use_se 14 | "blocks2": [[3, 16, 32, 1, False]], 15 | "blocks3": [[3, 32, 64, 2, False], [3, 64, 64, 1, False]], 16 | "blocks4": [[3, 64, 128, 2, False], [3, 128, 128, 1, False]], 17 | "blocks5": [[3, 128, 256, 2, False], [5, 256, 256, 1, False], 18 | [5, 256, 256, 1, False], [5, 256, 256, 1, False], 19 | [5, 256, 256, 1, False], [5, 256, 256, 1, False]], 20 | "blocks6": [[5, 256, 512, 2, True], [5, 512, 512, 1, True]] 21 | } 22 | 23 | 24 | def make_divisible(v, divisor=8, min_value=None): 25 | if min_value is None: 26 | min_value = divisor 27 | 28 | new_v = max(min_value, int(v + divisor / 2) // divisor * divisor) 29 | if new_v < 0.9 * v: 30 | new_v += divisor 31 | return new_v 32 | 33 | 34 | class ConvBNLayer(nn.Module): 35 | def __init__(self, num_channels, filter_size, 36 | num_filters, stride, num_groups=1): 37 | super().__init__() 38 | 39 | # TODO: 显示指定权重初始化方式 40 | self.conv = nn.Conv2d(in_channels=num_channels, 41 | out_channels=num_filters, 42 | kernel_size=filter_size, 43 | stride=stride, 44 | padding=(filter_size - 1) // 2, 45 | groups=num_groups, 46 | bias=False) 47 | 48 | self.bn = nn.BatchNorm2d(num_features=num_filters) 49 | 50 | self.hard_wish = nn.Hardswish() 51 | 52 | def forward(self, x): 53 | x = self.conv(x) 54 | x = self.bn(x) 55 | x = self.hard_wish(x) 56 | return x 57 | 58 | 59 | class SEModule(nn.Module): 60 | def __init__(self, channel, reduction=4): 61 | super().__init__() 62 | self.avg_pool = nn.AdaptiveAvgPool2d(1) 63 | self.conv1 = nn.Conv2d(in_channels=channel, 64 | out_channels=channel // reduction, 65 | kernel_size=1, 66 | stride=1, 67 | padding=0) 68 | 69 | self.relu = nn.ReLU() 70 | 71 | self.conv2 = nn.Conv2d(in_channels=channel // reduction, 72 | out_channels=channel, 73 | kernel_size=1, 74 | stride=1, 75 | padding=0) 76 | 77 | self.hard_sigmoid = nn.Hardsigmoid() 78 | 79 | def forward(self, x): 80 | identity = x 81 | x = self.avg_pool(x) 82 | 83 | x = self.conv1(x) 84 | x = self.relu(x) 85 | 86 | x = self.conv2(x) 87 | x = self.hard_sigmoid(x) 88 | x = torch.mul(identity, x) 89 | return x 90 | 91 | 92 | class DepthwiseSeparable(nn.Module): 93 | def __init__(self, num_channels, num_filters, 94 | stride, dw_size=3, use_se=False): 95 | super().__init__() 96 | self.use_se = use_se 97 | 98 | self.dw_conv = ConvBNLayer(num_channels=num_channels, 99 | num_filters=num_channels, 100 | filter_size=dw_size, 101 | stride=stride, 102 | num_groups=num_channels) 103 | 104 | if use_se: 105 | self.se = SEModule(num_channels) 106 | 107 | self.pw_conv = ConvBNLayer(num_channels=num_channels, 108 | filter_size=1, 109 | num_filters=num_filters, 110 | stride=1) 111 | 112 | def forward(self, x): 113 | x = self.dw_conv(x) 114 | 115 | if self.use_se: 116 | x = self.se(x) 117 | 118 | x = self.pw_conv(x) 119 | return x 120 | 121 | 122 | class PyTorchLCNet(nn.Module): 123 | def __init__(self, 124 | scale=1.0, 125 | class_num=1000, 126 | dropout_prob=0.2, 127 | class_expand=1280): 128 | super().__init__() 129 | self.scale = scale 130 | self.class_expand = class_expand 131 | 132 | self.conv1 = ConvBNLayer( 133 | num_channels=3, 134 | filter_size=3, 135 | num_filters=make_divisible(16 * scale), 136 | stride=2 137 | ) 138 | 139 | self.blocks2 = nn.Sequential(*[ 140 | DepthwiseSeparable( 141 | num_channels=make_divisible(in_c * scale), 142 | num_filters=make_divisible(out_c * scale), 143 | dw_size=k, 144 | stride=s, 145 | use_se=se) 146 | for k, in_c, out_c, s, se in NET_CONFIG["blocks2"] 147 | ]) 148 | 149 | self.blocks3 = nn.Sequential(*[ 150 | DepthwiseSeparable( 151 | num_channels=make_divisible(in_c * scale), 152 | num_filters=make_divisible(out_c * scale), 153 | dw_size=k, 154 | stride=s, 155 | use_se=se) 156 | for i, (k, in_c, out_c, s, se) in enumerate(NET_CONFIG["blocks3"]) 157 | ]) 158 | 159 | self.blocks4 = nn.Sequential(*[ 160 | DepthwiseSeparable( 161 | num_channels=make_divisible(in_c * scale), 162 | num_filters=make_divisible(out_c * scale), 163 | dw_size=k, 164 | stride=s, 165 | use_se=se) 166 | for i, (k, in_c, out_c, s, se) in enumerate(NET_CONFIG["blocks4"]) 167 | ]) 168 | 169 | self.blocks5 = nn.Sequential(*[ 170 | DepthwiseSeparable( 171 | num_channels=make_divisible(in_c * scale), 172 | num_filters=make_divisible(out_c * scale), 173 | dw_size=k, 174 | stride=s, 175 | use_se=se) 176 | for i, (k, in_c, out_c, s, se) in enumerate(NET_CONFIG["blocks5"]) 177 | ]) 178 | 179 | self.blocks6 = nn.Sequential(*[ 180 | DepthwiseSeparable( 181 | num_channels=make_divisible(in_c * scale), 182 | num_filters=make_divisible(out_c * scale), 183 | dw_size=k, 184 | stride=s, 185 | use_se=se) 186 | for i, (k, in_c, out_c, s, se) in enumerate(NET_CONFIG["blocks6"]) 187 | ]) 188 | 189 | self.avg_pool = nn.AdaptiveAvgPool2d(1) 190 | 191 | self.last_conv = nn.Conv2d( 192 | in_channels=make_divisible(NET_CONFIG["blocks6"][-1][2] * scale), 193 | out_channels=self.class_expand, 194 | kernel_size=1, 195 | stride=1, 196 | padding=0, 197 | bias=False 198 | ) 199 | 200 | self.hard_swish = nn.Hardswish() 201 | self.dropout = nn.Dropout(p=dropout_prob) 202 | self.flatten = nn.Flatten(start_dim=1, end_dim=-1) 203 | 204 | self.fc = nn.Linear(self.class_expand, class_num) 205 | 206 | def forward(self, x): 207 | x = self.conv1(x) 208 | 209 | x = self.blocks2(x) 210 | x = self.blocks3(x) 211 | x = self.blocks4(x) 212 | x = self.blocks5(x) 213 | x = self.blocks6(x) 214 | 215 | x = self.avg_pool(x) 216 | x = self.last_conv(x) 217 | x = self.hard_swish(x) 218 | x = self.dropout(x) 219 | x = self.flatten(x) 220 | x = self.fc(x) 221 | return x 222 | 223 | 224 | def PyTorchLCNet_x1_0(pretrained=False, use_ssld=False, 225 | pretrained_path=None, **kwargs): 226 | """ 227 | PyTorchLCNet_x1_0 228 | Args: 229 | pretrained: bool=False or str. If `True` load pretrained parameters, `False` otherwise. 230 | If str, means the path of the pretrained model. 231 | use_ssld: bool=False. Whether using distillation pretrained model when pretrained=True. 232 | Returns: 233 | model: nn.Layer. Specific `PPLCNet_x1_0` model depends on args. 234 | """ 235 | model = PyTorchLCNet(scale=1.0, **kwargs) 236 | if pretrained: 237 | state_dict = torch.load(pretrained_path) 238 | model.load_state_dict(state_dict) 239 | return model 240 | 241 | 242 | if __name__ == '__main__': 243 | decode_img = DecodeImage(to_rgb=True, channel_first=False) 244 | resize_img = ResizeImage(resize_short=256) 245 | crop_img = CropImage(size=224) 246 | 247 | scale = 1 / 255.0 248 | mean = [0.485, 0.456, 0.406] 249 | std = [0.229, 0.224, 0.225] 250 | 251 | normalize_img = NormalizeImage(scale, mean, std, order='') 252 | 253 | to_chw_img = ToCHWImage() 254 | 255 | img_path = 'images/n01440764_9780.JPEG' 256 | with open(img_path, 'rb') as f: 257 | x = f.read() 258 | 259 | x = decode_img(x) 260 | x = resize_img(x) 261 | x = crop_img(x) 262 | x = normalize_img(x) 263 | x = to_chw_img(x) 264 | 265 | batch_data = [] 266 | batch_data.append(x) 267 | batch_tensor = torch.Tensor(np.array(batch_data)) 268 | 269 | with open('images/imagenet1k_label_list.txt', 'r', encoding='utf-8') as f: 270 | label_list = f.readlines() 271 | 272 | model_path = 'pretrained_models/PPLCNet_x1_0_pretrained.pth' 273 | model = PyTorchLCNet_x1_0(pretrained=True, 274 | pretrained_path=model_path, 275 | class_num=1000) 276 | model.eval() 277 | 278 | y = model(batch_tensor) 279 | y = F.softmax(y, dim=-1) 280 | y = y.detach().numpy() 281 | probs = y[0] 282 | index = probs.argsort(axis=0)[-1:][::-1][0] 283 | score = probs[index] 284 | print(f'{label_list[index].strip()}: {score}') 285 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | numpy>=1.22 2 | opencv_python==4.5.3.56 3 | paddlepaddle 4 | six==1.16.0 5 | torch 6 | -------------------------------------------------------------------------------- /utils.py: -------------------------------------------------------------------------------- 1 | # -*- encoding: utf-8 -*- 2 | # @Author: SWHL 3 | # @Contact: liekkaskono@163.com 4 | from functools import partial 5 | 6 | import cv2 7 | import numpy as np 8 | import six 9 | from PIL import Image 10 | 11 | 12 | class UnifiedResize(object): 13 | def __init__(self, interpolation=None, backend="cv2"): 14 | _cv2_interp_from_str = { 15 | 'nearest': cv2.INTER_NEAREST, 16 | 'bilinear': cv2.INTER_LINEAR, 17 | 'area': cv2.INTER_AREA, 18 | 'bicubic': cv2.INTER_CUBIC, 19 | 'lanczos': cv2.INTER_LANCZOS4 20 | } 21 | _pil_interp_from_str = { 22 | 'nearest': Image.NEAREST, 23 | 'bilinear': Image.BILINEAR, 24 | 'bicubic': Image.BICUBIC, 25 | 'box': Image.BOX, 26 | 'lanczos': Image.LANCZOS, 27 | 'hamming': Image.HAMMING 28 | } 29 | 30 | def _pil_resize(src, size, resample): 31 | pil_img = Image.fromarray(src) 32 | pil_img = pil_img.resize(size, resample) 33 | return np.asarray(pil_img) 34 | 35 | if backend.lower() == "cv2": 36 | if isinstance(interpolation, str): 37 | interpolation = _cv2_interp_from_str[interpolation.lower()] 38 | # compatible with opencv < version 4.4.0 39 | elif interpolation is None: 40 | interpolation = cv2.INTER_LINEAR 41 | self.resize_func = partial(cv2.resize, interpolation=interpolation) 42 | elif backend.lower() == "pil": 43 | if isinstance(interpolation, str): 44 | interpolation = _pil_interp_from_str[interpolation.lower()] 45 | self.resize_func = partial(_pil_resize, resample=interpolation) 46 | else: 47 | print( 48 | f"The backend of Resize only support \"cv2\" or \"PIL\". \"f{backend}\" is unavailable. Use \"cv2\" instead." 49 | ) 50 | self.resize_func = cv2.resize 51 | 52 | def __call__(self, src, size): 53 | return self.resize_func(src, size) 54 | 55 | 56 | class DecodeImage(object): 57 | """ decode image """ 58 | 59 | def __init__(self, to_rgb=True, to_np=False, channel_first=False): 60 | self.to_rgb = to_rgb 61 | self.to_np = to_np # to numpy 62 | self.channel_first = channel_first # only enabled when to_np is True 63 | 64 | def __call__(self, img): 65 | if six.PY2: 66 | assert type(img) is str and len( 67 | img) > 0, "invalid input 'img' in DecodeImage" 68 | else: 69 | assert type(img) is bytes and len( 70 | img) > 0, "invalid input 'img' in DecodeImage" 71 | data = np.frombuffer(img, dtype='uint8') 72 | img = cv2.imdecode(data, 1) 73 | if self.to_rgb: 74 | assert img.shape[2] == 3, 'invalid shape of image[%s]' % ( 75 | img.shape) 76 | img = img[:, :, ::-1] 77 | 78 | if self.channel_first: 79 | img = img.transpose((2, 0, 1)) 80 | 81 | return img 82 | 83 | 84 | class ResizeImage(object): 85 | """ resize image """ 86 | 87 | def __init__(self, 88 | size=None, 89 | resize_short=None, 90 | interpolation=None, 91 | backend="cv2"): 92 | if resize_short is not None and resize_short > 0: 93 | self.resize_short = resize_short 94 | self.w = None 95 | self.h = None 96 | elif size is not None: 97 | self.resize_short = None 98 | self.w = size if type(size) is int else size[0] 99 | self.h = size if type(size) is int else size[1] 100 | else: 101 | raise ValueError("invalid params for ReisizeImage for '\ 102 | 'both 'size' and 'resize_short' are None") 103 | 104 | self._resize_func = UnifiedResize( 105 | interpolation=interpolation, backend=backend) 106 | 107 | def __call__(self, img): 108 | img_h, img_w = img.shape[:2] 109 | if self.resize_short is not None: 110 | percent = float(self.resize_short) / min(img_w, img_h) 111 | w = int(round(img_w * percent)) 112 | h = int(round(img_h * percent)) 113 | else: 114 | w = self.w 115 | h = self.h 116 | return self._resize_func(img, (w, h)) 117 | 118 | 119 | class CropImage(object): 120 | """ crop image """ 121 | 122 | def __init__(self, size): 123 | if type(size) is int: 124 | self.size = (size, size) 125 | else: 126 | self.size = size # (h, w) 127 | 128 | def __call__(self, img): 129 | w, h = self.size 130 | img_h, img_w = img.shape[:2] 131 | w_start = (img_w - w) // 2 132 | h_start = (img_h - h) // 2 133 | 134 | w_end = w_start + w 135 | h_end = h_start + h 136 | return img[h_start:h_end, w_start:w_end, :] 137 | 138 | 139 | class NormalizeImage(object): 140 | """ normalize image such as substract mean, divide std 141 | """ 142 | 143 | def __init__(self, 144 | scale=None, 145 | mean=None, 146 | std=None, 147 | order='chw', 148 | output_fp16=False, 149 | channel_num=3): 150 | if isinstance(scale, str): 151 | scale = eval(scale) 152 | assert channel_num in [ 153 | 3, 4 154 | ], "channel number of input image should be set to 3 or 4." 155 | self.channel_num = channel_num 156 | self.output_dtype = 'float16' if output_fp16 else 'float32' 157 | self.scale = np.float32(scale if scale is not None else 1.0 / 255.0) 158 | self.order = order 159 | mean = mean if mean is not None else [0.485, 0.456, 0.406] 160 | std = std if std is not None else [0.229, 0.224, 0.225] 161 | 162 | shape = (3, 1, 1) if self.order == 'chw' else (1, 1, 3) 163 | self.mean = np.array(mean).reshape(shape).astype('float32') 164 | self.std = np.array(std).reshape(shape).astype('float32') 165 | 166 | def __call__(self, img): 167 | from PIL import Image 168 | if isinstance(img, Image.Image): 169 | img = np.array(img) 170 | 171 | assert isinstance(img, 172 | np.ndarray), "invalid input 'img' in NormalizeImage" 173 | 174 | img = (img.astype('float32') * self.scale - self.mean) / self.std 175 | 176 | if self.channel_num == 4: 177 | img_h = img.shape[1] if self.order == 'chw' else img.shape[0] 178 | img_w = img.shape[2] if self.order == 'chw' else img.shape[1] 179 | pad_zeros = np.zeros( 180 | (1, img_h, img_w)) if self.order == 'chw' else np.zeros( 181 | (img_h, img_w, 1)) 182 | img = (np.concatenate( 183 | (img, pad_zeros), axis=0) 184 | if self.order == 'chw' else np.concatenate( 185 | (img, pad_zeros), axis=2)) 186 | return img.astype(self.output_dtype) 187 | 188 | 189 | class ToCHWImage(object): 190 | """ convert hwc image to chw image 191 | """ 192 | 193 | def __init__(self): 194 | pass 195 | 196 | def __call__(self, img): 197 | from PIL import Image 198 | if isinstance(img, Image.Image): 199 | img = np.array(img) 200 | 201 | return img.transpose((2, 0, 1)) 202 | --------------------------------------------------------------------------------