跟踪红外LED阵列以找到它们的坐标

2024-04-25 10:04:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个点阵列,我也知道它们在我们世界中的位置。我需要计算每个数组的总中间以及这个中间的2d(xy)坐标。因此,应该输入具有这些点阵列的图像,并且输出应该是2个列表:return[x1,y1],[x2,y2]。Python3.x语言,OpenCV库

Input image

我发现了一些有用的代码(Python):

import numpy as np
import cv2 as cv
from matplotlib import pyplot as plt
X = np.random.randint(25,50,(5,2))
Y = np.random.randint(60,85,(4,2))
Z = np.vstack((X,Y))
# convert to np.float32
Z = np.float32(Z)
# define criteria and apply kmeans()
criteria = (cv.TERM_CRITERIA_EPS + cv.TERM_CRITERIA_MAX_ITER, 10, 1.0)
ret,label,center=cv.kmeans(Z,2,None,criteria,10,cv.KMEANS_RANDOM_CENTERS)
# Now separate the data, Note the flatten()
A = Z[label.ravel()==0]
B = Z[label.ravel()==1]
# Plot the data
plt.scatter(A[:,0],A[:,1])
plt.scatter(B[:,0],B[:,1],c = 'r')
plt.scatter(center[:,0],center[:,1],s = 80,c = 'y', marker = 's')
plt.xlabel('Height'),plt.ylabel('Weight')
plt.show()

此代码在点数组中查找中点。 但问题是理解哪个点属于哪个数组


Tags: the代码importasnppltrandom数组
1条回答
网友
1楼 · 发布于 2024-04-25 10:04:40

一个想法是阈值,执行变形操作,找到轮廓,然后找到质心。这应该给你两点

变形关闭以连接点

enter image description here

以蓝色绘制质心的结果

enter image description here

坐标

(416, 234)
(231, 244)

代码

import cv2

# Load image, convert to grayscale, Otsu's threshold
image = cv2.imread('1.png')
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]

# Morphological transformations
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (11,11))
close = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel, iterations=5)

# Find contours, obtain bounding rect, and find centroid
cnts = cv2.findContours(close, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    # Get bounding rect
    x,y,w,h = cv2.boundingRect(c)

    # Find centroid
    M = cv2.moments(c)
    cX = int(M["m10"] / M["m00"])
    cY = int(M["m01"] / M["m00"])

    # Draw the contour and center of the shape on the image
    cv2.rectangle(image,(x,y),(x+w,y+h),(0,255,0),2)
    cv2.circle(image, (cX, cY), 1, (320, 159, 22), 8) 
    cv2.putText(image, '({}, {})'.format(cX, cY), (x,y - 15), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (100,255,100), 2)
    print('({}, {})'.format(cX, cY))

cv2.imshow('image', image)
cv2.imshow('close', close)
cv2.imshow('thresh', thresh)
cv2.waitKey()

相关问题 更多 >