本文整理汇总了Python中cv2.kmeans方法的典型用法代码示例。如果您正苦于以下问题:Python cv2.kmeans方法的具体用法?Python cv2.kmeans怎么用?Python cv2.kmeans使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类cv2
的用法示例。
在下文中一共展示了cv2.kmeans方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _detect_team_color
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import kmeans [as 别名]
def _detect_team_color(self, pixels):
criteria = \
(cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
pixels = np.array(pixels.reshape((-1, 3)), dtype=np.float32)
ret, label, center = cv2.kmeans(
pixels, 2, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)
# one is black, another is the team color.
colors = np.array(center, dtype=np.uint8).reshape((1, 2, 3))
colors_hsv = cv2.cvtColor(colors, cv2.COLOR_BGR2HSV)
x = np.argmax(colors_hsv[:, :, 2])
team_color_bgr = colors[0, x, :]
team_color_hsv = colors_hsv[0, x, :]
return {
'rgb': cv2.cvtColor(colors, cv2.COLOR_BGR2RGB).tolist()[0][x],
'hsv': cv2.cvtColor(colors, cv2.COLOR_BGR2HSV).tolist()[0][x],
}
示例2: color_quantization
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import kmeans [as 别名]
def color_quantization(image, k):
"""Performs color quantization using K-means clustering algorithm"""
# Transform image into 'data':
data = np.float32(image).reshape((-1, 3))
# print(data.shape)
# Define the algorithm termination criteria (the maximum number of iterations and/or the desired accuracy):
# In this case the maximum number of iterations is set to 20 and epsilon = 1.0
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 20, 1.0)
# Apply K-means clustering algorithm:
ret, label, center = cv2.kmeans(data, k, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)
# At this point we can make the image with k colors
# Convert center to uint8:
center = np.uint8(center)
# Replace pixel values with their center value:
result = center[label.flatten()]
result = result.reshape(img.shape)
return result
# Create the dimensions of the figure and set title:
开发者ID:PacktPublishing,项目名称:Mastering-OpenCV-4-with-Python,代码行数:26,代码来源:k_means_color_quantization.py
示例3: kmeans
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import kmeans [as 别名]
def kmeans(samples, k, criteria = None, attempts = 3, flags = None):
import cv2
if flags == None:
flags = cv2.KMEANS_RANDOM_CENTERS
if criteria == None:
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
samples = np.asarray(samples, dtype = np.float32)
_,labels,centers = cv2.kmeans(samples, k, criteria, attempts, flags)
labels = util.np.flatten(labels)
clusters = [None]*k
for idx, label in enumerate(labels):
if clusters[label] is None:
clusters[label] = []
clusters[label].append(idx)
for idx, cluster in enumerate(clusters):
if cluster == None:
logging.warn('Empty cluster appeared.')
clusters[idx] = []
return labels, clusters, centers
示例4: kmeans
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import kmeans [as 别名]
def kmeans(vs, ks, niter):
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER,
niter, 0.01)
flags = cv2.KMEANS_RANDOM_CENTERS
compactness, labels, centers = cv2.kmeans(
vs, ks, criteria, 1, flags)
return centers
示例5: _kmeans_colour
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import kmeans [as 别名]
def _kmeans_colour(self, row: np.ndarray) -> Tuple:
_, labels, palette = cv2.kmeans(
row, self.k, None, self.criteria, 10, self.flags
)
_, counts = np.unique(labels, return_counts=True)
return palette[np.argmax(counts)] / 255
示例6: drawBitmap
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import kmeans [as 别名]
def drawBitmap(w_image):
print('Reducing the colors...')
Z = w_image.reshape((-1, 3))
# convert to np.float32
Z = np.float32(Z)
# define criteria, number of clusters(K) and apply kmeans()
criteria = (cv2.TERM_CRITERIA_EPS, 10, 1.0)
global K
ret, label, center = cv2.kmeans(
Z, K, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)
# Now convert back into uint8, and make original image
center = np.uint8(center)
res = center[label.flatten()]
res = res.reshape(w_image.shape)
no = 1
for i in center:
sys.stdout.write('\rDrawing: %.2f%% [' % (
no / K * 100) + '#' * no + ' ' * (K - no) + ']')
no += 1
res2 = cv2.inRange(res, i, i)
res2 = cv2.bitwise_not(res2)
cv2.imwrite('.tmp.bmp', res2)
os.system('potrace.exe .tmp.bmp -s --flat')
# print(i)
drawSVG('.tmp.svg', '#%02x%02x%02x' % (i[2], i[1], i[0]))
os.remove('.tmp.bmp')
os.remove('.tmp.svg')
print('\n\rFinished, close the window to exit.')
te.done()
示例7: get_dominant_color
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import kmeans [as 别名]
def get_dominant_color(pixels, clusters, attempts):
"""
Given a (N, Channels) array of pixel values, compute the dominant color via K-means
"""
clusters = min(clusters, len(pixels))
flags = cv2.KMEANS_RANDOM_CENTERS
criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_MAX_ITER, 1, 10)
_, labels, centroids = cv2.kmeans(pixels.astype(np.float32), clusters, None, criteria, attempts, flags)
_, counts = np.unique(labels, return_counts=True)
dominant = centroids[np.argmax(counts)]
return dominant
示例8: kmeans
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import kmeans [as 别名]
def kmeans(array: np.ndarray, k: int = 3):
n_channels = 3 if len(np.shape(array)) == 3 else 1
arr_values = array.reshape((-1, n_channels))
arr_values = np.float32(arr_values)
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 100, 0.2)
_, labels, (centers) = cv2.kmeans(arr_values, k, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)
centers = np.uint8(centers)
clustered_arr = centers[labels.flatten()]
clustered_arr = clustered_arr.reshape(array.shape)
return clustered_arr
示例9: color_quantization
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import kmeans [as 别名]
def color_quantization(img, n_cluster, iteration, epsilon=1.0):
Z = img.reshape((-1, 3))
Z = np.float32(Z)
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, iteration, epsilon)
ret, label, center = cv2.kmeans(Z, n_cluster, None, criteria, iteration, cv2.KMEANS_PP_CENTERS)
labels = label.reshape((img.shape[0], img.shape[1], 1))
# center = np.uint(center)
# visual = center[label.flatten()]
# visual = visual.reshape(img.shape)
# visual = np.uint8(visual)
return labels
示例10: test_kmeans
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import kmeans [as 别名]
def test_kmeans(img):
## K均值聚类
z = img.reshape((-1, 3))
z = np.float32(z)
criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
ret, label, center = cv2.kmeans(z, 20, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)
center = np.uint8(center)
res = center[label.flatten()]
res2 = res.reshape((img.shape))
cv2.imshow('preview', res2)
cv2.waitKey()
示例11: k_means
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import kmeans [as 别名]
def k_means(points: np.ndarray):
"""返回一个数组经kmeans分类后的k值以及标签,k值由计算拐点给出
Args:
points (np.ndarray): 需分类数据
Returns:
Tuple[int, np.ndarry]: k值以及标签数组
"""
# Define criteria = ( type, max_iter = 10 , epsilon = 1.0 )
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
# Set flags (Just to avoid line break in the code)
flags = cv2.KMEANS_RANDOM_CENTERS
length = []
max_k = min(10, points.shape[0])
for k in range(2, max_k + 1):
avg = 0
for i in range(5):
compactness, _, _ = cv2.kmeans(
points, k, None, criteria, 10, flags)
avg += compactness
avg /= 5
length.append(avg)
peek_pos = find_peek(length)
k = peek_pos + 2
# print(k)
return k, cv2.kmeans(points, k, None, criteria, 10, flags)[1] # labels
示例12: get_group_center
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import kmeans [as 别名]
def get_group_center(points1: np.ndarray, points2: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
"""输入两个相对应的点对数组,返回经kmeans优化后的两个数组
Args:
points1 (np.ndarray): 数组一
points2 (np.ndarray): 数组二
Returns:
Tuple[np.ndarray, np.ndarray]: 两数组
"""
k, labels = k_means(points1)
labels = labels.flatten()
selected_centers1 = []
selected_centers2 = []
for i in range(k):
center1 = np.mean(points1[labels == i], axis=0)
center2 = np.mean(points2[labels == i], axis=0)
# center1 = points1[labels == i][0]
# center2 = points2[labels == i][0]
selected_centers1.append(center1)
selected_centers2.append(center2)
selected_centers1, selected_centers2 = np.array(
selected_centers1), np.array(selected_centers2)
# return selected_centers1, selected_centers2
# return np.append(selected_centers1, points1, axis=0), np.append(selected_centers2, points2, axis=0)
return points1, points2
示例13: k_means
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import kmeans [as 别名]
def k_means(self, keypoints):
# convert to np.float32
X = [k.pt[0] for k in keypoints]
Y = [k.pt[1] for k in keypoints]
Z = np.float32(np.vstack((X, Y)).T)
# define criteria and apply kmeans()
criteria = (cv2.TERM_CRITERIA_EPS +
cv2.TERM_CRITERIA_MAX_ITER, 25, 1.0)
K = 6
ret, label, center = cv2.kmeans(
Z, K, criteria, 25, cv2.KMEANS_RANDOM_CENTERS)
Leaves = {}
for x in range(K):
Leaves['Center%d' % x] = Z[label.ravel() == x]
Centers = {}
for x in range(K):
Centers['Center%d' % x] = center[
label.flatten()][label.ravel() == x][0, :]
ReferencePoint = np.array([0, 0])
print Centers.values()
Distances = {}
for x in range(K):
Distances['Center%d' % x] = distance.euclidean(
ReferencePoint.ravel(), Centers['Center%d' % x])
CentersOrderedList = sorted(Distances.items(), key=lambda x: x[1])
leaves_data = {'SocketA': [Leaves[CentersOrderedList[0][0]], Centers[CentersOrderedList[0][0]], self.MaxLeavesSocketA],
'SocketB': [Leaves[CentersOrderedList[1][0]], Centers[CentersOrderedList[1][0]], self.MaxLeavesSocketB],
'SocketC': [Leaves[CentersOrderedList[2][0]], Centers[CentersOrderedList[2][0]], self.MaxLeavesSocketC],
'SocketD': [Leaves[CentersOrderedList[3][0]], Centers[CentersOrderedList[3][0]], self.MaxLeavesSocketD],
'SocketE': [Leaves[CentersOrderedList[4][0]], Centers[CentersOrderedList[4][0]], self.MaxLeavesSocketE],
'SocketF': [Leaves[CentersOrderedList[5][0]], Centers[CentersOrderedList[5][0]], self.MaxLeavesSocketF]}
return leaves_data
示例14: extract_cols
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import kmeans [as 别名]
def extract_cols(image, numCols):
# convert to np.float32 matrix that can be clustered
Z = image.reshape((-1,3))
Z = np.float32(Z)
# Set parameters for the clustering
max_iter = 20
epsilon = 1.0
K = numCols
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, max_iter, epsilon)
# cluster
lab = []
compactness, labels, centers = cv2.kmeans(data=Z, K=K, bestLabels=None, criteria=criteria, attempts=10, flags=cv2.KMEANS_RANDOM_CENTERS)
clusterCounts = []
for idx in range(K):
count = len(Z[labels == idx])
clusterCounts.append(count)
#Reverse the cols stored in centers because cols are stored in BGR
#in opencv.
rgbCenters = []
for center in centers:
bgr = center.tolist()
bgr.reverse()
rgbCenters.append(bgr)
cols = []
for i in range(K):
iCol = {
"count": clusterCounts[i],
"col": rgbCenters[i]
}
cols.append(iCol)
return cols
#
# Calculates change data one one frame to the next one.
#
示例15: color_quantization
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import kmeans [as 别名]
def color_quantization(image, k):
"""Performs color quantization using K-means clustering algorithm"""
# Transform image into 'data':
data = np.float32(image).reshape((-1, 3))
# print(data.shape)
# Define the algorithm termination criteria (the maximum number of iterations and/or the desired accuracy):
# In this case the maximum number of iterations is set to 20 and epsilon = 1.0
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 20, 1.0)
# Apply K-means clustering algorithm:
ret, label, center = cv2.kmeans(data, k, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)
# At this point we can make the image with k colors
# Convert center to uint8:
center = np.uint8(center)
# Replace pixel values with their center value:
result = center[label.flatten()]
result = result.reshape(img.shape)
# Build the 'color_distribution' legend.
# We will use the number of pixels assigned to each center value:
counter = collections.Counter(label.flatten())
print(counter)
# Calculate the total number of pixels of the input image:
total = img.shape[0] * img.shape[1]
# Assign width and height to the color_distribution image:
desired_width = img.shape[1]
# The difference between 'desired_height' and 'desired_height_colors'
# will be the separation between the images
desired_height = 70
desired_height_colors = 50
# Initialize the color_distribution image:
color_distribution = np.ones((desired_height, desired_width, 3), dtype="uint8") * 255
# Initialize start:
start = 0
for key, value in counter.items():
# Calculate the normalized value:
value_normalized = value / total * desired_width
# Move end to the right position:
end = start + value_normalized
# Draw rectangle corresponding to the current color:
cv2.rectangle(color_distribution, (int(start), 0), (int(end), desired_height_colors), center[key].tolist(), -1)
# Update start:
start = end
return np.vstack((color_distribution, result))
# Create the dimensions of the figure and set title:
开发者ID:PacktPublishing,项目名称:Mastering-OpenCV-4-with-Python,代码行数:59,代码来源:k_means_color_quantization_distribution.py