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);
}
}
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:
First, install the required packages using pip:
code
pip install mediapipe opencv-python
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.
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
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.
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.
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.
User
Generate a code to implement body background removal and returning the "body edge" landmarks using MediaPipe in Python
Assistant
Here's the code to remove the body background and return the "body 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.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))
# Define the edge landmarks
edge_landmarks = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 16, 18, 19, 20, 22, 23, 24, 26, 27, 28, 30, 31, 32]
# Draw the edge landmarks on the image, if the landmarks are detected
if pose_results.pose_landmarks is not None:
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, I have updated the edge_landmarks list to include the keypoints around the body's edge. The code removes the body background using MediaPipe's Selfie Segmentation solution and then detects body landmarks using MediaPipe's Pose solution. It then highlights the "body 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.
User
dude, but the output image is all white. what I need is "background removal" and "body edge landmarks" using "MediaPipe in Python"
Assistant
Apologies for the confusion earlier. Here's the revised code that should correctly remove the background and display body edge landmarks using MediaPipe in Python:
python
import cv2
import mediapipe as mp
import numpy as np
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(model_selection=0)
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 binary mask with a threshold
body_mask = np.where(body_mask > 0.1, 255, 0).astype(np.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))
# Define the edge landmarks
edge_landmarks = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 16, 18, 19, 20, 22, 23, 24, 26, 27, 28, 30, 31, 32]
# Draw the edge landmarks on the image, if the landmarks are detected
if pose_results.pose_landmarks is not None:
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 version of the code, I've adjusted the body mask creation by adding a threshold to create a binary mask. This should fix the issue with the white output image. The code removes the background using MediaPipe's Selfie Segmentation solution and then detects body landmarks using MediaPipe's Pose solution. It then highlights the "body edge" landmarks in green.
Please replace "input_image.jpg" with the path to your input image and "output_image.jpg" with the desired output file name.
You can also modify this code to work with real-time video by capturing frames from a webcam using OpenCV.
User
bro, could you help me to change this code in your answer from "body landmarks" to human "body edge landmarks"?
if pose_results.pose_landmarks is not None:
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)
Assistant
My apologies for the confusion earlier. As MediaPipe's Pose solution does not provide body edge landmarks directly, we can use the contour of the binary body mask instead. Here's the updated code to display the human body edge landmarks:
python
import cv2
import mediapipe as mp
import numpy as np
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(model_selection=0)
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 binary mask with a threshold
body_mask = np.where(body_mask > 0.1, 255, 0).astype(np.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)
# Find the contours in the body_mask
contours, _ = cv2.findContours(body_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# Draw the body edge landmarks (contour points) on the removed_background image
for contour in contours:
for point in contour:
x, y = point[0][0], point[0][1]
cv2.circle(removed_background, (x, y), 2, (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 code, I removed the part that uses pose landmarks and replaced it with a contour extraction from the binary body mask. The code finds the contours of the body mask and then iterates over the contour points, drawing circles for each point on the removed_background image. This should provide an approximation of the body edge landmarks.
Remember to replace "input_image.jpg" with the path to your input image and "output_image.jpg" with the desired output file name.