如何用OpenCV Python在人体图像上叠加透明衣物图像?求实现代码
How to Overlay Transparent Clothing on a Body Image with OpenCV
Got it, let's break this down for you! Since you already have the placement coordinates sorted out, the core task here is handling the transparency (alpha channel) of your clothing image and blending it properly with the body image. Here's a straightforward Python implementation using OpenCV, with two common scenarios covered:
Scenario 1: Fixed Placement (Top-Left Coordinate + Resized Clothing)
If you already know the exact top-left position and target size for the clothing, this basic approach works perfectly:
import cv2 import numpy as np # Load your images: body (no alpha) and clothing (with alpha channel, use PNG!) body_img = cv2.imread("body.jpg") clothing_img = cv2.imread("clothing.png", cv2.IMREAD_UNCHANGED) # Critical: preserves alpha channel # Validate clothing image has alpha channel if clothing_img.shape[2] != 4: raise ValueError("Your clothing image needs an alpha channel — use a PNG file!") # Resize clothing to match your calculated target dimensions target_width = 220 # Replace with your computed width target_height = 350 # Replace with your computed height clothing_resized = cv2.resize(clothing_img, (target_width, target_height)) # Split BGR channels and alpha channel (normalize alpha to 0-1 range) clothing_bgr = clothing_resized[:, :, :3] clothing_alpha = clothing_resized[:, :, 3] / 255.0 # 0 = fully transparent, 1 = fully opaque # Define placement position (top-left corner coordinates) x_pos, y_pos = 120, 210 # Replace with your calculated coordinates # Ensure clothing fits within the body image bounds rows, cols = clothing_resized.shape[:2] if y_pos + rows > body_img.shape[0] or x_pos + cols > body_img.shape[1]: raise ValueError("Clothing placement goes outside the body image — adjust coordinates/size!") # Grab the region of the body image where we'll place the clothing body_region = body_img[y_pos:y_pos+rows, x_pos:x_pos+cols] # Blend the two regions using the alpha channel as a weight blended_region = (body_region * (1 - clothing_alpha[:, :, None]) + clothing_bgr * clothing_alpha[:, :, None]).astype(np.uint8) # Replace the body region with the blended result body_img[y_pos:y_pos+rows, x_pos:x_pos+cols] = blended_region # View or save the final image cv2.imshow("Overlay Result", body_img) cv2.waitKey(0) cv2.destroyAllWindows() cv2.imwrite("final_overlay.jpg", body_img)
Scenario 2: Perspective Transform (Matching 4 Corresponding Points)
If you have 4 matching points (e.g., clothing corners aligned to body landmarks), we'll use perspective transform to warp the clothing to fit perfectly before overlaying:
import cv2 import numpy as np # Load images body_img = cv2.imread("body.jpg") clothing_img = cv2.imread("clothing.png", cv2.IMREAD_UNCHANGED) # Define your matching points (replace with your actual coordinates) # Clothing's 4 corners (clockwise: top-left, top-right, bottom-right, bottom-left) clothing_pts = np.array([[0, 0], [clothing_img.shape[1], 0], [clothing_img.shape[1], clothing_img.shape[0]], [0, clothing_img.shape[0]]], dtype=np.float32) # Corresponding points on the body image body_pts = np.array([[160, 220], [360, 230], [355, 510], [155, 500]], dtype=np.float32) # Calculate perspective transform matrix perspective_matrix = cv2.getPerspectiveTransform(clothing_pts, body_pts) h, w = body_img.shape[:2] # Warp both the clothing's BGR channels and alpha channel clothing_bgr_warped = cv2.warpPerspective(clothing_img[:, :, :3], perspective_matrix, (w, h)) clothing_alpha_warped = cv2.warpPerspective(clothing_img[:, :, 3], perspective_matrix, (w, h)) / 255.0 # Blend the warped clothing with the body image final_result = (body_img * (1 - clothing_alpha_warped[:, :, None]) + clothing_bgr_warped * clothing_alpha_warped[:, :, None]).astype(np.uint8) # View or save cv2.imshow("Perspective Overlay Result", final_result) cv2.waitKey(0) cv2.destroyAllWindows() cv2.imwrite("perspective_final.jpg", final_result)
Key Notes:
- Always use a PNG file for the clothing image — JPEG doesn't support alpha channels.
- The alpha channel is normalized to 0-1 so we can use it as a weight for blending:
background * (1 - alpha) + foreground * alpha. - If you're using landmark points (like from pose estimation), just plug those coordinates into the
body_ptsarray in the perspective transform scenario.
内容的提问来源于stack exchange,提问作者Chintun Violet
相关产品推荐
相关产品推荐

