如何用Python获取HTML map多边形区域的主色调(排除文字干扰)
实现步骤与代码
1. 安装依赖库
先安装处理图像和数组操作的必要库:
pip install pillow numpy
2. 核心实现逻辑
- 解析HTML
<area>标签里的coords字符串,转换成(x,y)坐标对列表。 - 用掩码技术只保留多边形区域内的像素,屏蔽区域外内容。
- 过滤掉区域内的白色(或接近白色)像素,避免文字干扰统计结果。
- 统计剩余像素的颜色出现频率,取最高频的颜色作为主色调。
3. 完整代码示例
from PIL import Image, ImageDraw from collections import Counter import numpy as np # 解析coords坐标字符串为(x,y)列表 def parse_coords(coords_str): coords = list(map(int, coords_str.split(','))) return list(zip(coords[::2], coords[1::2])) # 获取区域内有效像素(排除白色文字) def get_region_pixels(image_path, coords, white_threshold=240): img = Image.open(image_path).convert('RGB') width, height = img.size # 创建掩码:多边形区域设为白色,其余为黑色 mask = Image.new('L', (width, height), 0) draw = ImageDraw.Draw(mask) draw.polygon(coords, fill=255) # 转成numpy数组简化像素筛选 img_array = np.array(img) mask_array = np.array(mask) # 筛选掩码内且非白色的像素 region_pixels = img_array[mask_array == 255] valid_pixels = region_pixels[~((region_pixels[:, 0] > white_threshold) & (region_pixels[:, 1] > white_threshold) & (region_pixels[:, 2] > white_threshold))] return valid_pixels # 统计主色调 def get_dominant_color(pixels): pixel_tuples = [tuple(p) for p in pixels] color_counts = Counter(pixel_tuples) return color_counts.most_common(1)[0][0] # 执行示例 if __name__ == '__main__': # 替换为你的图片路径 image_path = 'usa-colored-regions-map.jpg' # 从HTML map中复制的田纳西州coords tennessee_coords = "492,379,521,376,562,377,568,363,583,355,589,347,595,340,570,343,535,348,515,349,507,355,494,355,491,370" coords = parse_coords(tennessee_coords) valid_pixels = get_region_pixels(image_path, coords) dominant_color = get_dominant_color(valid_pixels) print(f"该区域主色调RGB值:{dominant_color}") hex_color = '#{:02x}{:02x}{:02x}'.format(*dominant_color) print(f"十六进制表示:{hex_color}")
关键细节说明
- 坐标解析:将逗号分隔的字符串转成Pillow绘图需要的坐标对格式。
- 掩码筛选:通过掩码精准锁定目标区域,避免其他州的颜色干扰。
- 白色过滤:通过RGB阈值判断白色文字,阈值可根据图片实际情况调整(比如文字偏米白可降低阈值)。
- 多区域处理:如果有多个州的coords,只需循环调用上述函数即可批量获取主色调。
内容的提问来源于stack exchange,提问作者MOHAMMAD RASIM
相关产品推荐
相关产品推荐

