# -*- coding: utf-8 -*-
"""
从彩色图像提取各颜色区域轮廓,并用 turtle 按区域填色绘制。
Author: ChatGPT
"""
import cv2
import numpy as np
import turtle
import json
import os
import math
#######################
# 参数区(可调)
IMG_PATH = "cinnamoroll.png" # 待处理图片路径
K = 4 # 颜色聚类数,视图片颜色复杂度调(3~8)
SIMPLIFY_FACTOR = 0.001 # 轮廓简化比例(与周长相关),越大越简化
MIN_REGION_AREA_RATIO = 0.00005 # 忽略太小区域(相对于图像总像素)
TURTLE_WINDOW = 1200 # turtle 画布尺寸(正方)
MARGIN = 80 # 留白像素用于缩放
EXPORT_JSON = True # 是否导出轮廓+颜色 JSON
JSON_PATH = "regions.json"
#######################
def rgb_to_hex(rgb):
return '#{:02x}{:02x}{:02x}'.format(int(rgb[0]), int(rgb[1]), int(rgb[2]))
def darker_color(rgb, factor=0.7):
return tuple(max(0, int(c*factor)) for c in rgb)
def quantize_colors_kmeans(img_bgr, k):
# img_bgr : HxWx3 (uint8)
Z = img_bgr.reshape((-1,3)).astype(np.float32)
# criteria (type, max_iter, epsilon)
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.2)
attempts = 4
flags = cv2.KMEANS_PP_CENTERS
compactness, labels, centers = cv2.kmeans(Z, k, None, criteria, attempts, flags)
labels = labels.flatten().reshape((img_bgr.shape[0], img_bgr.shape[1]))
centers = centers.astype(np.uint8) # BGR
return labels, centers
def find_color_regions(img_bgr, labels, centers, background_idx=None):
h, w = labels.shape
img_area = h*w
regions = []
for idx, center in enumerate(centers):
if background_idx is not None and idx == background_idx:
continue
mask = (labels == idx).astype(np.uint8) * 255
# 去噪:开/闭运
根据图像绘制画像
最新推荐文章于 2025-12-03 22:35:21 发布

最低0.47元/天 解锁文章
441

被折叠的 条评论
为什么被折叠?



