extract_colors
Extract dominant colors from an image to identify key color themes. Specify the number of colors to be extracted and the output format (PNG, JPEG, WEBP) for analysis or design purposes.
Instructions
提取图片主要颜色
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| image_source | Yes | 图片源,可以是文件路径或base64编码的图片数据 | |
| num_colors | No | 要提取的主要颜色数量 | |
| output_format | No | 输出格式:PNG、JPEG、WEBP 等 | PNG |
Implementation Reference
- tools/advanced.py:837-943 (handler)Core implementation of the extract_colors tool: loads image, quantizes to extract dominant colors using PIL, generates RGB/hex list, optionally creates palette image.async def extract_colors(arguments: Dict[str, Any]) -> List[TextContent]: """ 提取图片的主要颜色 Args: arguments: 包含图片源和颜色提取参数的字典 Returns: List[TextContent]: 处理结果 """ try: # 参数验证 image_source = arguments.get("image_source") ensure_valid_image_source(image_source) color_count = arguments.get("color_count") or arguments.get("num_colors", 5) create_palette = arguments.get("create_palette", True) palette_width = arguments.get("palette_width", 400) palette_height = arguments.get("palette_height", 100) # 验证参数 validate_numeric_range(color_count, 1, 20, "color_count") validate_numeric_range(palette_width, 100, 800, "palette_width") validate_numeric_range(palette_height, 50, 200, "palette_height") processor = ImageProcessor() image = processor.load_image(image_source) # 转换为RGB模式 if image.mode != "RGB": image = image.convert("RGB") # 使用量化来提取主要颜色 quantized = image.quantize(colors=color_count) palette_colors = quantized.getpalette() # 提取RGB颜色值 colors = [] # 确保不超过实际可用的颜色数量 actual_color_count = min(color_count, len(palette_colors) // 3) for i in range(actual_color_count): try: r = palette_colors[i * 3] g = palette_colors[i * 3 + 1] b = palette_colors[i * 3 + 2] hex_color = f"#{r:02x}{g:02x}{b:02x}" colors.append({ "rgb": [r, g, b], "hex": hex_color }) except IndexError: # 如果索引越界,停止添加颜色 break result_data = { "success": True, "message": f"成功提取{len(colors)}种主要颜色", "colors": colors, "metadata": { "image_size": f"{image.width}x{image.height}", "color_count": len(colors) } } # 创建调色板图片 if create_palette: palette_image = Image.new("RGB", (palette_width, palette_height)) color_width = palette_width // len(colors) for i, color_info in enumerate(colors): color_rgb = tuple(color_info["rgb"]) x1 = i * color_width x2 = (i + 1) * color_width if i < len(colors) - 1 else palette_width # 填充颜色块 for x in range(x1, x2): for y in range(palette_height): palette_image.putpixel((x, y), color_rgb) # 输出调色板图片 palette_output = processor.output_image(palette_image, "extract_colors", "PNG") result_data["palette"] = palette_output result_data["metadata"]["palette_size"] = f"{palette_width}x{palette_height}" return [TextContent( type="text", text=json.dumps(result_data, ensure_ascii=False) )] except ValidationError as e: return [TextContent( type="text", text=json.dumps({ "success": False, "error": f"参数验证失败: {str(e)}" }, ensure_ascii=False) )] except Exception as e: return [TextContent( type="text", text=json.dumps({ "success": False, "error": f"提取颜色失败: {str(e)}" }, ensure_ascii=False) )]
- tools/advanced.py:240-279 (schema)JSON schema definition for extract_colors tool input parameters including image_source, color_count, palette options.Tool( name="extract_colors", description="提取图片的主要颜色", inputSchema={ "type": "object", "properties": { "image_source": { "type": "string", "description": "图片源(文件路径或base64编码)" }, "color_count": { "type": "integer", "description": "提取的颜色数量", "minimum": 1, "maximum": 20, "default": 5 }, "create_palette": { "type": "boolean", "description": "是否创建调色板图片", "default": True }, "palette_width": { "type": "integer", "description": "调色板宽度", "minimum": 100, "maximum": 800, "default": 400 }, "palette_height": { "type": "integer", "description": "调色板高度", "minimum": 50, "maximum": 200, "default": 100 } }, "required": ["image_source"] } ),
- main.py:751-771 (registration)FastMCP registration of extract_colors tool with type annotations for schema, wraps and calls the advanced handler function.@mcp.tool() def extract_colors( image_source: Annotated[str, Field(description="图片源,可以是文件路径或base64编码的图片数据")], num_colors: Annotated[int, Field(description="要提取的主要颜色数量", ge=1, le=20, default=5)], output_format: Annotated[str, Field(description="输出格式:PNG、JPEG、WEBP 等", default="PNG")] ) -> str: """提取图片主要颜色""" try: arguments = { "image_source": image_source, "num_colors": num_colors, "output_format": output_format } result = safe_run_async(advanced_extract_colors(arguments)) return result[0].text except Exception as e: return json.dumps({ "success": False, "error": f"提取颜色失败: {str(e)}" }, ensure_ascii=False, indent=2)