Skip to main content
Glama
duke0317

Image Processing MCP Server

by duke0317

extract_colors

Extract dominant colors from images to analyze color schemes, identify primary palettes, or process visual data for design and analysis purposes.

Instructions

提取图片主要颜色

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
image_sourceYes图片源,可以是文件路径或base64编码的图片数据
num_colorsNo要提取的主要颜色数量
output_formatNo输出格式:PNG、JPEG、WEBP 等PNG

Implementation Reference

  • The core handler function for the 'extract_colors' tool. It processes the input image by quantizing it to extract the dominant colors, computes RGB and HEX representations, and optionally generates a visual palette image using PIL.
    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)
            )]
  • Input schema definition for the 'extract_colors' tool, defining parameters like image_source, color_count, and palette options as part of the Tool object in get_advanced_tools().
    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:752-771 (registration)
    MCP tool registration for 'extract_colors' using @mcp.tool() decorator. This wrapper function adapts parameters and calls the advanced handler from tools.advanced.
    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)

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/duke0317/ps-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server