├── .gitignore ├── LICENSE ├── MANIFEST.in ├── README.md ├── example ├── README.md ├── classification.py ├── demo.py ├── detection.py ├── pointdet.py └── sam_segmentation.py ├── image ├── classification.gif ├── deer.jpg ├── demo.gif ├── detection.gif ├── dog.jpg ├── framingo.jpg ├── penguin.jpg ├── pointdet.gif └── sam_segmentation.gif ├── requirements.txt ├── setup.py └── streamlit_image_annotation ├── Classification ├── __init__.py └── frontend │ ├── .env │ ├── .prettierrc │ ├── package.json │ ├── public │ ├── bootstrap.min.css │ └── index.html │ ├── src │ ├── Classification.tsx │ ├── ThemeSwitcher.tsx │ ├── index.tsx │ └── react-app-env.d.ts │ ├── tsconfig.json │ └── yarn.lock ├── Detection ├── __init__.py └── frontend │ ├── .env │ ├── .prettierrc │ ├── package.json │ ├── public │ ├── bootstrap.min.css │ └── index.html │ ├── src │ ├── BBox.tsx │ ├── BBoxCanvas.tsx │ ├── Detection.tsx │ ├── ThemeSwitcher.tsx │ ├── index.tsx │ └── react-app-env.d.ts │ ├── tsconfig.json │ └── yarn.lock ├── Point ├── __init__.py └── frontend │ ├── .env │ ├── .prettierrc │ ├── package.json │ ├── public │ ├── bootstrap.min.css │ └── index.html │ ├── src │ ├── Point.tsx │ ├── PointCanvas.tsx │ ├── PointDet.tsx │ ├── ThemeSwitcher.tsx │ ├── index.tsx │ └── react-app-env.d.ts │ ├── tsconfig.json │ └── yarn.lock └── __init__.py /.gitignore: -------------------------------------------------------------------------------- 1 | ######################################################################## 2 | # Python - https://github.com/github/gitignore/blob/master/Python.gitignore 3 | ######################################################################## 4 | # Byte-compiled / optimized / DLL files 5 | __pycache__/ 6 | *.py[cod] 7 | *$py.class 8 | 9 | # Distribution / packaging 10 | build/ 11 | dist/ 12 | eggs/ 13 | .eggs/ 14 | *.egg-info/ 15 | *.egg 16 | 17 | # Unit test / coverage reports 18 | .coverage 19 | .coverage\.* 20 | .pytest_cache/ 21 | .mypy_cache/ 22 | test-reports 23 | 24 | # Test fixtures 25 | cffi_bin 26 | 27 | # Pyenv Stuff 28 | .python-version 29 | 30 | ######################################################################## 31 | # OSX - https://github.com/github/gitignore/blob/master/Global/macOS.gitignore 32 | ######################################################################## 33 | .DS_Store 34 | .DocumentRevisions-V100 35 | .fseventsd 36 | .Spotlight-V100 37 | .TemporaryItems 38 | .Trashes 39 | .VolumeIcon.icns 40 | .com.apple.timemachine.donotpresent 41 | 42 | ######################################################################## 43 | # node - https://github.com/github/gitignore/blob/master/Node.gitignore 44 | ######################################################################## 45 | # Logs 46 | npm-debug.log* 47 | yarn-debug.log* 48 | yarn-error.log* 49 | 50 | # Dependency directories 51 | node_modules/ 52 | 53 | # Coverage directory used by tools like istanbul 54 | coverage/ 55 | 56 | # Lockfiles 57 | #yarn.lock 58 | package-lock.json 59 | 60 | ######################################################################## 61 | # JetBrains 62 | ######################################################################## 63 | .idea 64 | 65 | ######################################################################## 66 | # VSCode 67 | ######################################################################## 68 | .vscode/ 69 | 70 | ######################################################################## 71 | # Other 72 | ######################################################################## 73 | .venv/ 74 | -------------------------------------------------------------------------------- /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 | 203 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | recursive-include streamlit_image_annotation/*/frontend/build * -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Streamlit Image Annotation 2 | 3 | Streamlit component for image annotation. 4 | 5 | [](https://st-image-annotation.streamlit.app/) 6 | [](https://pypi.org/project/streamlit-image-annotation/) 7 |  8 | # Features 9 | * You can easily launch an image annotation tool using streamlit. 10 | * By customizing the pre- and post-processing, you can achieve your preferred annotation workflow. 11 | * Currently supports classification, detection, point detection tasks. 12 | * Simple UI that is easy to navigate. 13 | 14 | # Install 15 | 16 | ```sh 17 | pip install streamlit-image-annotation 18 | ``` 19 | 20 | # Example Usage 21 | If you want to see other use cases, please check inside the examples folder. 22 | 23 | ```python 24 | from glob import glob 25 | import pandas as pd 26 | import streamlit as st 27 | from streamlit_image_annotation import classification 28 | 29 | label_list = ['deer', 'human', 'dog', 'penguin', 'framingo', 'teddy bear'] 30 | image_path_list = glob('image/*.jpg') 31 | if 'result_df' not in st.session_state: 32 | st.session_state['result_df'] = pd.DataFrame.from_dict({'image': image_path_list, 'label': [0]*len(image_path_list)}).copy() 33 | 34 | num_page = st.slider('page', 0, len(image_path_list)-1, 0) 35 | label = classification(image_path_list[num_page], 36 | label_list=label_list, 37 | default_label_index=int(st.session_state['result_df'].loc[num_page, 'label'])) 38 | 39 | if label is not None and label['label'] != st.session_state['result_df'].loc[num_page, 'label']: 40 | st.session_state['result_df'].loc[num_page, 'label'] = label_list.index(label['label']) 41 | st.table(st.session_state['result_df']) 42 | ``` 43 | 44 | # API 45 | 46 | ```python 47 | classification( 48 | image_path: str, 49 | label_list: List[str], 50 | default_label_index: Optional[int] = None, 51 | height: int = 512, 52 | width: int = 512, 53 | key: Optional[str] = None 54 | ) 55 | ``` 56 | 57 | - **image_path**: Image path. 58 | - **label_list**: List of label candidates. 59 | - **default_label_index**: Initial label index. 60 | - **height**: The maximum height of the displayed image. 61 | - **width**: The maximum width of the displayed image. 62 | - **key**: An optional string to use as the unique key for the widget. Assign a key so the component is not remount every time the script is rerun. 63 | 64 | - **Component Value**: {'label': label_name} 65 | 66 | Example: [example code](example/classification.py) 67 | 68 | ```python 69 | detection( 70 | image_path: str, 71 | label_list: List[str], 72 | bboxes: Optional[List[List[int, int, int, int]]] = None, 73 | labels: Optional[List[int]] = None, 74 | height: int = 512, 75 | width: int = 512, 76 | line_width: int = 5, 77 | use_space: bool = False, 78 | key: Optional[str] = None 79 | ) 80 | ``` 81 | 82 | - **image_path**: Image path. 83 | - **label_list**: List of label candidates. 84 | - **bboxes**: Initial list of bounding boxes, where each bbox is in the format [x, y, w, h]. 85 | - **labels**: List of label for each initial bbox. 86 | - **height**: The maximum height of the displayed image. 87 | - **width**: The maximum width of the displayed image. 88 | - **line_width**: The stroke width of the bbox. 89 | - **use_space**: Enable Space key for complete. 90 | - **key**: An optional string to use as the unique key for the widget. Assign a key so the component is not remount every time the script is rerun. 91 | 92 | - **Component Value**: \[{'bbox':[x,y,width, height], 'label_id': label_id, 'label': label_name},...\] 93 | 94 | Example: [example code](example/detection.py) 95 | 96 | ```python 97 | pointdet( 98 | image_path: str, 99 | label_list: List[str], 100 | points: Optional[List[List[int, int]]] = None, 101 | labels: Optional[List[int]] = None, 102 | height: int = 512, 103 | width: int = 512, 104 | point_width: int =3, 105 | use_space: bool = False, 106 | key: Optional[str] = None 107 | ) 108 | ``` 109 | 110 | - **image_path**: Image path. 111 | - **label_list**: List of label candidates. 112 | - **points**: Initial list of points, where each point is in the format [x, y]. 113 | - **labels**: List of label for each initial bbox. 114 | - **height**: The maximum height of the displayed image. 115 | - **width**: The maximum width of the displayed image. 116 | - **point_width**: The stroke width of the bbox. 117 | - **use_space**: Enable Space key for complete. 118 | - **key**: An optional string to use as the unique key for the widget. Assign a key so the component is not remount every time the script is rerun. 119 | 120 | - **Component Value**: \[{'bbox':[x,y], 'label_id': label_id, 'label': label_name},...\] 121 | 122 | Example: [example code](example/pointdet.py) 123 | 124 | # Future Work 125 | * Addition of component for segmentation task. 126 | 127 | # Development 128 | ## setup 129 | ```bash 130 | cd Streamlit-Image-Annotation/ 131 | export PYTHONPATH=$PWD 132 | ``` 133 | and set `IS_RELEASE = False` in `Streamlit-Image-Annotation/__init__.py`. 134 | 135 | 136 | ## start frontend 137 | ```bash 138 | git clone https://github.com/hirune924/Streamlit-Image-Annotation.git 139 | cd Streamlit-Image-Annotation/streamlit_image_annotation/Detection/frontend 140 | yarn 141 | yarn start 142 | ``` 143 | 144 | ## start streamlit 145 | ```bash 146 | cd Streamlit-Image-Annotation/ 147 | streamlit run streamlit_image_annotation/Detection/__init__.py 148 | ``` 149 | 150 | ## build 151 | ```bash 152 | cd Streamlit-Image-Annotation/Classification/frontend 153 | yarn build 154 | cd Streamlit-Image-Annotation/Detection/frontend 155 | yarn build 156 | cd Streamlit-Image-Annotation/Point/frontend 157 | yarn build 158 | ``` 159 | and set `IS_RELEASE = True` in `Streamlit-Image-Annotation/__init__.py`. 160 | 161 | ## make wheel 162 | ```bash 163 | python setup.py sdist bdist_wheel 164 | ``` 165 | ## upload 166 | ```bash 167 | python3 -m twine upload --repository testpypi dist/* 168 | python -m pip install --index-url https://test.pypi.org/simple/ --no-deps streamlit-image-annotation 169 | ``` 170 | ```bash 171 | twine upload dist/* 172 | ``` 173 | -------------------------------------------------------------------------------- /example/README.md: -------------------------------------------------------------------------------- 1 | # Examples 2 | ## Classification 3 | ``` 4 | streamlit run classification.py 5 | ``` 6 |  7 | ## Detection 8 | ``` 9 | streamlit run detection.py 10 | ``` 11 |  12 | 13 | ## Point Detection 14 | ``` 15 | streamlit run pointdet.py 16 | ``` 17 |  18 | 19 | ## Segmentation via SAM 20 | ``` 21 | streamlit run sam_segmentation.py 22 | ``` 23 |  24 | -------------------------------------------------------------------------------- /example/classification.py: -------------------------------------------------------------------------------- 1 | from glob import glob 2 | import pandas as pd 3 | import streamlit as st 4 | from streamlit_image_annotation import classification 5 | 6 | label_list = ['deer', 'human', 'dog', 'penguin', 'framingo', 'teddy bear'] 7 | image_path_list = glob('image/*.jpg') 8 | if 'result_df' not in st.session_state: 9 | st.session_state['result_df'] = pd.DataFrame.from_dict({'image': image_path_list, 'label': [0]*len(image_path_list)}).copy() 10 | 11 | num_page = st.slider('page', 0, len(image_path_list)-1, 0) 12 | 13 | label = classification(image_path_list[num_page], 14 | label_list=label_list, 15 | default_label_index=int(st.session_state['result_df'].loc[num_page, 'label'])) 16 | 17 | if label is not None and label['label'] != st.session_state['result_df'].loc[num_page, 'label']: 18 | st.session_state['result_df'].loc[num_page, 'label'] = label_list.index(label['label']) 19 | st.table(st.session_state['result_df']) -------------------------------------------------------------------------------- /example/demo.py: -------------------------------------------------------------------------------- 1 | import streamlit as st 2 | from glob import glob 3 | import pandas as pd 4 | from streamlit_image_annotation import detection, classification, pointdet 5 | 6 | mode = st.tabs(["Detection", "Classification", "Point"]) 7 | label_list = ['deer', 'human', 'dog', 'penguin', 'framingo', 'teddy bear'] 8 | image_path_list = glob('image/*.jpg') 9 | 10 | with mode[0]: 11 | if 'result_dict_det' not in st.session_state: 12 | result_dict = {} 13 | for img in image_path_list: 14 | result_dict[img] = {'bboxes': [[0,0,100,100],[10,20,50,150]],'labels':[0,3]} 15 | st.session_state['result_dict_det'] = result_dict.copy() 16 | 17 | num_page = st.slider('page', 0, len(image_path_list)-1, 0, key='slider_det') 18 | target_image_path = image_path_list[num_page] 19 | 20 | new_labels = detection(image_path=target_image_path, 21 | bboxes=st.session_state['result_dict_det'][target_image_path]['bboxes'], 22 | labels=st.session_state['result_dict_det'][target_image_path]['labels'], 23 | label_list=label_list, use_space=True, key=target_image_path+'_det') 24 | if new_labels is not None: 25 | st.session_state['result_dict_det'][target_image_path]['bboxes'] = [v['bbox'] for v in new_labels] 26 | st.session_state['result_dict_det'][target_image_path]['labels'] = [v['label_id'] for v in new_labels] 27 | st.json(st.session_state['result_dict_det']) 28 | 29 | with mode[1]: 30 | 31 | if 'result_df_cls' not in st.session_state: 32 | st.session_state['result_df_cls'] = pd.DataFrame.from_dict({'image': image_path_list, 'label': [0]*len(image_path_list)}).copy() 33 | 34 | num_page = st.slider('page', 0, len(image_path_list)-1, 0, key='slider_cls') 35 | 36 | label = classification(image_path_list[num_page], 37 | label_list=label_list, 38 | default_label_index=int(st.session_state['result_df_cls'].loc[num_page, 'label'])) 39 | 40 | if label is not None and label['label'] != st.session_state['result_df_cls'].loc[num_page, 'label']: 41 | st.session_state['result_df_cls'].loc[num_page, 'label'] = label_list.index(label['label']) 42 | st.table(st.session_state['result_df_cls']) 43 | 44 | with mode[2]: 45 | 46 | if 'result_dict_point' not in st.session_state: 47 | result_dict = {} 48 | for img in image_path_list: 49 | result_dict[img] = {'points': [[0,0],[50,150], [200,200]],'labels':[0,3,4]} 50 | st.session_state['result_dict_point'] = result_dict.copy() 51 | 52 | num_page = st.slider('page', 0, len(image_path_list)-1, 0, key='slider_point') 53 | target_image_path = image_path_list[num_page] 54 | 55 | new_labels = pointdet(image_path=target_image_path, 56 | label_list=label_list, 57 | points=st.session_state['result_dict_point'][target_image_path]['points'], 58 | labels=st.session_state['result_dict_point'][target_image_path]['labels'], 59 | use_space=True, key=target_image_path+'_point') 60 | if new_labels is not None: 61 | st.session_state['result_dict_point'][target_image_path]['points'] = [v['point'] for v in new_labels] 62 | st.session_state['result_dict_point'][target_image_path]['labels'] = [v['label_id'] for v in new_labels] 63 | st.json(st.session_state['result_dict_point']) -------------------------------------------------------------------------------- /example/detection.py: -------------------------------------------------------------------------------- 1 | import streamlit as st 2 | from glob import glob 3 | from streamlit_image_annotation import detection 4 | 5 | label_list = ['deer', 'human', 'dog', 'penguin', 'framingo', 'teddy bear'] 6 | image_path_list = glob('image/*.jpg') 7 | if 'result_dict' not in st.session_state: 8 | result_dict = {} 9 | for img in image_path_list: 10 | result_dict[img] = {'bboxes': [[0,0,100,100],[10,20,50,150]],'labels':[0,3]} 11 | st.session_state['result_dict'] = result_dict.copy() 12 | 13 | num_page = st.slider('page', 0, len(image_path_list)-1, 0, key='slider') 14 | target_image_path = image_path_list[num_page] 15 | 16 | new_labels = detection(image_path=target_image_path, 17 | bboxes=st.session_state['result_dict'][target_image_path]['bboxes'], 18 | labels=st.session_state['result_dict'][target_image_path]['labels'], 19 | label_list=label_list, use_space=True, key=target_image_path) 20 | if new_labels is not None: 21 | st.session_state['result_dict'][target_image_path]['bboxes'] = [v['bbox'] for v in new_labels] 22 | st.session_state['result_dict'][target_image_path]['labels'] = [v['label_id'] for v in new_labels] 23 | st.json(st.session_state['result_dict']) -------------------------------------------------------------------------------- /example/pointdet.py: -------------------------------------------------------------------------------- 1 | import streamlit as st 2 | from glob import glob 3 | from streamlit_image_annotation import pointdet 4 | 5 | label_list = ['deer', 'human', 'dog', 'penguin', 'framingo', 'teddy bear'] 6 | image_path_list = glob('image/*.jpg') 7 | if 'result_dict' not in st.session_state: 8 | result_dict = {} 9 | for img in image_path_list: 10 | result_dict[img] = {'points': [[0,0],[50,150], [200,200]],'labels':[0,3,4]} 11 | st.session_state['result_dict'] = result_dict.copy() 12 | 13 | num_page = st.slider('page', 0, len(image_path_list)-1, 0, key='slider') 14 | target_image_path = image_path_list[num_page] 15 | 16 | new_labels = pointdet(image_path=target_image_path, 17 | label_list=label_list, 18 | points=st.session_state['result_dict'][target_image_path]['points'], 19 | labels=st.session_state['result_dict'][target_image_path]['labels'], 20 | use_space=True, key=target_image_path) 21 | if new_labels is not None: 22 | st.session_state['result_dict'][target_image_path]['points'] = [v['point'] for v in new_labels] 23 | st.session_state['result_dict'][target_image_path]['labels'] = [v['label_id'] for v in new_labels] 24 | st.json(st.session_state['result_dict']) -------------------------------------------------------------------------------- /example/sam_segmentation.py: -------------------------------------------------------------------------------- 1 | import streamlit as st 2 | from glob import glob 3 | from streamlit_image_annotation import detection 4 | import cv2 5 | import numpy as np 6 | import urllib.request 7 | import torch 8 | import os 9 | import matplotlib.pyplot as plt 10 | 11 | try: 12 | from segment_anything import SamPredictor, sam_model_registry 13 | except: 14 | import subprocess 15 | subprocess.call(["pip","install","git+https://github.com/facebookresearch/segment-anything.git"]) 16 | subprocess.call(["mkdir",".sam"]) 17 | from segment_anything import SamPredictor, sam_model_registry 18 | 19 | def get_colormap(label_names, colormap_name='gist_rainbow'): 20 | colormap = [] 21 | cmap = plt.get_cmap(colormap_name) 22 | for idx, l in enumerate(label_names): 23 | rgb = [int(d) for d in np.array(cmap(float(idx)/len(label_names)))*255][:3] 24 | #colormap[l] = ('#%02x%02x%02x' % tuple(rgb)) 25 | colormap.append(rgb) 26 | return colormap 27 | 28 | class SAMPredictor: 29 | def __init__(self, model_type, device, ckpt_dir='.sam'): 30 | os.makedirs(ckpt_dir, exist_ok=True) 31 | url = 'https://dl.fbaipublicfiles.com/segment_anything/' 32 | ckpt_dict = {'vit_b': 'sam_vit_b_01ec64.pth', 33 | 'vit_l': 'sam_vit_l_0b3195.pth', 34 | 'vit_h': 'sam_vit_h_4b8939.pth'} 35 | @st.cache_resource() 36 | def get_sam_predictor(ckpt, model_type, device): 37 | sam = sam_model_registry[model_type](checkpoint=ckpt) 38 | sam.to(device=device) 39 | predictor = SamPredictor(sam) 40 | return predictor 41 | with st.spinner('Downloading SAM model...'): 42 | if not os.path.exists(os.path.join(ckpt_dir, ckpt_dict[model_type])): 43 | urllib.request.urlretrieve(url+ckpt_dict[model_type], os.path.join(ckpt_dir, ckpt_dict[model_type])) 44 | 45 | self.model_type = model_type 46 | self.device = device 47 | self.predictor = get_sam_predictor(os.path.join(ckpt_dir, ckpt_dict[model_type]), model_type, device) 48 | 49 | def set_image(self, image): 50 | self.image = image 51 | self.predictor.set_image(image) 52 | 53 | def predict(self, bboxes): 54 | ''' 55 | bboxes: [[x,y,x,y], [x,y,x,y]] 56 | ''' 57 | input_boxes = torch.tensor(bboxes).to(self.device) 58 | transformed_boxes = self.predictor.transform.apply_boxes_torch(input_boxes, self.image.shape[:2]) 59 | masks, _, _ = self.predictor.predict_torch( 60 | point_coords=None, 61 | point_labels=None, 62 | boxes=transformed_boxes, 63 | multimask_output=False, 64 | ) 65 | masks = masks.cpu().numpy() 66 | return masks 67 | 68 | def draw_masks(self, masks, colormap, labels): 69 | result = self.image.copy() 70 | for idx, m in enumerate(masks): 71 | color = np.array(colormap[labels[idx]]) 72 | h, w = m.shape[-2:] 73 | mask_image = m.reshape(h, w, 1) * color.reshape(1, 1, -1) 74 | result = np.where(np.tile(m.reshape(h, w, 1),(1,1,3)),(result * 0.5 + mask_image * 0.5).astype(np.uint8), result) 75 | return result 76 | 77 | sam_predictor = SAMPredictor(model_type='vit_b', device='cpu') 78 | label_list = ['deer', 'human', 'dog', 'penguin', 'framingo', 'teddy bear'] 79 | colormap = get_colormap(label_list, colormap_name='gist_rainbow') 80 | image_path_list = glob('image/*.jpg') 81 | if 'result_dict' not in st.session_state: 82 | result_dict = {} 83 | for img in image_path_list: 84 | result_dict[img] = {'bboxes': [],'labels':[]} 85 | st.session_state['result_dict'] = result_dict.copy() 86 | 87 | num_page = st.slider('page', 0, len(image_path_list)-1, 0, key='slider') 88 | target_image_path = image_path_list[num_page] 89 | 90 | new_labels = detection(image_path=target_image_path, 91 | bboxes=st.session_state['result_dict'][target_image_path]['bboxes'], 92 | labels=st.session_state['result_dict'][target_image_path]['labels'], 93 | label_list=label_list, key=target_image_path) 94 | if new_labels is not None: 95 | st.session_state['result_dict'][target_image_path]['bboxes'] = [v['bbox'] for v in new_labels] 96 | st.session_state['result_dict'][target_image_path]['labels'] = [v['label_id'] for v in new_labels] 97 | 98 | image = cv2.imread(target_image_path) 99 | image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) 100 | sam_predictor.set_image(image) 101 | if len(st.session_state['result_dict'][target_image_path]['bboxes'])!=0: 102 | input_boxes = [[b[0], b[1], b[2]+b[0], b[3]+b[1]] for b in st.session_state['result_dict'][target_image_path]['bboxes']] 103 | masks = sam_predictor.predict(input_boxes) 104 | draw_image = sam_predictor.draw_masks(masks, colormap, [l for l in st.session_state['result_dict'][target_image_path]['labels']]) 105 | st.image(draw_image) 106 | else: 107 | st.image(image) 108 | -------------------------------------------------------------------------------- /image/classification.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hirune924/Streamlit-Image-Annotation/abd8f7e7c060fa04e1b47bd138d5306328d4cbf1/image/classification.gif -------------------------------------------------------------------------------- /image/deer.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hirune924/Streamlit-Image-Annotation/abd8f7e7c060fa04e1b47bd138d5306328d4cbf1/image/deer.jpg -------------------------------------------------------------------------------- /image/demo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hirune924/Streamlit-Image-Annotation/abd8f7e7c060fa04e1b47bd138d5306328d4cbf1/image/demo.gif -------------------------------------------------------------------------------- /image/detection.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hirune924/Streamlit-Image-Annotation/abd8f7e7c060fa04e1b47bd138d5306328d4cbf1/image/detection.gif -------------------------------------------------------------------------------- /image/dog.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hirune924/Streamlit-Image-Annotation/abd8f7e7c060fa04e1b47bd138d5306328d4cbf1/image/dog.jpg -------------------------------------------------------------------------------- /image/framingo.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hirune924/Streamlit-Image-Annotation/abd8f7e7c060fa04e1b47bd138d5306328d4cbf1/image/framingo.jpg -------------------------------------------------------------------------------- /image/penguin.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hirune924/Streamlit-Image-Annotation/abd8f7e7c060fa04e1b47bd138d5306328d4cbf1/image/penguin.jpg -------------------------------------------------------------------------------- /image/pointdet.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hirune924/Streamlit-Image-Annotation/abd8f7e7c060fa04e1b47bd138d5306328d4cbf1/image/pointdet.gif -------------------------------------------------------------------------------- /image/sam_segmentation.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hirune924/Streamlit-Image-Annotation/abd8f7e7c060fa04e1b47bd138d5306328d4cbf1/image/sam_segmentation.gif -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | streamlit 2 | Pillow 3 | streamlit-image-annotation 4 | matplotlib 5 | pandas 6 | numpy 7 | opencv-python-headless 8 | torch 9 | git+https://github.com/facebookresearch/segment-anything.git 10 | torchvision 11 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import setuptools 2 | 3 | with open("README.md", "r") as fh: 4 | long_description = fh.read() 5 | 6 | setuptools.setup( 7 | name="streamlit_image_annotation", 8 | version="0.4.0", 9 | author="hirune924", 10 | description="streamlit components for image annotation", 11 | long_description=long_description, 12 | long_description_content_type="text/markdown", 13 | url="https://github.com/hirune924/Streamlit-Image-Annotation", 14 | packages=setuptools.find_packages(), 15 | include_package_data=True, 16 | classifiers=[], 17 | keywords=['Python', 'Streamlit', 'React', 'JavaScript'], 18 | python_requires=">=3.6", 19 | install_requires=[ 20 | "streamlit >= 0.63", 21 | ], 22 | ) -------------------------------------------------------------------------------- /streamlit_image_annotation/Classification/__init__.py: -------------------------------------------------------------------------------- 1 | import os 2 | import streamlit.components.v1 as components 3 | from streamlit.components.v1.components import CustomComponent 4 | 5 | import streamlit as st 6 | try: 7 | from streamlit.elements.image import image_to_url 8 | except: 9 | from streamlit.elements.lib.image_utils import image_to_url 10 | from PIL import Image 11 | 12 | from hashlib import md5 13 | from streamlit_image_annotation import IS_RELEASE 14 | 15 | if IS_RELEASE: 16 | absolute_path = os.path.dirname(os.path.abspath(__file__)) 17 | build_path = os.path.join(absolute_path, "frontend/build") 18 | _component_func = components.declare_component("st_classification", path=build_path) 19 | else: 20 | _component_func = components.declare_component("st_classification", url="http://localhost:3000") 21 | 22 | def classification(image_path, label_list, default_label_index=None, height=512, width=512, key=None) -> CustomComponent: 23 | image = Image.open(image_path) 24 | image.thumbnail(size=(width, height)) 25 | image_url = image_to_url(image, image.size[0], True, "RGB", "PNG", f"classification-{md5(image.tobytes()).hexdigest()}-{key}") 26 | if image_url.startswith('/'): 27 | image_url = image_url[1:] 28 | component_value = _component_func(image_url=image_url, image_size=image.size, label_list=label_list, default_label_idx=default_label_index, key=key) 29 | return component_value 30 | 31 | if not IS_RELEASE: 32 | from glob import glob 33 | import pandas as pd 34 | label_list = ['deer', 'human', 'dog', 'penguin', 'framingo', 'teddy bear'] 35 | image_path_list = glob('image/*.jpg') 36 | if 'result_df' not in st.session_state: 37 | st.session_state['result_df'] = pd.DataFrame.from_dict({'image': image_path_list, 'label': [0]*len(image_path_list)}).copy() 38 | 39 | num_page = st.slider('page', 0, len(image_path_list)-1, 0, key="slider") 40 | label = classification(image_path_list[num_page], 41 | label_list=label_list, 42 | default_label_index=int(st.session_state['result_df'].loc[num_page, 'label']), 43 | key=image_path_list[num_page]) 44 | 45 | if label is not None and label['label'] != st.session_state['result_df'].loc[num_page, 'label']: 46 | st.session_state['result_df'].loc[num_page, 'label'] = label_list.index(label['label']) 47 | st.table(st.session_state['result_df']) -------------------------------------------------------------------------------- /streamlit_image_annotation/Classification/frontend/.env: -------------------------------------------------------------------------------- 1 | # Run the component's dev server on :3001 2 | # (The Streamlit dev server already runs on :3000) 3 | PORT=3000 4 | 5 | # Don't automatically open the web browser on `npm run start`. 6 | BROWSER=none 7 | -------------------------------------------------------------------------------- /streamlit_image_annotation/Classification/frontend/.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "endOfLine": "lf", 3 | "semi": false, 4 | "trailingComma": "es5" 5 | } 6 | -------------------------------------------------------------------------------- /streamlit_image_annotation/Classification/frontend/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "st-classification", 3 | "version": "0.1.0", 4 | "private": true, 5 | "homepage": ".", 6 | "dependencies": { 7 | "@chakra-ui/react": "^2.5.5", 8 | "@emotion/react": "^11", 9 | "@emotion/styled": "^11", 10 | "@testing-library/jest-dom": "^5.14.1", 11 | "@testing-library/react": "^13.0.0", 12 | "@testing-library/user-event": "^13.2.1", 13 | "@types/jest": "^27.0.1", 14 | "@types/node": "^16.7.13", 15 | "@types/react": "^18.0.0", 16 | "@types/react-dom": "^18.0.0", 17 | "framer-motion": "^6", 18 | "konva": "^8.4.3", 19 | "react": "^18.2.0", 20 | "react-dom": "^18.2.0", 21 | "react-konva": "^18.2.5", 22 | "react-scripts": "5.0.1", 23 | "streamlit-component-lib": "^1.4.0", 24 | "typescript": "^4.4.2", 25 | "use-image": "^1.1.0", 26 | "web-vitals": "^2.1.0" 27 | }, 28 | "resolutions": { 29 | "streamlit-component-lib/apache-arrow": "11.0.0" 30 | }, 31 | "scripts": { 32 | "start": "react-scripts start", 33 | "build": "react-scripts build", 34 | "test": "react-scripts test", 35 | "eject": "react-scripts eject" 36 | }, 37 | "eslintConfig": { 38 | "extends": [ 39 | "react-app", 40 | "react-app/jest" 41 | ] 42 | }, 43 | "browserslist": { 44 | "production": [ 45 | ">0.2%", 46 | "not dead", 47 | "not op_mini all" 48 | ], 49 | "development": [ 50 | "last 1 chrome version", 51 | "last 1 firefox version", 52 | "last 1 safari version" 53 | ] 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /streamlit_image_annotation/Classification/frontend/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 |
4 |