我正在使用顏色查找坐標,在我的情況下假設為藍色,并給出影像中具有該顏色的那個點的坐標。
我正在使用此代碼:
#!/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 的任何想法?
提前致謝
參考:查找影像中檢測到指定顏色的坐標
uj5u.com熱心網友回復:
好吧,我找到了另一個使用 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))
uj5u.com熱心網友回復:
使用 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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/404757.html
標籤:
下一篇:與補充影像的背景隔離
