效果
有个要提取图片主色调的需求,记录一下。
代码编写
import numpy as np
import cv2
from sklearn.cluster import KMeans
from skimage.color import rgb2lab, deltaE_cie76
from collections import Counter
# 创建默认变量
# 这是用于确定背景的阈值
remove_background_threshold = 235
# 这是用于确定要提取的颜色数量的参数
extract_colors_num_colors = 8
# 这是用于确定两种颜色是否相似的阈值
is_similar_color_threshold = 30
def remove_background(image, threshold=remove_background_threshold):
# Convert image to grayscale
# 将图像转换为灰度图
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Create a binary mask of the background
# 创建一个背景的二值掩码
_, mask = cv2.threshold(gray, threshold, 255, cv2.THRESH_BINARY_INV)
# Apply the mask to the original image
# 将掩码应用到原始图像上
result = cv2.bitwise_and(image, image, mask=mask)
return result
def get_color_name(lab):
colors = {
"red": [53.23, 80.11, 67.22],
"green": [87.74, -86.18, 83.18],
"blue": [32.30, 79.19, -107.86],
"yellow": [97.14, -21.55, 94.48],
"cyan": [91.11