import cv2
import numpy as np
def get_contour_colors(num_contours):
# 定义颜色表 (BGR 格式)
colors = [
(255, 0, 0),
(255, 50, 0),
(255, 100, 0),
(255, 150, 0),
(255, 200, 0),
(255, 255, 0),
(200, 255, 0),
(150, 255, 0),
(100, 255, 0),
(50, 255, 0),
(0, 255, 0),
(0, 255, 50),
(0, 255, 100),
(0, 255, 150),
(0, 255, 200),
(0, 255, 255),
(0, 200, 255),
(0, 150, 255),
(0, 100, 255),
(0, 50, 255),
(0, 0, 255),
]
# 返回一个颜色表
return [colors[i % len(colors)] for i in range(num_contours)]
def fill_contours(img, contours):
# 创建空白的图像,用来画轮廓表
filled_img = np.zeros_like(img)
num_contours = len(contours)
# 颜色表
colors = get_contour_colors(num_contours)
for i, contour in enumerate(contours):
cv2.drawContours(filled_img, [contour], -1, colors[i], -1)
return filled_img
# 读取原图,原图是RGB图
img = cv2.imread('1.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 查找轮廓
contours, _ = cv2.findContours(gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
# 填充轮廓
filled_img = fill_contours(img, contours)
cv2.imshow('Filled Contours', filled_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
原图:
输出: