Skip to content

Commit b064a48

Browse files
soulslicergineshidalgo99
authored andcommitted
New examples for PyOpenPose (CMU-Perceptual-Computing-Lab#1039)
1 parent 3356336 commit b064a48

File tree

11 files changed

+480
-15
lines changed

11 files changed

+480
-15
lines changed

doc/modules/python_module.md

Lines changed: 90 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
OpenPose Python Module and Demo
2-
=============================================
1+
# OpenPose Python Module and Demo
32

43
## Contents
54
1. [Introduction](#introduction)
@@ -18,7 +17,29 @@ This module exposes a Python API for OpenPose. It is effectively a wrapper that
1817
## Compatibility
1918
The OpenPose Python module is compatible with both Python 2 and Python 3. In addition, it will also run in all OpenPose compatible operating systems. It uses [Pybind11](https://github.com/pybind/pybind11) for mapping between C++ and Python datatypes.
2019

21-
To compile, enable `BUILD_PYTHON` in cmake. Pybind selects the latest version of Python by default (Python 3). To use Python 2, change `PYTHON_EXECUTABLE` and `PYTHON_LIBRARY` flags in cmake to your desired python version.
20+
To compile, enable `BUILD_PYTHON` in cmake. Pybind selects the latest version of Python by default (Python 3). To use Python 2, change `PYTHON_EXECUTABLE` and `PYTHON_LIBRARY` flags in cmake-gui to your desired python version.
21+
22+
Ubuntu Eg:
23+
24+
```
25+
PYTHON_EXECUTABLE=/usr/bin/python2.7
26+
PYTHON_LIBRARY=/usr/lib/x86_64-linux-gnu/libpython2.7m.so
27+
```
28+
29+
Mac OSX Eg:
30+
31+
```
32+
PYTHON_EXECUTABLE=/usr/local/bin/python2.7
33+
PYTHON_LIBRARY=/usr/local/opt/python/Frameworks/Python.framework/Versions/2.7/lib/libpython2.7m.dylib
34+
```
35+
36+
Windows Eg:
37+
38+
```
39+
PYTHON_EXECUTABLE=C:/Users/user/AppData/Local/Programs/Python/Python27/python.exe
40+
```
41+
42+
If run via the command line, you may need to run cmake twice in order for this change to take effect.
2243

2344

2445

@@ -61,5 +82,69 @@ python3 2_whole_body_from_image.py
6182
## Exporting Python OpenPose
6283
Note: This step is only required if you are moving the `*.py` files outside their original location, or writting new `*.py` scripts outside `build/examples/tutorial_api_python`.
6384

64-
- Option a, installing OpenPose: On an Ubuntu or OSX based system, you could install OpenPose by running `sudo make install`, you could then set the OpenPose path in your python scripts to the OpenPose installation path (default: `/usr/local/python`) and start using OpenPose at any location. Take a look at `build/examples/tutorial_pose/1_body_from_image.py` for an example.
65-
- Option b, not installing OpenPose: To move the OpenPose Python API demos to a different folder, ensure that the line `sys.path.append('{OpenPose_path}/python')` is properly set in your `*.py` files, where `{OpenPose_path}` points to your build folder of OpenPose. Take a look at `build/examples/tutorial_pose/1_body_from_image.py` for an example.
85+
Ubuntu/OSX:
86+
87+
- Option a, installing OpenPose: On an Ubuntu or OSX based system, you could install OpenPose by running `sudo make install`, you could then set the OpenPose path in your python scripts to the OpenPose installation path (default: `/usr/local/python`) and start using OpenPose at any location. Take a look at `build/examples/tutorial_api_python/1_body_from_image.py` for an example.
88+
- Option b, not installing OpenPose: To move the OpenPose Python API demos to a different folder, ensure that the line `sys.path.append('{OpenPose_path}/python')` is properly set in your `*.py` files, where `{OpenPose_path}` points to your build folder of OpenPose. Take a look at `build/examples/tutorial_api_python/1_body_from_image.py` for an example.
89+
90+
Windows:
91+
92+
- Ensure that the folder `build/x{86/64}/Release`and `build/bin` are copied along with `build/python` As noted in the example, the path for these can be changed in the following two variables:
93+
94+
```
95+
sys.path.append(dir_path + '/../../python/openpose/Release);
96+
os.environ['PATH'] = os.environ['PATH'] + ';' + dir_path + '/../../{x86/x64}/Release;' + dir_path + '/../../bin;'
97+
```
98+
99+
100+
101+
#### Common Issues
102+
The error in general is that openpose cannot be found. Ensure first that `BUILD_PYTHON` flag is set to ON. If the error persists, check the following:
103+
104+
In the script you are running, check for the following line, and run the following command in the same location as where the file is
105+
106+
**Ubuntu/OSX:**
107+
108+
`sys.path.append('../../python');`
109+
110+
```
111+
ls ../../python/openpose
112+
```
113+
114+
Check the contents of this location. It should contain one of the following files:
115+
116+
```
117+
pyopenpose.cpython-35m-x86_64-linux-gnu.so
118+
pyopenpose.so
119+
```
120+
121+
If you do not have any one of those, you may not have compiled openpose successfully, or you may be running the examples, not from the build folder but the source folder. If you have the first one, you have compiled pyopenpose for python 3, and have to run the scripts with python3, and vice versa for the 2nd one. Follow the testing examples above for exact commands.
122+
123+
**Windows:**
124+
125+
Python for Openpose needs to be compiled in Release mode for now. This can be done in [Visual Studio](https://cdn.stereolabs.com/docs/getting-started/images/release_mode.png). Once that is done check this line:
126+
127+
`sys.path.append(dir_path + '/../../python/openpose/Release');`
128+
129+
```
130+
dir ../../python/openpose/Release
131+
```
132+
133+
Check the contents of this location. It should contain one of the following files:
134+
135+
```
136+
pyopenpose.cp36-win_amd64.pyd
137+
pyopenpose.pyd
138+
```
139+
140+
If such a folder does not exist, you need to compile in Release mode as seen above. If you have the first one, you have compiled pyopenpose for python 3, and have to run the scripts with python3, and vice versa for the 2nd one. Follow the testing examples above for exact commands. If that still does not work, check this line:
141+
142+
`os.environ['PATH'] = os.environ['PATH'] + ';' + dir_path + '/../../x64/Release;' + dir_path + '/../../bin;'`
143+
144+
```
145+
dir ../../x64/Release
146+
dir ../../bin
147+
```
148+
149+
Ensure that both of these paths exist, as pyopenpose needs to reference those libraries. If they don't exist, change the path so that they point to the correct location in your build folder
150+

examples/tutorial_api_cpp/08_heatmaps_from_image.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ bool display(
4343
const cv::Mat inputNetDataR(
4444
height, width, CV_32F, &inputNetData.getPtr()[2*height*width]);
4545
cv::Mat netInputImage;
46-
cv::merge({inputNetDataB, inputNetDataG, inputNetDataR}, netInputImage);
46+
cv::merge(std::vector<cv::Mat>{inputNetDataB, inputNetDataG, inputNetDataR}, netInputImage);
4747
netInputImage = (netInputImage+0.5)*255;
4848
// Turn into uint8 cv::Mat
4949
cv::Mat netInputImageUint8;

examples/tutorial_api_python/1_body_from_image.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,5 @@
6363

6464
# Display Image
6565
print("Body keypoints: \n" + str(datum.poseKeypoints))
66-
while 1:
67-
cv2.imshow("win", datum.cvOutputData)
68-
cv2.waitKey(15)
66+
cv2.imshow("OpenPose 1.4.0 - Tutorial Python API", datum.cvOutputData)
67+
cv2.waitKey(0)

examples/tutorial_api_python/2_whole_body_from_image.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,5 @@
6868
print("Face keypoints: \n" + str(datum.faceKeypoints))
6969
print("Left hand keypoints: \n" + str(datum.handKeypoints[0]))
7070
print("Right hand keypoints: \n" + str(datum.handKeypoints[1]))
71-
while 1:
72-
cv2.imshow("win", datum.cvOutputData)
73-
cv2.waitKey(15)
71+
cv2.imshow("OpenPose 1.4.0 - Tutorial Python API", datum.cvOutputData)
72+
cv2.waitKey(0)

examples/tutorial_api_python/3_heatmaps_from_image.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,9 @@
3535
params = dict()
3636
params["model_folder"] = "../../../models/"
3737
params["heatmaps_add_parts"] = True
38+
params["heatmaps_add_bkg"] = True
3839
params["heatmaps_add_PAFs"] = True
40+
params["heatmaps_scale"] = 2
3941

4042
# Add others in path?
4143
for i in range(0, len(args[1])):
@@ -69,7 +71,7 @@
6971
outputImageF = cv2.merge([outputImageF[0,:,:], outputImageF[1,:,:], outputImageF[2,:,:]])
7072
outputImageF = (outputImageF*255.).astype(dtype='uint8')
7173
heatmaps = datum.poseHeatMaps.copy()
72-
heatmaps = (heatmaps*255.).astype(dtype='uint8')
74+
heatmaps = (heatmaps).astype(dtype='uint8')
7375

7476
# Display Image
7577
counter = 0
@@ -78,7 +80,9 @@
7880
heatmap = heatmaps[counter, :, :].copy()
7981
heatmap = cv2.applyColorMap(heatmap, cv2.COLORMAP_JET)
8082
combined = cv2.addWeighted(outputImageF, 0.5, heatmap, 0.5, 0)
81-
cv2.imshow("win", combined)
82-
cv2.waitKey(-1)
83+
cv2.imshow("OpenPose 1.4.0 - Tutorial Python API", combined)
84+
key = cv2.waitKey(-1)
85+
if key == 27:
86+
break
8387
counter += 1
8488
counter = counter % num_maps
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
# From Python
2+
# It requires OpenCV installed for Python
3+
import sys
4+
import cv2
5+
import os
6+
from sys import platform
7+
import argparse
8+
import time
9+
10+
# Import Openpose (Windows/Ubuntu/OSX)
11+
dir_path = os.path.dirname(os.path.realpath(__file__))
12+
try:
13+
# Windows Import
14+
if platform == "win32":
15+
# Change these variables to point to the correct folder (Release/x64 etc.)
16+
sys.path.append(dir_path + '/../../python/openpose/Release');
17+
os.environ['PATH'] = os.environ['PATH'] + ';' + dir_path + '/../../x64/Release;' + dir_path + '/../../bin;'
18+
import pyopenpose as op
19+
else:
20+
# Change these variables to point to the correct folder (Release/x64 etc.)
21+
sys.path.append('../../python');
22+
# If you run `make install` (default path is `/usr/local/python` for Ubuntu), you can also access the OpenPose/python module from there. This will install OpenPose and the python library at your desired installation path. Ensure that this is in your python path in order to use it.
23+
# sys.path.append('/usr/local/python')
24+
from openpose import pyopenpose as op
25+
except ImportError as e:
26+
print('Error: OpenPose library could not be found. Did you enable `BUILD_PYTHON` in CMake and have this Python script in the right folder?')
27+
raise e
28+
29+
# Flags
30+
parser = argparse.ArgumentParser()
31+
parser.add_argument("--image_dir", default="../../../examples/media/", help="Process a directory of images. Read all standard formats (jpg, png, bmp, etc.).")
32+
parser.add_argument("--no_display", default=False, help="Enable to disable the visual display.")
33+
args = parser.parse_known_args()
34+
35+
# Custom Params (refer to include/openpose/flags.hpp for more parameters)
36+
params = dict()
37+
params["model_folder"] = "../../../models/"
38+
39+
# Add others in path?
40+
for i in range(0, len(args[1])):
41+
curr_item = args[1][i]
42+
if i != len(args[1])-1: next_item = args[1][i+1]
43+
else: next_item = "1"
44+
if "--" in curr_item and "--" in next_item:
45+
key = curr_item.replace('-','')
46+
if key not in params: params[key] = "1"
47+
elif "--" in curr_item and "--" not in next_item:
48+
key = curr_item.replace('-','')
49+
if key not in params: params[key] = next_item
50+
51+
# Construct it from system arguments
52+
# op.init_argv(args[1])
53+
# oppython = op.OpenposePython()
54+
55+
# Starting OpenPose
56+
opWrapper = op.WrapperPython()
57+
opWrapper.configure(params)
58+
opWrapper.start()
59+
60+
# Read frames on directory
61+
imagePaths = op.get_images_on_directory(args[0].image_dir);
62+
start = time.time()
63+
64+
# Process and display images
65+
for imagePath in imagePaths:
66+
datum = op.Datum()
67+
imageToProcess = cv2.imread(imagePath)
68+
datum.cvInputData = imageToProcess
69+
opWrapper.emplaceAndPop([datum])
70+
71+
print("Body keypoints: \n" + str(datum.poseKeypoints))
72+
73+
if not args[0].no_display:
74+
cv2.imshow("OpenPose 1.4.0 - Tutorial Python API", datum.cvOutputData)
75+
key = cv2.waitKey(15)
76+
if key == 27: break
77+
78+
end = time.time()
79+
print("OpenPose demo successfully finished. Total time: " + str(end - start) + " seconds")
Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
# From Python
2+
# It requires OpenCV installed for Python
3+
import sys
4+
import cv2
5+
import os
6+
from sys import platform
7+
import argparse
8+
import time
9+
10+
# Import Openpose (Windows/Ubuntu/OSX)
11+
dir_path = os.path.dirname(os.path.realpath(__file__))
12+
try:
13+
# Windows Import
14+
if platform == "win32":
15+
# Change these variables to point to the correct folder (Release/x64 etc.)
16+
sys.path.append(dir_path + '/../../python/openpose/Release');
17+
os.environ['PATH'] = os.environ['PATH'] + ';' + dir_path + '/../../x64/Release;' + dir_path + '/../../bin;'
18+
import pyopenpose as op
19+
else:
20+
# Change these variables to point to the correct folder (Release/x64 etc.)
21+
sys.path.append('../../python');
22+
# If you run `make install` (default path is `/usr/local/python` for Ubuntu), you can also access the OpenPose/python module from there. This will install OpenPose and the python library at your desired installation path. Ensure that this is in your python path in order to use it.
23+
# sys.path.append('/usr/local/python')
24+
from openpose import pyopenpose as op
25+
except ImportError as e:
26+
print('Error: OpenPose library could not be found. Did you enable `BUILD_PYTHON` in CMake and have this Python script in the right folder?')
27+
raise e
28+
29+
# Flags
30+
parser = argparse.ArgumentParser()
31+
parser.add_argument("--image_dir", default="../../../examples/media/", help="Process a directory of images. Read all standard formats (jpg, png, bmp, etc.).")
32+
parser.add_argument("--no_display", default=False, help="Enable to disable the visual display.")
33+
args = parser.parse_known_args()
34+
35+
# Custom Params (refer to include/openpose/flags.hpp for more parameters)
36+
params = dict()
37+
params["model_folder"] = "../../../models/"
38+
39+
# Add others in path?
40+
for i in range(0, len(args[1])):
41+
curr_item = args[1][i]
42+
if i != len(args[1])-1: next_item = args[1][i+1]
43+
else: next_item = "1"
44+
if "--" in curr_item and "--" in next_item:
45+
key = curr_item.replace('-','')
46+
if key not in params: params[key] = "1"
47+
elif "--" in curr_item and "--" not in next_item:
48+
key = curr_item.replace('-','')
49+
if key not in params: params[key] = next_item
50+
51+
# Construct it from system arguments
52+
# op.init_argv(args[1])
53+
# oppython = op.OpenposePython()
54+
55+
# Starting OpenPose
56+
opWrapper = op.WrapperPython()
57+
opWrapper.configure(params)
58+
opWrapper.start()
59+
60+
# Read frames on directory
61+
imagePaths = op.get_images_on_directory(args[0].image_dir);
62+
63+
# Read number of GPUs in your system
64+
numberGPUs = op.get_gpu_number()
65+
start = time.time()
66+
67+
# Process and display images
68+
for imageBaseId in range(0, len(imagePaths), numberGPUs):
69+
70+
# Create datums
71+
datums = []
72+
73+
# Read and push images into OpenPose wrapper
74+
for gpuId in range(0, numberGPUs):
75+
76+
imageId = imageBaseId+gpuId
77+
if imageId < len(imagePaths):
78+
79+
imagePath = imagePaths[imageBaseId+gpuId]
80+
datum = op.Datum()
81+
imageToProcess = cv2.imread(imagePath)
82+
datum.cvInputData = imageToProcess
83+
datums.append(datum)
84+
opWrapper.waitAndEmplace([datums[-1]])
85+
86+
# Retrieve processed results from OpenPose wrapper
87+
for gpuId in range(0, numberGPUs):
88+
89+
imageId = imageBaseId+gpuId
90+
if imageId < len(imagePaths):
91+
92+
datum = datums[gpuId]
93+
opWrapper.waitAndPop([datum])
94+
95+
print("Body keypoints: \n" + str(datum.poseKeypoints))
96+
97+
if not args[0].no_display:
98+
cv2.imshow("OpenPose 1.4.0 - Tutorial Python API", datum.cvOutputData)
99+
key = cv2.waitKey(15)
100+
if key == 27: break
101+
102+
end = time.time()
103+
print("OpenPose demo successfully finished. Total time: " + str(end - start) + " seconds")

0 commit comments

Comments
 (0)