如何用Python获取透明背景衬衫图像的边界坐标与尺寸信息
提取带透明背景衬衫图像的边界坐标
针对带透明背景的衬衫图像,我们可以通过识别非透明像素区域的外接矩形来获取目标的位置和尺寸,以下是具体实现方案:
实现思路
利用图像的alpha通道筛选出所有不透明的像素点,然后计算这些像素点的最小、最大x/y坐标,以此确定外接矩形的左上角位置、宽度和高度。
Python 实现代码
我们使用Pillow库来处理图像,先安装依赖:
pip install pillow
然后编写代码:
from PIL import Image import numpy as np # 加载图像 img = Image.open("shirt.png") # 替换为你的图像路径 img_array = np.array(img) # 获取alpha通道(透明通道) alpha_channel = img_array[:, :, 3] # 找出所有非透明像素的坐标 non_transparent_pixels = np.where(alpha_channel > 0) y_coords, x_coords = non_transparent_pixels # 计算边界 x_min = x_coords.min() y_min = y_coords.min() x_max = x_coords.max() y_max = y_coords.max() # 计算宽度和高度 width = x_max - x_min + 1 height = y_max - y_min + 1 # 整理成目标格式 result = { "x": x_min, "y": y_min, "width": width, "height": height } print(result)
结果说明
运行代码后会输出类似如下格式的结果:
{ "x": 120, "y": 85, "width": 620, "height": 780 }
其中x和y是衬衫区域左上角的坐标,width和height是衬衫区域的宽高。
内容的提问来源于stack exchange,提问作者Jay-R Joseph Gabunada
相关产品推荐
相关产品推荐

