Generate a sample code to implement body background removal and returning the edge landmarks using MediaPipe in Python
Assistant
MediaPipe is a versatile framework for building machine learning applications. To implement body background removal and returning the edge landmarks using MediaPipe in Python, you can follow these steps:
User
we got error like this:
Traceback (most recent call last):
File "/Users/jasontsai/open_sources/shrug-detection/src/pose_edge_gpt4.py", line 46, in
output_image = process_image(image)
^^^^^^^^^^^^^^^^^^^^
File "/Users/jasontsai/open_sources/shrug-detection/src/pose_edge_gpt4.py", line 23, in process_image
mp_drawing.draw_landmarks(body_mask, results.pose_landmarks, mp_holistic.POSE_CONNECTIONS)
File "/opt/homebrew/lib/python3.11/site-packages/mediapipe/python/solutions/drawing_utils.py", line 153, in draw_landmarks
if image.shape[2] != _BGR_CHANNELS:
^^^
IndexError: tuple index out of range
please tell me why and fix it, thanks.
Assistant
Apologies for the confusion. The error seems to be caused by the code I provided earlier. I made a mistake in the code, and the line containing mp_drawing.draw_landmarks() is not required. Here's the corrected code:
python
User
but it still got error:
Traceback (most recent call last):
File "/Users/jasontsai/open_sources/shrug-detection/src/pose_edge_gpt4.py", line 42, in
output_image = process_image(image)
^^^^^^^^^^^^^^^^^^^^
File "/Users/jasontsai/open_sources/shrug-detection/src/pose_edge_gpt4.py", line 33, in process_image
x, y = int(pose_results.pose_landmarks.landmark[landmark].x * image.shape[1]), int(pose_results.pose_landmarks.landmark[landmark].y * image.shape[0])
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'landmark'
Assistant
I apologize for the confusion. The error occurs because the pose_results.pose_landmarks object is None. This can happen if the Pose model couldn't find any landmarks in the image. To handle this case, you can add a conditional statement to check if the pose_landmarks object is not None before processing the landmarks.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
using System.Collections.Generic;
using UnityEngine;
public class JsonToDictionary : MonoBehaviour
{
[System.Serializable]
public class Data
{
public List<Item> items;
}
[System.Serializable]
public class Item
{
public string key;
public string value;
}
public static Dictionary<string, string> JsonToDict(string json)
{
Data data = JsonUtility.FromJson<Data>(json);
Dictionary<string, string> result = new Dictionary<string, string>();
foreach (Item item in data.items)
{
result.Add(item.key, item.value);
}
return result;
}
void Start()
{
string jsonString = "{\"items\":[{\"key\":\"key1\",\"value\":\"value1\"},{\"key\":\"key2\",\"value\":\"value2\"}]}";
Dictionary<string, string> dict = JsonToDict(jsonString);
}
}
使用SimpleJSON(首先需要導入SimpleJSON套件):
csharp
using System.Collections.Generic;
using UnityEngine;
using SimpleJSON;
public class JsonToDictionary : MonoBehaviour
{
public static Dictionary<string, string> JsonToDict(string json)
{
var jsonObj = JSON.Parse(json);
var result = new Dictionary<string, string>();
foreach (KeyValuePair<string, JSONNode> item in jsonObj.AsObject)
{
result.Add(item.Key, item.Value);
}
return result;
}
void Start()
{
string jsonString = "{\"key1\":\"value1\",\"key2\":\"value2\"}";
Dictionary<string, string> dict = JsonToDict(jsonString);
}
}
Here's the sample code to remove the body background and return the edge landmarks using MediaPipe in Python:
python
import cv2
import mediapipe as mp
mp_drawing = mp.solutions.drawing_utils
mp_selfie_segmentation = mp.solutions.selfie_segmentation
mp_pose = mp.solutions.pose
# Initialize MediaPipe pose and selfie segmentation solutions
pose = mp_pose.Pose(static_image_mode=True)
selfie_segmentation = mp_selfie_segmentation.SelfieSegmentation()
def process_image(image):
# Convert the image to RGB
image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# Get body mask using selfie_segmentation
segmentation_results = selfie_segmentation.process(image_rgb)
body_mask = segmentation_results.segmentation_mask
# Create a background and foreground masks
background_mask = cv2.bitwise_not(body_mask)
foreground_mask = cv2.bitwise_and(image_rgb, image_rgb, mask=body_mask)
# Remove the background
removed_background = cv2.add(cv2.merge([background_mask]*3), foreground_mask)
# Get pose landmarks
pose_results = pose.process(cv2.cvtColor(removed_background, cv2.COLOR_BGR2RGB))
# Draw the edge landmarks on the image
edge_landmarks = [11, 12, 13, 14, 15, 16, 23, 24, 25, 26, 27, 28]
for landmark in edge_landmarks:
x, y = int(pose_results.pose_landmarks.landmark[landmark].x * image.shape[1]), int(pose_results.pose_landmarks.landmark[landmark].y * image.shape[0])
cv2.circle(removed_background, (x, y), 5, (0, 255, 0), -1)
return removed_background
# Read the input image
image = cv2.imread("input_image.jpg")
# Process the image
output_image = process_image(image)
# Save the output image
cv2.imwrite("output_image.jpg", output_image)
In this example, we read an input image, remove the background using MediaPipe's Selfie Segmentation solution, and then detect body landmarks using MediaPipe's Pose solution. We then highlight the edge landmarks in green.
Remember to replace "input_image.jpg" with the path to your input image and "output_image.jpg" with the desired output file name.
This example uses a single image as input, but you can modify the code to work with real-time video by capturing frames from a webcam using OpenCV.
import cv2
import mediapipe as mp
mp_drawing = mp.solutions.drawing_utils
mp_selfie_segmentation = mp.solutions.selfie_segmentation
mp_pose = mp.solutions.pose
# Initialize MediaPipe pose and selfie segmentation solutions
pose = mp_pose.Pose(static_image_mode=True)
selfie_segmentation = mp_selfie_segmentation.SelfieSegmentation()
def process_image(image):
# Convert the image to RGB
image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# Get body mask using selfie_segmentation
segmentation_results = selfie_segmentation.process(image_rgb)
body_mask = segmentation_results.segmentation_mask.astype('uint8')
# Create a background and foreground masks
background_mask = cv2.bitwise_not(body_mask)
foreground_mask = cv2.bitwise_and(image_rgb, image_rgb, mask=body_mask)
# Remove the background
removed_background = cv2.add(cv2.merge([background_mask]*3), foreground_mask)
# Get pose landmarks
pose_results = pose.process(cv2.cvtColor(removed_background, cv2.COLOR_BGR2RGB))
# Draw the edge landmarks on the image
edge_landmarks = [11, 12, 13, 14, 15, 16, 23, 24, 25, 26, 27, 28]
for landmark in edge_landmarks:
x, y = int(pose_results.pose_landmarks.landmark[landmark].x * image.shape[1]), int(pose_results.pose_landmarks.landmark[landmark].y * image.shape[0])
cv2.circle(removed_background, (x, y), 5, (0, 255, 0), -1)
return removed_background
# Read the input image
image = cv2.imread("input_image.jpg")
# Process the image
output_image = process_image(image)
# Save the output image
cv2.imwrite("output_image.jpg", output_image)
In this revised version of the code, I removed the unnecessary line, and I also converted the body_mask to an integer type to avoid any errors related to floating-point masks.
Please try this updated code, and it should work without any errors.
Here's the updated code:
python
import cv2
import mediapipe as mp
mp_drawing = mp.solutions.drawing_utils
mp_selfie_segmentation = mp.solutions.selfie_segmentation
mp_pose = mp.solutions.pose
# Initialize MediaPipe pose and selfie segmentation solutions
pose = mp_pose.Pose(static_image_mode=True)
selfie_segmentation = mp_selfie_segmentation.SelfieSegmentation()
def process_image(image):
# Convert the image to RGB
image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# Get body mask using selfie_segmentation
segmentation_results = selfie_segmentation.process(image_rgb)
body_mask = segmentation_results.segmentation_mask.astype('uint8')
# Create a background and foreground masks
background_mask = cv2.bitwise_not(body_mask)
foreground_mask = cv2.bitwise_and(image_rgb, image_rgb, mask=body_mask)
# Remove the background
removed_background = cv2.add(cv2.merge([background_mask]*3), foreground_mask)
# Get pose landmarks
pose_results = pose.process(cv2.cvtColor(removed_background, cv2.COLOR_BGR2RGB))
# Draw the edge landmarks on the image, if the landmarks are detected
if pose_results.pose_landmarks is not None:
edge_landmarks = [11, 12, 13, 14, 15, 16, 23, 24, 25, 26, 27, 28]
for landmark in edge_landmarks:
x, y = int(pose_results.pose_landmarks.landmark[landmark].x * image.shape[1]), int(pose_results.pose_landmarks.landmark[landmark].y * image.shape[0])
cv2.circle(removed_background, (x, y), 5, (0, 255, 0), -1)
return removed_background
# Read the input image
image = cv2.imread("input_image.jpg")
# Process the image
output_image = process_image(image)
# Save the output image
cv2.imwrite("output_image.jpg", output_image)
In this updated version, I added a conditional statement to check if pose_results.pose_landmarks is not None before drawing the edge landmarks on the image. This should prevent the error you encountered. Please try this code and let me know if it works for you.