You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

单目标图像颜色检测咨询:SEINET仙人掌数据集颜色提取需求

技术指导:提取仙人掌图像颜色并保存颜色名称

1. 环境准备

  • 安装必备工具库:
    pip install opencv-python numpy
    

2. 分离仙人掌区域(图像预处理)

因为每张图仅含一株仙人掌,可通过轮廓检测提取目标区域,生成掩码过滤背景:

import cv2
import numpy as np

def get_cactus_mask(image_path):
    # 读取图像(OpenCV默认BGR格式)
    img = cv2.imread(image_path)
    # 转灰度图简化处理
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    # 自动阈值二值化,区分前景(仙人掌)和背景
    _, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
    # 提取所有轮廓,取面积最大的(即仙人掌)
    contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    max_contour = max(contours, key=cv2.contourArea)
    # 创建与原图大小一致的掩码,仅保留仙人掌区域
    mask = np.zeros_like(gray)
    cv2.drawContours(mask, [max_contour], -1, 255, thickness=cv2.FILLED)
    return img, mask

3. 提取仙人掌主颜色

利用掩码提取仙人掌像素,计算颜色平均值(新手友好,后续可升级为聚类取主色):

def get_main_color(img, mask):
    # 筛选掩码内的仙人掌像素
    cactus_pixels = img[mask == 255]
    # 计算BGR通道平均值,转RGB格式(符合常规认知)
    avg_bgr = np.mean(cactus_pixels, axis=0).astype(int)
    avg_rgb = (avg_bgr[2], avg_bgr[1], avg_bgr[0])
    return avg_rgb

4. 匹配颜色名称

自定义颜色字典,通过RGB范围匹配对应名称,可根据数据集实际颜色扩展:

# 示例颜色字典,可根据你的仙人掌样本调整范围
COLOR_MAP = {
    "鲜绿色": [(0, 120, 0), (80, 255, 80)],
    "深绿色": [(0, 50, 0), (50, 150, 50)],
    "黄绿色": [(60, 200, 60), (160, 255, 160)],
    "灰褐色": [(40, 40, 20), (130, 130, 100)]
}

def match_color_name(rgb):
    r, g, b = rgb
    for name, (lower, upper) in COLOR_MAP.items():
        lr, lg, lb = lower
        ur, ug, ub = upper
        if lr <= r <= ur and lg <= g <= ug and lb <= b <= ub:
            return name
    return "未知颜色"

5. 批量处理并保存结果

遍历数据集文件夹,将结果写入CSV文件:

import os
import csv

def batch_process_dataset(img_folder, output_csv):
    with open(output_csv, 'w', newline='', encoding='utf-8') as f:
        writer = csv.writer(f)
        writer.writerow(["图像文件名", "主颜色RGB", "颜色名称"])
        # 遍历所有图像文件
        for filename in os.listdir(img_folder):
            if filename.lower().endswith(('.jpg', '.jpeg', '.png')):
                img_path = os.path.join(img_folder, filename)
                img, mask = get_cactus_mask(img_path)
                main_rgb = get_main_color(img, mask)
                color_name = match_color_name(main_rgb)
                writer.writerow([filename, main_rgb, color_name])
                print(f"完成处理:{filename}")

# 调用示例,替换为你的实际路径
batch_process_dataset("你的仙人掌图像文件夹路径", "cactus_color_results.csv")

新手优化建议

  • 若阈值分割效果差,可改用HSV颜色空间(绿色在HSV中范围更固定)进行分割。
  • 追求更精准的主色,可使用K-means聚类将仙人掌像素聚为2-3类,取占比最高的聚类中心颜色。
  • 扩展COLOR_MAP时,可提取样本图像的RGB值,调整范围以匹配更多颜色类型。

内容的提问来源于stack exchange,提问作者Hurricane

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 22:33:13