rkoushikroy2 commited on
Commit
9484fc5
β€’
1 Parent(s): f43fb5c

Add application file

Browse files
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2022 Koushik Roy
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
README.md CHANGED
@@ -1,12 +1,59 @@
1
- ---
2
- title: Portrait Photo Generator
3
- emoji: πŸ“š
4
- colorFrom: blue
5
- colorTo: purple
6
- sdk: gradio
7
- sdk_version: 3.1.1
8
- app_file: app.py
9
- pinned: false
10
- ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Portrait Photo Generator
2
+
3
+ In this repo we are going to use image segmentation model(facebook/detr-resnet-50-panoptic) to generate portrait photo of any object present in a photo. Then we are going to make a deployable app using gradio and finally, we will host it in hugging face hub spaces.
4
+
5
+ ## User Interface
6
+ Here is a screenshot of the interface. The app has been hosted in hugging face spaces. [Click Here]() to explore the deployed version.
7
+ ![Interface Snapshot](interface_snapshot.png)
8
+ > You can drag and drop images in the top left image box. After you drop an image the image segmentaion model will process the image and provide a list of objects in the drowpdown menu in the right. Now, you can choose any object from the list and that objet will be foucsed in the Output image box. You can adjust the slider to adject the strength of the background blur. The whole interface is reactive and anything you change will trigger an auto refresh. You may find the example images in lower right useful.
9
+
10
+ ## Protrait Image Generation Steps:
11
+ - Load segmentation model, pass your image, generate the masks and labels for each object present in the image.
12
+ - Make a list of objects from the "label" keys in the prediction dictionaries.
13
+ - Add a number identifier so that each object name can be unique. This is important for selecting a object.
14
+ - Image segmentation and background blurring method for selected object in the image:
15
+ - Take the mask provided by the segmentation model in the earlier stage.
16
+ - Divide by 255 to make the range 0 to 1.
17
+ - At this point the mask is 1 channel. Make it three channel by coping the single channel three times.
18
+ - Element wise multiply the input image and the three channel mask.
19
+ This will give an image where only the segmented part of the image will be present. This means, only the selected object pixels will be intact and other pixels will be black (0).
20
+ - Now, take the original image and blur it using any kind of blurring kernel. Here I used Gaussian Blur.
21
+ - After that, create a invert of the three channel mask created the previous steps.
22
+ - Element wise multiply the invert mask and blurred image.
23
+ This will give an image where the blurred background of the selected object will be present and
24
+ the pixels associate with the object of interest will be blank/black/value=0.
25
+ - Then, add up the segmented image and reverse segmented (blurred background portion).
26
+ This will give the desired portrait photo looking output.
27
+ - Smoothen the image.
28
+
29
+ ## Gradio GUI Steps:
30
+ - Used block element for more control over the interface.
31
+ - Used image.change, slider.change and dropdown.change event handler for generating output each time any of these changes.
32
+
33
+ ## Requirements
34
+ ```
35
+ gradio
36
+ numpy
37
+ Pillow
38
+ torch
39
+ timm
40
+ transformers
41
+ ```
42
+ ```
43
+ pip install -r requirements.txt
44
+ ```
45
+
46
+ ## Run App
47
+ ```
48
+ python app.py
49
+ ```
50
+
51
+ ## Files
52
+ | File | Contents |
53
+ |---|--- |
54
+ | [Segmentation Notebook](segmentation.ipynb) | Here the segmentation model to background blur part has been shown step by step.|
55
+ | [Gradio Notebook](gradio.ipynb) | You may experiment with different componets of a gradio app.|
56
+ | [Gradio App](app.py) | It is the main file of the deploed version of the portrait photo generator app.|
57
+
58
+
59
+
app.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Portrait Photo Generator App
2
+
3
+ # Imports
4
+ from PIL import Image, ImageFilter
5
+ import numpy as np
6
+ from transformers import pipeline
7
+ import gradio as gr
8
+ import os
9
+
10
+ model = pipeline("image-segmentation", model="facebook/detr-resnet-50-panoptic")
11
+
12
+ pred = []
13
+
14
+ def img_resize(image):
15
+ width = 1280
16
+ width_percent = (width / float(image.size[0]))
17
+ height = int((float(image.size[1]) * float(width_percent)))
18
+ return image.resize((width, height))
19
+
20
+ def image_objects(image):
21
+ global pred
22
+ image = img_resize(image)
23
+ pred = model(image)
24
+ pred_object_list = [str(i)+'_'+x['label'] for i, x in enumerate(pred)]
25
+ return gr.Dropdown.update(choices = pred_object_list, interactive = True)
26
+
27
+ def blurr_object(image, object, blur_strength):
28
+ image = img_resize(image)
29
+
30
+ object_number = int(object.split('_')[0])
31
+ mask_array = np.asarray(pred[object_number]['mask'])/255
32
+ image_array = np.asarray(image)
33
+
34
+ mask_array_three_channel = np.zeros_like(image_array)
35
+ mask_array_three_channel[:,:,0] = mask_array
36
+ mask_array_three_channel[:,:,1] = mask_array
37
+ mask_array_three_channel[:,:,2] = mask_array
38
+
39
+ segmented_image = image_array*mask_array_three_channel
40
+
41
+ blur_image = np.asarray(image.filter(ImageFilter.GaussianBlur(radius=blur_strength)))
42
+ mask_array_three_channel_invert = 1-mask_array_three_channel
43
+ blur_image_reverse_mask = blur_image*mask_array_three_channel_invert
44
+
45
+ blurred_output_image = Image.fromarray((blur_image_reverse_mask).astype(np.uint8)+segmented_image.astype(np.uint8))
46
+ for _ in range(int(blur_strength//2.5)):
47
+ blurred_output_image = blurred_output_image.filter(ImageFilter.SMOOTH_MORE)
48
+ return blurred_output_image
49
+
50
+ app = gr.Blocks()
51
+
52
+
53
+ with app:
54
+ gr.Markdown(
55
+ """
56
+ ## Portrait Photo Generator
57
+ - Create stunning portrait photos by blurring the background of your selected object.
58
+ - Adjust the blurring strength using the slider.
59
+ """)
60
+ with gr.Row():
61
+ with gr.Column():
62
+ gr.Markdown(
63
+ """
64
+ ### Input Image
65
+ """)
66
+ image_input = gr.Image(type="pil")
67
+
68
+
69
+ with gr.Column():
70
+ with gr.Row():
71
+ gr.Markdown(
72
+ """
73
+ ### Found Objects
74
+ """)
75
+ with gr.Row():
76
+ blur_slider = gr.Slider(minimum=0.5, maximum=10, value=3, label="Adject Blur Strength")
77
+ with gr.Row():
78
+ object_output = gr.Dropdown(label="Select Object From Dropdown")
79
+
80
+
81
+ with gr.Row():
82
+ with gr.Column():
83
+ gr.Markdown(
84
+ """
85
+ ### Blurred Image Output
86
+ """)
87
+ image_output = gr.Image()
88
+ with gr.Column():
89
+ gr.Markdown(
90
+ """
91
+ ### Example Images
92
+ """)
93
+ gr.Examples(
94
+ examples=[
95
+ "test_images/dog_horse_cowboy.jpg",
96
+ "test_images/woman_and_dog.jpg",
97
+ "test_images/family_in_sofa.jpg",
98
+ "test_images/group_of_friends.jpg",
99
+ "test_images/people_group.jpg"
100
+ ],
101
+ fn=image_objects,
102
+ inputs=image_input,
103
+ outputs=object_output)
104
+
105
+ image_input.change(fn=image_objects,
106
+ inputs=image_input,
107
+ outputs=object_output
108
+ )
109
+
110
+ object_output.change(fn=blurr_object,
111
+ inputs=[image_input, object_output, blur_slider],
112
+ outputs=image_output)
113
+
114
+ blur_slider.change(fn=blurr_object,
115
+ inputs=[image_input, object_output, blur_slider],
116
+ outputs=image_output)
117
+
118
+
119
+ app.launch()
gradio.ipynb ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 14,
6
+ "metadata": {},
7
+ "outputs": [],
8
+ "source": [
9
+ "# Imports\n",
10
+ "from PIL import Image, ImageFilter\n",
11
+ "import numpy as np\n",
12
+ "from transformers import pipeline\n",
13
+ "import gradio as gr\n",
14
+ "import os\n",
15
+ "\n",
16
+ "model = pipeline(\"image-segmentation\", model=\"facebook/detr-resnet-50-panoptic\")\n",
17
+ "\n",
18
+ "pred = []\n",
19
+ "\n",
20
+ "def img_resize(image):\n",
21
+ " width = 1000\n",
22
+ " width_percent = (width / float(image.size[0]))\n",
23
+ " height = int((float(image.size[1]) * float(width_percent)))\n",
24
+ " return image.resize((width, height))\n",
25
+ "\n",
26
+ "def image_objects(image):\n",
27
+ " global pred\n",
28
+ " image = img_resize(image)\n",
29
+ " pred = model(image)\n",
30
+ " pred_object_list = [str(i)+'_'+x['label'] for i, x in enumerate(pred)]\n",
31
+ " return gr.Dropdown.update(choices = pred_object_list, interactive = True)\n",
32
+ "\n",
33
+ "def blurr_object(image, object, blur_strength):\n",
34
+ " image = img_resize(image)\n",
35
+ "\n",
36
+ " object_number = int(object.split('_')[0])\n",
37
+ " mask_array = np.asarray(pred[object_number]['mask'])/255\n",
38
+ " image_array = np.asarray(image)\n",
39
+ "\n",
40
+ " mask_array_three_channel = np.zeros_like(image_array)\n",
41
+ " mask_array_three_channel[:,:,0] = mask_array\n",
42
+ " mask_array_three_channel[:,:,1] = mask_array\n",
43
+ " mask_array_three_channel[:,:,2] = mask_array\n",
44
+ "\n",
45
+ " segmented_image = image_array*mask_array_three_channel\n",
46
+ "\n",
47
+ " blur_image = np.asarray(image.filter(ImageFilter.GaussianBlur(radius=blur_strength)))\n",
48
+ " mask_array_three_channel_invert = 1-mask_array_three_channel\n",
49
+ " blur_image_reverse_mask = blur_image*mask_array_three_channel_invert\n",
50
+ "\n",
51
+ " blurred_output_image = Image.fromarray((blur_image_reverse_mask).astype(np.uint8)+segmented_image.astype(np.uint8))\n",
52
+ "\n",
53
+ " return blurred_output_image\n",
54
+ "\n"
55
+ ]
56
+ },
57
+ {
58
+ "cell_type": "code",
59
+ "execution_count": 18,
60
+ "metadata": {},
61
+ "outputs": [
62
+ {
63
+ "name": "stdout",
64
+ "output_type": "stream",
65
+ "text": [
66
+ "Running on local URL: http://127.0.0.1:7862/\n",
67
+ "\n",
68
+ "To create a public link, set `share=True` in `launch()`.\n"
69
+ ]
70
+ },
71
+ {
72
+ "data": {
73
+ "text/html": [
74
+ "<div><iframe src=\"http://127.0.0.1:7862/\" width=\"900\" height=\"500\" allow=\"autoplay; camera; microphone;\" frameborder=\"0\" allowfullscreen></iframe></div>"
75
+ ],
76
+ "text/plain": [
77
+ "<IPython.core.display.HTML object>"
78
+ ]
79
+ },
80
+ "metadata": {},
81
+ "output_type": "display_data"
82
+ },
83
+ {
84
+ "name": "stderr",
85
+ "output_type": "stream",
86
+ "text": [
87
+ "Traceback (most recent call last):\n",
88
+ " File \"/home/nybsysml/anaconda3/envs/mediapipe3_7/lib/python3.7/site-packages/gradio/routes.py\", line 256, in run_predict\n",
89
+ " fn_index, raw_input, username, session_state\n",
90
+ " File \"/home/nybsysml/anaconda3/envs/mediapipe3_7/lib/python3.7/site-packages/gradio/blocks.py\", line 599, in process_api\n",
91
+ " predictions, duration = await self.call_function(fn_index, processed_input)\n",
92
+ " File \"/home/nybsysml/anaconda3/envs/mediapipe3_7/lib/python3.7/site-packages/gradio/blocks.py\", line 515, in call_function\n",
93
+ " block_fn.fn, *processed_input, limiter=self.limiter\n",
94
+ " File \"/home/nybsysml/anaconda3/envs/mediapipe3_7/lib/python3.7/site-packages/anyio/to_thread.py\", line 32, in run_sync\n",
95
+ " func, *args, cancellable=cancellable, limiter=limiter\n",
96
+ " File \"/home/nybsysml/anaconda3/envs/mediapipe3_7/lib/python3.7/site-packages/anyio/_backends/_asyncio.py\", line 937, in run_sync_in_worker_thread\n",
97
+ " return await future\n",
98
+ " File \"/home/nybsysml/anaconda3/envs/mediapipe3_7/lib/python3.7/site-packages/anyio/_backends/_asyncio.py\", line 867, in run\n",
99
+ " result = context.run(func, *args)\n",
100
+ " File \"/tmp/ipykernel_6335/646230931.py\", line 20, in image_objects\n",
101
+ " image = img_resize(image)\n",
102
+ " File \"/tmp/ipykernel_6335/646230931.py\", line 14, in img_resize\n",
103
+ " width_percent = (width / float(image.size[0]))\n",
104
+ "AttributeError: 'NoneType' object has no attribute 'size'\n"
105
+ ]
106
+ }
107
+ ],
108
+ "source": [
109
+ "app = gr.Blocks()\n",
110
+ "\n",
111
+ "\n",
112
+ "with app:\n",
113
+ " gr.Markdown(\n",
114
+ " \"\"\"\n",
115
+ " ## Portrait Photo Generator\n",
116
+ " - Create stunning portrait photos by blurring the background of your selected object.\n",
117
+ " - Adjust the blurring strength using the slider.\n",
118
+ " \"\"\")\n",
119
+ " with gr.Row():\n",
120
+ " with gr.Column():\n",
121
+ " gr.Markdown(\n",
122
+ " \"\"\"\n",
123
+ " ### Input Image\n",
124
+ " \"\"\")\n",
125
+ " image_input = gr.Image(type=\"pil\")\n",
126
+ " \n",
127
+ "\n",
128
+ " with gr.Column():\n",
129
+ " with gr.Row():\n",
130
+ " gr.Markdown(\n",
131
+ " \"\"\"\n",
132
+ " ### Found Objects\n",
133
+ " \"\"\")\n",
134
+ " with gr.Row():\n",
135
+ " blur_slider = gr.Slider(minimum=0.5, maximum=10, value=3, label=\"Adject Blur Strength\")\n",
136
+ " with gr.Row():\n",
137
+ " object_output = gr.Dropdown(label=\"Select Object From Dropdown\")\n",
138
+ "\n",
139
+ " \n",
140
+ " with gr.Row():\n",
141
+ " with gr.Column():\n",
142
+ " gr.Markdown(\n",
143
+ " \"\"\"\n",
144
+ " ### Blurred Image Output\n",
145
+ " \"\"\")\n",
146
+ " image_output = gr.Image()\n",
147
+ " with gr.Column():\n",
148
+ " gr.Markdown(\n",
149
+ " \"\"\"\n",
150
+ " ### Example Images\n",
151
+ " \"\"\")\n",
152
+ " gr.Examples(\n",
153
+ " examples=[\n",
154
+ " \"test_images/dog_horse_cowboy.jpg\",\n",
155
+ " \"test_images/woman_and_dog.jpg\",\n",
156
+ " \"test_images/family_in_sofa.jpg\",\n",
157
+ " \"test_images/group_of_friends.jpg\",\n",
158
+ " \"test_images/people_group.jpg\"\n",
159
+ " ],\n",
160
+ " fn=image_objects,\n",
161
+ " inputs=image_input, \n",
162
+ " outputs=object_output)\n",
163
+ "\n",
164
+ " image_input.change(fn=image_objects, \n",
165
+ " inputs=image_input, \n",
166
+ " outputs=object_output\n",
167
+ " )\n",
168
+ "\n",
169
+ " object_output.change(fn=blurr_object, \n",
170
+ " inputs=[image_input, object_output, blur_slider],\n",
171
+ " outputs=image_output)\n",
172
+ "\n",
173
+ " blur_slider.change(fn=blurr_object, \n",
174
+ " inputs=[image_input, object_output, blur_slider],\n",
175
+ " outputs=image_output)\n",
176
+ " \n",
177
+ "\n",
178
+ "app.launch(debug=True)"
179
+ ]
180
+ }
181
+ ],
182
+ "metadata": {
183
+ "kernelspec": {
184
+ "display_name": "Python 3.9.7 ('base')",
185
+ "language": "python",
186
+ "name": "python3"
187
+ },
188
+ "language_info": {
189
+ "codemirror_mode": {
190
+ "name": "ipython",
191
+ "version": 3
192
+ },
193
+ "file_extension": ".py",
194
+ "mimetype": "text/x-python",
195
+ "name": "python",
196
+ "nbconvert_exporter": "python",
197
+ "pygments_lexer": "ipython3",
198
+ "version": "3.9.7"
199
+ },
200
+ "orig_nbformat": 4,
201
+ "vscode": {
202
+ "interpreter": {
203
+ "hash": "d03b47a5a9bfc09262d9700ac41deff9ead9ff3e21241983433bdf2900140cd2"
204
+ }
205
+ }
206
+ },
207
+ "nbformat": 4,
208
+ "nbformat_minor": 2
209
+ }
interface_snapshot.png ADDED
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ gradio
2
+ numpy
3
+ Pillow
4
+ torch
5
+ timm
6
+ transformers
segmentation.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
test_images/dog_horse_cowboy.jpg ADDED
test_images/family_in_sofa.jpg ADDED
test_images/group_of_friends.jpg ADDED
test_images/people_group.jpg ADDED
test_images/woman_and_dog.jpg ADDED