SavyaSanchi-Sharma commited on
Commit ·
07604d2
1
Parent(s): 979472c
human_parsing model
Browse files- human_parsing_jppnet/LICENSE +21 -0
- human_parsing_jppnet/README.md +127 -0
- human_parsing_jppnet/convert_to_onnx.py +131 -0
- human_parsing_jppnet/demo.cpp +143 -0
- human_parsing_jppnet/demo.py +99 -0
- human_parsing_jppnet/example_outputs/input_image.png +3 -0
- human_parsing_jppnet/example_outputs/output_image.png +3 -0
- human_parsing_jppnet/human_parsing_jppnet_2026sep.onnx +3 -0
human_parsing_jppnet/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2016 Vladimir Nekrasov
|
| 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.
|
human_parsing_jppnet/README.md
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Human Parsing (JPPNet)
|
| 2 |
+
|
| 3 |
+
Single-person human parsing with JPPNet — it labels every pixel of a person as one of
|
| 4 |
+
20 LIP classes (hair, face, upper clothes, pants, left/right arm, left/right shoe, and
|
| 5 |
+
so on). The model was originally distributed as a frozen TensorFlow graph
|
| 6 |
+
(`lip_jppnet_384.pb`, the one referenced by OpenCV's `samples/dnn/human_parsing.py`)
|
| 7 |
+
and converted to ONNX for use with OpenCV's DNN module.
|
| 8 |
+
|
| 9 |
+
## Model Details
|
| 10 |
+
- **Architecture**: JPPNet — a ResNet-101 backbone with atrous convolutions, three
|
| 11 |
+
parsing heads (`fc1_human`, `fc2_parsing`, `fc3_parsing`) built from four-branch ASPP
|
| 12 |
+
modules, run at three input scales (0.75x, 1.0x, 1.25x) whose predictions are averaged
|
| 13 |
+
- **Input**: BGR image, 384×384, raw 0–255 float, mean `(104.00698793, 116.66876762,
|
| 14 |
+
122.67891434)`, no scaling, no swapRB, NCHW layout (`input:0`, shape `[2, 3, 384, 384]`)
|
| 15 |
+
- **Output**: `Mean_3:0` — class scores, shape `[2, 20, 384, 384]`
|
| 16 |
+
- **Framework**: ONNX opset 15 (converted from the TensorFlow frozen graph via tf2onnx)
|
| 17 |
+
- **Original weights**: https://github.com/Engineering-Course/LIP_JPPNet
|
| 18 |
+
- **Paper**: Liang, Gong, Shen and Lin, *Look into Person: Joint Body Parsing & Pose
|
| 19 |
+
Estimation Network and a New Benchmark*, T-PAMI 2018
|
| 20 |
+
|
| 21 |
+
The batch dimension is fixed at **2** and is not a batch of two different pictures. The
|
| 22 |
+
network expects the image *and its horizontal mirror*: the two predictions get averaged,
|
| 23 |
+
which is what the original evaluation script does to stabilise the result. Before
|
| 24 |
+
averaging, the mirrored half has its left/right channel pairs swapped back
|
| 25 |
+
(LeftArm↔RightArm, LeftLeg↔RightLeg, LeftShoe↔RightShoe) and is flipped horizontally.
|
| 26 |
+
`demo.py` and `demo.cpp` both do this; skipping it costs accuracy on the limbs.
|
| 27 |
+
|
| 28 |
+
The 20 classes, in channel order:
|
| 29 |
+
|
| 30 |
+
| | | | |
|
| 31 |
+
|---|---|---|---|
|
| 32 |
+
| 0 Background | 5 UpperClothes | 10 Jumpsuits | 15 RightArm |
|
| 33 |
+
| 1 Hat | 6 Dress | 11 Scarf | 16 LeftLeg |
|
| 34 |
+
| 2 Hair | 7 Coat | 12 Skirt | 17 RightLeg |
|
| 35 |
+
| 3 Glove | 8 Socks | 13 Face | 18 LeftShoe |
|
| 36 |
+
| 4 Sunglasses | 9 Pants | 14 LeftArm | 19 RightShoe |
|
| 37 |
+
|
| 38 |
+
The spatial size is frozen at 384×384 — the graph resizes its own heads back to that
|
| 39 |
+
resolution with hardcoded constants, so it always predicts at 384×384 no matter what it
|
| 40 |
+
is fed. The demos resize the picture to 384×384 on the way in and scale the score maps
|
| 41 |
+
back to the original resolution before taking the argmax.
|
| 42 |
+
|
| 43 |
+
## Usage
|
| 44 |
+
|
| 45 |
+
### Python
|
| 46 |
+
```bash
|
| 47 |
+
python demo.py --model human_parsing_jppnet_2026sep.onnx \
|
| 48 |
+
--image example_outputs/input_image.png \
|
| 49 |
+
--output example_outputs/output_image.png
|
| 50 |
+
```
|
| 51 |
+
|
| 52 |
+
Or import directly:
|
| 53 |
+
```python
|
| 54 |
+
import cv2
|
| 55 |
+
|
| 56 |
+
net = cv2.dnn.readNetFromONNX("human_parsing_jppnet_2026sep.onnx")
|
| 57 |
+
# see demo.py for preprocessing, the mirror merge and the LIP palette
|
| 58 |
+
```
|
| 59 |
+
|
| 60 |
+
### C++
|
| 61 |
+
The C++ demo runs inference with OpenCV's DNN module (default engine — no ONNX Runtime
|
| 62 |
+
needed). Adjust the OpenCV paths to your setup:
|
| 63 |
+
```bash
|
| 64 |
+
OCV=/path/to/opencv # OpenCV source tree
|
| 65 |
+
OCVBUILD=/path/to/opencv/build # OpenCV build directory (generated headers + libs)
|
| 66 |
+
g++ -std=c++17 demo.cpp -o demo \
|
| 67 |
+
-I$OCV/include \
|
| 68 |
+
-I$OCV/modules/core/include \
|
| 69 |
+
-I$OCV/modules/dnn/include \
|
| 70 |
+
-I$OCV/modules/imgproc/include \
|
| 71 |
+
-I$OCV/modules/imgcodecs/include \
|
| 72 |
+
-I$OCVBUILD \
|
| 73 |
+
-L$OCVBUILD/lib -Wl,-rpath,$OCVBUILD/lib -lopencv_dnn -lopencv_imgcodecs -lopencv_imgproc -lopencv_core
|
| 74 |
+
./demo --model human_parsing_jppnet_2026sep.onnx --image example_outputs/input_image.png
|
| 75 |
+
```
|
| 76 |
+
|
| 77 |
+
Both demos produce the same label map, pixel for pixel.
|
| 78 |
+
|
| 79 |
+
## Conversion
|
| 80 |
+
The ONNX model was exported from the frozen TensorFlow graph with tf2onnx (opset 15) via
|
| 81 |
+
[convert_to_onnx.py](./convert_to_onnx.py) — input `input:0`, output `Mean_3:0`, both
|
| 82 |
+
forced to NCHW (`inputs_as_nchw` / `outputs_as_nchw`) so the tensors match OpenCV's
|
| 83 |
+
layout, with the input shape overridden to `[2, 384, 384, 3]`. Requires `tensorflow`,
|
| 84 |
+
`tf2onnx`, `onnx` and `opencv-python` (the last only for `--verify`).
|
| 85 |
+
|
| 86 |
+
```bash
|
| 87 |
+
python convert_to_onnx.py --pb ../pb/lip_jppnet_384.pb --verify example_outputs/input_image.png
|
| 88 |
+
```
|
| 89 |
+
|
| 90 |
+
Fixing the input shape lets tf2onnx fold the whole graph down to nine op types — `Conv`,
|
| 91 |
+
`Relu`, `Sum`, `Add`, `Concat`, `Resize`, `Unsqueeze`, `ReduceMean` and `MaxPool`. The
|
| 92 |
+
batch-norms fuse into the convolutions, and the `SpaceToBatchND`/`BatchToSpaceND` pairs
|
| 93 |
+
that implement atrous convolution collapse into plain `Conv` nodes with `dilations`.
|
| 94 |
+
|
| 95 |
+
One post-processing step is applied to the exported graph. The three ASPP heads sum four
|
| 96 |
+
branches each, which tf2onnx emits as nine `Sum` nodes with four inputs; OpenCV 4.x's
|
| 97 |
+
ONNX importer mis-computes those (about 14% of the pixels came out with the wrong label).
|
| 98 |
+
`split_multi_input_sums` rewrites them as chains of two-input `Add`, which is numerically
|
| 99 |
+
identical and imports correctly everywhere.
|
| 100 |
+
|
| 101 |
+
The 412 MB file size is expected: the weights are shared across the three scale branches,
|
| 102 |
+
so it is close to a single ResNet-101 plus the parsing heads at float32.
|
| 103 |
+
|
| 104 |
+
### Verification
|
| 105 |
+
The exported model was checked against the original TensorFlow graph on the example
|
| 106 |
+
image, over all 2 × 20 × 384 × 384 output values:
|
| 107 |
+
|
| 108 |
+
| runtime | max abs diff | mean abs diff | pixels with the same label |
|
| 109 |
+
|---|---|---|---|
|
| 110 |
+
| ONNX Runtime 1.23 | 3.05e-05 | 2.33e-06 | 100.0000% |
|
| 111 |
+
| OpenCV 4.11 DNN | 3.34e-05 | 2.60e-06 | 100.0000% |
|
| 112 |
+
| OpenCV 5.0 DNN | 3.62e-05 | 2.58e-06 | 100.0000% |
|
| 113 |
+
|
| 114 |
+
## Example
|
| 115 |
+
`example_outputs/input_image.png` is the standing-person image from OpenCV's own test
|
| 116 |
+
data (`opencv_extra/testdata/dnn/pose.png`); `example_outputs/output_image.png` is the
|
| 117 |
+
parsing result painted with the LIP palette.
|
| 118 |
+
|
| 119 |
+
## License
|
| 120 |
+
See [LICENSE](./LICENSE) — the MIT license file shipped in
|
| 121 |
+
[Engineering-Course/LIP_JPPNet](https://github.com/Engineering-Course/LIP_JPPNet),
|
| 122 |
+
carried over from the DeepLab-ResNet TensorFlow implementation the code is built on
|
| 123 |
+
(hence the `Copyright (c) 2016 Vladimir Nekrasov` line).
|
| 124 |
+
|
| 125 |
+
Note that the license covers the code. The released weights are trained on the
|
| 126 |
+
[LIP dataset](https://lip.sysuhcp.com/), which the authors distribute for non-commercial
|
| 127 |
+
research use; check the dataset's own terms before using the model in a product.
|
human_parsing_jppnet/convert_to_onnx.py
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import datetime
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import onnx
|
| 6 |
+
from onnx import helper
|
| 7 |
+
import tensorflow as tf
|
| 8 |
+
import tf2onnx
|
| 9 |
+
|
| 10 |
+
# The frozen graph takes a batch of exactly two images (the picture and its
|
| 11 |
+
# horizontal mirror) and always emits a 384x384 label map, so the spatial size
|
| 12 |
+
# is the only thing worth parameterising.
|
| 13 |
+
INPUT_NAME = "input:0"
|
| 14 |
+
OUTPUT_NAME = "Mean_3:0"
|
| 15 |
+
BATCH = 2
|
| 16 |
+
MEAN = (104.00698793, 116.66876762, 122.67891434)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def load_graph_def(pb_path):
|
| 20 |
+
with tf.io.gfile.GFile(pb_path, "rb") as f:
|
| 21 |
+
graph_def = tf.compat.v1.GraphDef()
|
| 22 |
+
graph_def.ParseFromString(f.read())
|
| 23 |
+
return graph_def
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def split_multi_input_sums(model):
|
| 27 |
+
"""Rewrite Sum nodes that take more than two inputs into chains of Add.
|
| 28 |
+
|
| 29 |
+
The three ASPP heads are exported as four-input Sum nodes. OpenCV 4.x's
|
| 30 |
+
ONNX importer gets those wrong (roughly 14% of the pixels end up with the
|
| 31 |
+
wrong label) while two-input adds import correctly on every version we
|
| 32 |
+
tested, and the rewrite is numerically identical.
|
| 33 |
+
"""
|
| 34 |
+
graph = model.graph
|
| 35 |
+
rewritten = []
|
| 36 |
+
count = 0
|
| 37 |
+
for node in graph.node:
|
| 38 |
+
if node.op_type != "Sum" or len(node.input) <= 2:
|
| 39 |
+
rewritten.append(node)
|
| 40 |
+
continue
|
| 41 |
+
count += 1
|
| 42 |
+
acc = node.input[0]
|
| 43 |
+
for i, operand in enumerate(node.input[1:]):
|
| 44 |
+
name = "%s__add%d" % (node.name, i)
|
| 45 |
+
last = i == len(node.input) - 2
|
| 46 |
+
out = node.output[0] if last else name
|
| 47 |
+
rewritten.append(helper.make_node("Add", [acc, operand], [out], name=name))
|
| 48 |
+
acc = out
|
| 49 |
+
del graph.node[:]
|
| 50 |
+
graph.node.extend(rewritten)
|
| 51 |
+
return count
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def make_input(image_path, size):
|
| 55 |
+
"""Build the [2, 3, size, size] NCHW blob the exported model expects."""
|
| 56 |
+
import cv2
|
| 57 |
+
|
| 58 |
+
image = cv2.imread(image_path)
|
| 59 |
+
if image is None:
|
| 60 |
+
raise OSError("cannot read %s" % image_path)
|
| 61 |
+
image = cv2.resize(image, (size, size))
|
| 62 |
+
mirror = np.flip(image, axis=1)
|
| 63 |
+
return cv2.dnn.blobFromImages([image, mirror], mean=MEAN)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def verify(graph_def, onnx_path, blob, size):
|
| 67 |
+
"""Compare the exported model against the original TensorFlow graph."""
|
| 68 |
+
import cv2
|
| 69 |
+
|
| 70 |
+
graph = tf.Graph()
|
| 71 |
+
with graph.as_default():
|
| 72 |
+
tf.import_graph_def(graph_def, name="")
|
| 73 |
+
with tf.compat.v1.Session(graph=graph) as sess:
|
| 74 |
+
nhwc = blob.transpose(0, 2, 3, 1).copy()
|
| 75 |
+
tf_out = sess.run(OUTPUT_NAME, feed_dict={INPUT_NAME: nhwc})
|
| 76 |
+
tf_out = tf_out.transpose(0, 3, 1, 2)
|
| 77 |
+
|
| 78 |
+
net = cv2.dnn.readNetFromONNX(onnx_path)
|
| 79 |
+
net.setInput(blob)
|
| 80 |
+
onnx_out = net.forward()
|
| 81 |
+
|
| 82 |
+
diff = np.abs(tf_out.astype(np.float64) - onnx_out.astype(np.float64))
|
| 83 |
+
agree = 100.0 * (tf_out.argmax(1) == onnx_out.argmax(1)).mean()
|
| 84 |
+
print("verify: tensorflow %s vs opencv %s" % (tf_out.shape, onnx_out.shape))
|
| 85 |
+
print("verify: max abs diff %.3e, mean abs diff %.3e" % (diff.max(), diff.mean()))
|
| 86 |
+
print("verify: identical labels on %.4f%% of the pixels" % agree)
|
| 87 |
+
return diff.max()
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def main():
|
| 91 |
+
parser = argparse.ArgumentParser(
|
| 92 |
+
description="Export the frozen LIP_JPPNet human parsing graph to ONNX")
|
| 93 |
+
parser.add_argument("--pb", default="../pb/lip_jppnet_384.pb",
|
| 94 |
+
help="frozen TensorFlow graph (lip_jppnet_384.pb)")
|
| 95 |
+
parser.add_argument("--size", type=int, default=384, help="input resolution")
|
| 96 |
+
parser.add_argument("--opset", type=int, default=15)
|
| 97 |
+
parser.add_argument("--output", default=None, help="output .onnx path")
|
| 98 |
+
parser.add_argument("--verify", metavar="IMAGE", default=None,
|
| 99 |
+
help="after exporting, compare the ONNX model against "
|
| 100 |
+
"the TensorFlow graph on this image")
|
| 101 |
+
args = parser.parse_args()
|
| 102 |
+
|
| 103 |
+
graph_def = load_graph_def(args.pb)
|
| 104 |
+
|
| 105 |
+
model_proto, _ = tf2onnx.convert.from_graph_def(
|
| 106 |
+
graph_def,
|
| 107 |
+
input_names=[INPUT_NAME],
|
| 108 |
+
output_names=[OUTPUT_NAME],
|
| 109 |
+
inputs_as_nchw=[INPUT_NAME],
|
| 110 |
+
outputs_as_nchw=[OUTPUT_NAME],
|
| 111 |
+
opset=args.opset,
|
| 112 |
+
shape_override={INPUT_NAME: [BATCH, args.size, args.size, 3]},
|
| 113 |
+
)
|
| 114 |
+
n = split_multi_input_sums(model_proto)
|
| 115 |
+
print("rewrote %d multi-input Sum nodes as Add chains" % n)
|
| 116 |
+
onnx.checker.check_model(model_proto)
|
| 117 |
+
|
| 118 |
+
onnx_path = args.output
|
| 119 |
+
if onnx_path is None:
|
| 120 |
+
stamp = datetime.datetime.now().strftime("%Y%b").lower()
|
| 121 |
+
onnx_path = "human_parsing_jppnet_%s.onnx" % stamp
|
| 122 |
+
with open(onnx_path, "wb") as f:
|
| 123 |
+
f.write(model_proto.SerializeToString())
|
| 124 |
+
print("wrote", onnx_path)
|
| 125 |
+
|
| 126 |
+
if args.verify:
|
| 127 |
+
verify(graph_def, onnx_path, make_input(args.verify, args.size), args.size)
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
if __name__ == "__main__":
|
| 131 |
+
main()
|
human_parsing_jppnet/demo.cpp
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#include <opencv2/dnn.hpp>
|
| 2 |
+
#include <opencv2/imgproc.hpp>
|
| 3 |
+
#include <opencv2/imgcodecs.hpp>
|
| 4 |
+
#include <iostream>
|
| 5 |
+
#include <string>
|
| 6 |
+
#include <vector>
|
| 7 |
+
|
| 8 |
+
// The exported graph is frozen at 384x384 and always takes two images: the
|
| 9 |
+
// picture and its horizontal mirror.
|
| 10 |
+
static const int INPUT_SIZE = 384;
|
| 11 |
+
static const cv::Scalar MEAN(104.00698793, 116.66876762, 122.67891434);
|
| 12 |
+
|
| 13 |
+
// The 20 LIP classes, in channel order.
|
| 14 |
+
static const char* CLASSES[] = {
|
| 15 |
+
"Background", "Hat", "Hair", "Glove", "Sunglasses", "UpperClothes",
|
| 16 |
+
"Dress", "Coat", "Socks", "Pants", "Jumpsuits", "Scarf", "Skirt",
|
| 17 |
+
"Face", "LeftArm", "RightArm", "LeftLeg", "RightLeg", "LeftShoe",
|
| 18 |
+
"RightShoe"
|
| 19 |
+
};
|
| 20 |
+
static const int NUM_CLASSES = 20;
|
| 21 |
+
|
| 22 |
+
// LIP palette, RGB.
|
| 23 |
+
static const unsigned char COLORS[NUM_CLASSES][3] = {
|
| 24 |
+
{0, 0, 0}, {128, 0, 0}, {255, 0, 0}, {0, 85, 0}, {170, 0, 51},
|
| 25 |
+
{255, 85, 0}, {0, 0, 85}, {0, 119, 221}, {85, 85, 0}, {0, 85, 85},
|
| 26 |
+
{85, 51, 0}, {52, 86, 128}, {0, 128, 0}, {0, 0, 255}, {51, 170, 221},
|
| 27 |
+
{0, 255, 255}, {85, 255, 170}, {170, 255, 85}, {255, 255, 0}, {255, 170, 0}
|
| 28 |
+
};
|
| 29 |
+
|
| 30 |
+
static std::string argVal(int argc, char** argv, const std::string& key, const std::string& def)
|
| 31 |
+
{
|
| 32 |
+
for (int i = 1; i + 1 < argc; ++i)
|
| 33 |
+
if (key == argv[i]) return argv[i + 1];
|
| 34 |
+
return def;
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
// Mirroring an image swaps the left and right body parts, so the channels of
|
| 38 |
+
// the mirrored prediction have to be swapped back before the two are averaged.
|
| 39 |
+
static int mirrorChannel(int c)
|
| 40 |
+
{
|
| 41 |
+
switch (c)
|
| 42 |
+
{
|
| 43 |
+
case 14: return 15; // LeftArm <-> RightArm
|
| 44 |
+
case 15: return 14;
|
| 45 |
+
case 16: return 17; // LeftLeg <-> RightLeg
|
| 46 |
+
case 17: return 16;
|
| 47 |
+
case 18: return 19; // LeftShoe <-> RightShoe
|
| 48 |
+
case 19: return 18;
|
| 49 |
+
default: return c;
|
| 50 |
+
}
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
// Build the [2, 3, 384, 384] blob: the image and its mirror, mean-subtracted.
|
| 54 |
+
static cv::Mat preprocess(const cv::Mat& image)
|
| 55 |
+
{
|
| 56 |
+
cv::Mat resized, mirror;
|
| 57 |
+
cv::resize(image, resized, cv::Size(INPUT_SIZE, INPUT_SIZE));
|
| 58 |
+
cv::flip(resized, mirror, 1);
|
| 59 |
+
|
| 60 |
+
std::vector<cv::Mat> images;
|
| 61 |
+
images.push_back(resized);
|
| 62 |
+
images.push_back(mirror);
|
| 63 |
+
|
| 64 |
+
return cv::dnn::blobFromImages(images, 1.0, cv::Size(), MEAN);
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
// Average the two predictions and turn them into a label map of `size`.
|
| 68 |
+
// `out` is [2, 20, 384, 384].
|
| 69 |
+
static cv::Mat postprocess(const cv::Mat& out, const cv::Size& size)
|
| 70 |
+
{
|
| 71 |
+
cv::Mat labels(size, CV_8U, cv::Scalar(0));
|
| 72 |
+
cv::Mat best(size, CV_32F, cv::Scalar(-FLT_MAX));
|
| 73 |
+
|
| 74 |
+
for (int c = 0; c < NUM_CLASSES; ++c)
|
| 75 |
+
{
|
| 76 |
+
cv::Mat direct(INPUT_SIZE, INPUT_SIZE, CV_32F,
|
| 77 |
+
const_cast<float*>(out.ptr<float>(0, c)));
|
| 78 |
+
cv::Mat mirrored(INPUT_SIZE, INPUT_SIZE, CV_32F,
|
| 79 |
+
const_cast<float*>(out.ptr<float>(1, mirrorChannel(c))));
|
| 80 |
+
|
| 81 |
+
cv::Mat unmirrored;
|
| 82 |
+
cv::flip(mirrored, unmirrored, 1);
|
| 83 |
+
|
| 84 |
+
cv::Mat score = 0.5f * (direct + unmirrored);
|
| 85 |
+
cv::resize(score, score, size, 0, 0, cv::INTER_LINEAR);
|
| 86 |
+
|
| 87 |
+
cv::Mat better = score > best;
|
| 88 |
+
score.copyTo(best, better);
|
| 89 |
+
labels.setTo(c, better);
|
| 90 |
+
}
|
| 91 |
+
return labels;
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
// Paint a label map with the LIP palette, as a BGR image.
|
| 95 |
+
static cv::Mat colorize(const cv::Mat& labels)
|
| 96 |
+
{
|
| 97 |
+
cv::Mat lut(1, NUM_CLASSES, CV_8UC3);
|
| 98 |
+
for (int i = 0; i < NUM_CLASSES; ++i)
|
| 99 |
+
lut.at<cv::Vec3b>(0, i) = cv::Vec3b(COLORS[i][2], COLORS[i][1], COLORS[i][0]);
|
| 100 |
+
|
| 101 |
+
cv::Mat segmentation(labels.size(), CV_8UC3);
|
| 102 |
+
for (int y = 0; y < labels.rows; ++y)
|
| 103 |
+
{
|
| 104 |
+
const unsigned char* src = labels.ptr<unsigned char>(y);
|
| 105 |
+
cv::Vec3b* dst = segmentation.ptr<cv::Vec3b>(y);
|
| 106 |
+
for (int x = 0; x < labels.cols; ++x)
|
| 107 |
+
dst[x] = lut.at<cv::Vec3b>(0, src[x]);
|
| 108 |
+
}
|
| 109 |
+
return segmentation;
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
int main(int argc, char** argv)
|
| 113 |
+
{
|
| 114 |
+
std::string model = argVal(argc, argv, "--model", "human_parsing_jppnet_2026sep.onnx");
|
| 115 |
+
std::string image = argVal(argc, argv, "--image", "example_outputs/input_image.png");
|
| 116 |
+
std::string output = argVal(argc, argv, "--output", "example_outputs/output_image.png");
|
| 117 |
+
|
| 118 |
+
cv::Mat img = cv::imread(image);
|
| 119 |
+
if (img.empty())
|
| 120 |
+
{
|
| 121 |
+
std::cerr << "could not read image: " << image << std::endl;
|
| 122 |
+
return 1;
|
| 123 |
+
}
|
| 124 |
+
|
| 125 |
+
cv::dnn::Net net = cv::dnn::readNetFromONNX(model);
|
| 126 |
+
net.setInput(preprocess(img));
|
| 127 |
+
cv::Mat out = net.forward();
|
| 128 |
+
|
| 129 |
+
cv::Mat labels = postprocess(out, img.size());
|
| 130 |
+
cv::Mat segmentation = colorize(labels);
|
| 131 |
+
|
| 132 |
+
std::cout << "human_parsing_jppnet input " << img.cols << "x" << img.rows << std::endl;
|
| 133 |
+
for (int c = 0; c < NUM_CLASSES; ++c)
|
| 134 |
+
{
|
| 135 |
+
int pixels = cv::countNonZero(labels == c);
|
| 136 |
+
if (pixels > 0)
|
| 137 |
+
std::cout << " " << CLASSES[c] << " " << pixels << " px" << std::endl;
|
| 138 |
+
}
|
| 139 |
+
|
| 140 |
+
cv::imwrite(output, segmentation);
|
| 141 |
+
std::cout << "wrote " << output << std::endl;
|
| 142 |
+
return 0;
|
| 143 |
+
}
|
human_parsing_jppnet/demo.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import os
|
| 3 |
+
|
| 4 |
+
import cv2 as cv
|
| 5 |
+
import numpy as np
|
| 6 |
+
|
| 7 |
+
here = os.path.dirname(os.path.abspath(__file__))
|
| 8 |
+
|
| 9 |
+
# The exported graph is frozen at 384x384 and always takes two images: the
|
| 10 |
+
# picture and its horizontal mirror.
|
| 11 |
+
INPUT_SIZE = 384
|
| 12 |
+
MEAN = (104.00698793, 116.66876762, 122.67891434)
|
| 13 |
+
|
| 14 |
+
# The 20 LIP classes, in channel order.
|
| 15 |
+
CLASSES = ["Background", "Hat", "Hair", "Glove", "Sunglasses", "UpperClothes",
|
| 16 |
+
"Dress", "Coat", "Socks", "Pants", "Jumpsuits", "Scarf", "Skirt",
|
| 17 |
+
"Face", "LeftArm", "RightArm", "LeftLeg", "RightLeg", "LeftShoe",
|
| 18 |
+
"RightShoe"]
|
| 19 |
+
|
| 20 |
+
# LIP palette, RGB.
|
| 21 |
+
COLORS = [(0, 0, 0), (128, 0, 0), (255, 0, 0), (0, 85, 0), (170, 0, 51),
|
| 22 |
+
(255, 85, 0), (0, 0, 85), (0, 119, 221), (85, 85, 0), (0, 85, 85),
|
| 23 |
+
(85, 51, 0), (52, 86, 128), (0, 128, 0), (0, 0, 255), (51, 170, 221),
|
| 24 |
+
(0, 255, 255), (85, 255, 170), (170, 255, 85), (255, 255, 0),
|
| 25 |
+
(255, 170, 0)]
|
| 26 |
+
|
| 27 |
+
# Mirroring an image swaps the left and right body parts, so the channels of
|
| 28 |
+
# the mirrored prediction have to be swapped back before the two are averaged.
|
| 29 |
+
FLIP_PAIRS = [(14, 15), (16, 17), (18, 19)]
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def preprocess(image):
|
| 33 |
+
"""Build the [2, 3, 384, 384] blob: the image and its mirror, mean-subtracted."""
|
| 34 |
+
resized = cv.resize(image, (INPUT_SIZE, INPUT_SIZE))
|
| 35 |
+
mirror = np.flip(resized, axis=1)
|
| 36 |
+
return cv.dnn.blobFromImages([resized, mirror], mean=MEAN)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def postprocess(out, size):
|
| 40 |
+
"""Average the two predictions and turn them into a label map of `size`.
|
| 41 |
+
|
| 42 |
+
`out` is [2, 20, 384, 384]; `size` is the (width, height) to scale back to.
|
| 43 |
+
"""
|
| 44 |
+
direct, mirrored = out[0], out[1]
|
| 45 |
+
|
| 46 |
+
order = list(range(len(CLASSES)))
|
| 47 |
+
for left, right in FLIP_PAIRS:
|
| 48 |
+
order[left], order[right] = right, left
|
| 49 |
+
mirrored = np.flip(mirrored[order], axis=2)
|
| 50 |
+
|
| 51 |
+
scores = 0.5 * (direct + mirrored)
|
| 52 |
+
scores = np.stack([cv.resize(c, size, interpolation=cv.INTER_LINEAR) for c in scores])
|
| 53 |
+
return scores.argmax(axis=0).astype(np.uint8)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def colorize(labels):
|
| 57 |
+
"""Paint a label map with the LIP palette, as a BGR image."""
|
| 58 |
+
palette = np.array(COLORS, dtype=np.uint8)[:, ::-1] # RGB -> BGR
|
| 59 |
+
return palette[labels]
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def parse_human(net, image):
|
| 63 |
+
"""Run the network on one image and return its label map."""
|
| 64 |
+
net.setInput(preprocess(image))
|
| 65 |
+
out = net.forward()
|
| 66 |
+
return postprocess(out, (image.shape[1], image.shape[0]))
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def main():
|
| 70 |
+
parser = argparse.ArgumentParser(description="JPPNet human parsing (ONNX) demo")
|
| 71 |
+
parser.add_argument("--model", default=os.path.join(here, "human_parsing_jppnet_2026sep.onnx"))
|
| 72 |
+
parser.add_argument("--image", default=os.path.join(here, "example_outputs", "input_image.png"))
|
| 73 |
+
parser.add_argument("--output", default=os.path.join(here, "example_outputs", "output_image.png"))
|
| 74 |
+
parser.add_argument("--show", action="store_true", help="display the result in a window")
|
| 75 |
+
args = parser.parse_args()
|
| 76 |
+
|
| 77 |
+
image = cv.imread(args.image)
|
| 78 |
+
if image is None:
|
| 79 |
+
raise SystemExit("could not read image: %s" % args.image)
|
| 80 |
+
|
| 81 |
+
net = cv.dnn.readNetFromONNX(args.model)
|
| 82 |
+
labels = parse_human(net, image)
|
| 83 |
+
segmentation = colorize(labels)
|
| 84 |
+
|
| 85 |
+
present = [(CLASSES[i], int((labels == i).sum())) for i in np.unique(labels)]
|
| 86 |
+
print("human_parsing_jppnet input %dx%d" % (image.shape[1], image.shape[0]))
|
| 87 |
+
for name, pixels in sorted(present, key=lambda p: -p[1]):
|
| 88 |
+
print(" %-14s %7d px" % (name, pixels))
|
| 89 |
+
|
| 90 |
+
cv.imwrite(args.output, segmentation)
|
| 91 |
+
print("wrote", args.output)
|
| 92 |
+
|
| 93 |
+
if args.show:
|
| 94 |
+
cv.imshow("Deep learning human parsing in OpenCV", segmentation)
|
| 95 |
+
cv.waitKey()
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
if __name__ == "__main__":
|
| 99 |
+
main()
|
human_parsing_jppnet/example_outputs/input_image.png
ADDED
|
Git LFS Details
|
human_parsing_jppnet/example_outputs/output_image.png
ADDED
|
Git LFS Details
|
human_parsing_jppnet/human_parsing_jppnet_2026sep.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:eeace33fc98ed398bb33a3df3dca20839d9c7bcae8cfd3984409b4ddf8c426b4
|
| 3 |
+
size 431265151
|