在彩色点图像中找到中心坐标

Finding the centre coordinates in an image of colored points

我正在努力使用颜色查找坐标,在我的例子中假设为蓝色,并给出图像中具有该颜色的那个点的坐标。

我正在使用此代码:

#!/usr/bin/env python3

import cv2
import numpy as np

#Load image
img = cv2.imread('image.png')

#Define the blue color we want to find 
blue = [255,0,0]

#Get X and Y cooridinates of ALL blue pixels
X,Y = np.where(np.all(img==blue, axis=2))
zipped = np.column_stack((X,Y))

#Get the number of coordinates founded
print(len(zipped))

当我只需要那个特定位置的一个坐标时,我得到了所有蓝色区域的像素。

此图像包含 image_with_blue_coordinates 蓝色坐标(但每个蓝色点至少包含 6 到 8 个蓝色像素)所以我得到了所有坐标,而我只需要中心像素.

知道如何处理这个问题并只获得 36 个 x,y 坐标而不是 1342 个吗?

提前致谢

参考:

好吧,我找到了另一个使用 Kmeans 的解决方案,以防有人需要它,这是代码

import cv2
import numpy as np
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score

# Load image
im = cv2.imread('image.png')

# Define the blue colour we want to find - remember OpenCV uses BGR ordering
blue = [255,0,0]

# Get X and Y coordinates of all blue pixels

X,Y = np.where(np.all(im==blue,axis=2))
zipped = np.column_stack((X,Y))
print(len(zipped))

sil = []
kmax = 40

# dissimilarity would not be defined for a single cluster, thus, minimum number of clusters should be 2    
for k in range(2, kmax+1):
  kmeans = KMeans(n_clusters = k).fit(zipped)
  labels = kmeans.labels_
  sil.append(silhouette_score(zipped, labels, metric = 'euclidean'))

ind = sil.index(max(sil))
n_points = list(range(2, kmax+1))[ind]
print(n_points)

kmeans = KMeans(n_clusters=n_points).fit(zipped)
points = kmeans.cluster_centers_
print(len(points))

这里是使用 DFS 的更快更好的方法代码:

import cv2
import numpy as np

dx=[0,0,1,1,-1,-1]
dy=[1,-1,1,-1,1,-1]
visited={}
def dfs(x, y):
    visited[(x,y)]=2
    i=0
    while i<6:
        new_x=x+dx[i]
        new_y=y+dy[i]
        if(not((new_x,new_y)in visited)):
            i+=1
            continue
        if(visited[(new_x,new_y)]==2):
            i+=1
            continue 
        dfs(new_x,new_y)
        i+=1
# Load image
im = cv2.imread('image.png')
# Define the blue colour we want to find - remember OpenCV uses BGR ordering
blue = [255,0,0]

# Get X and Y coordinates of all blue pixels

X,Y = np.where(np.all(im==blue,axis=2))
zipped = np.column_stack((X,Y))
for pixel in zipped:
    x=pixel[0]
    y=pixel[1]
    visited[(x,y)]=1
result=[]
for pixel in zipped:
    x=pixel[0]
    y=pixel[1]
    if visited[(x,y)]==1:
        result.append((x,y))
        dfs(x,y)
print(result)