本文整理匯總了Python中cv2.KMEANS_RANDOM_CENTERS屬性的典型用法代碼示例。如果您正苦於以下問題:Python cv2.KMEANS_RANDOM_CENTERS屬性的具體用法?Python cv2.KMEANS_RANDOM_CENTERS怎麽用?Python cv2.KMEANS_RANDOM_CENTERS使用的例子?那麽, 這裏精選的屬性代碼示例或許可以為您提供幫助。您也可以進一步了解該屬性所在類cv2
的用法示例。
在下文中一共展示了cv2.KMEANS_RANDOM_CENTERS屬性的12個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: _detect_team_color
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import KMEANS_RANDOM_CENTERS [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_RANDOM_CENTERS [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_RANDOM_CENTERS [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_RANDOM_CENTERS [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: drawBitmap
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import KMEANS_RANDOM_CENTERS [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()
示例6: get_dominant_color
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import KMEANS_RANDOM_CENTERS [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
示例7: kmeans
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import KMEANS_RANDOM_CENTERS [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
示例8: test_kmeans
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import KMEANS_RANDOM_CENTERS [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()
示例9: k_means
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import KMEANS_RANDOM_CENTERS [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
示例10: k_means
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import KMEANS_RANDOM_CENTERS [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
示例11: extract_cols
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import KMEANS_RANDOM_CENTERS [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.
#
示例12: color_quantization
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import KMEANS_RANDOM_CENTERS [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