python - 跟踪一组 IR LED 以找到它们的坐标
问题描述
我有 2 个点数组,我也知道它们在我们世界中的位置。我需要计算每个数组的总中间和这个中间的 2d(xy) 坐标。因此,应输入具有这些点数组的图像,输出应为 2 个列表:返回 [x1, y1], [x2, y2]。Python 3.x 语言,OpenCV 库。
我发现了一些有用的代码(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()
此代码在点数组中找到中点。但问题是理解哪个点属于哪个数组。
解决方案
一个想法是阈值,执行变形操作,找到轮廓,然后找到质心。这应该给你两点。
变形接近连接点
质心以蓝色绘制的结果
坐标
(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()
推荐阅读
- javascript - 用js删除元素后如何重新应用css网格布局?
- java - Proxy.newProxyInstance 第一个参数类加载器如何工作
- react-native - React Native - 观察 AsyncStorage 值的变化?
- c# - ComboBox SelectValue 返回前一个
- java - imageView 没有出现在模拟器中
- c# - 如何序列化具有相同复杂道具类型但名称不同的对象
- vba - 使用 IsNumeric 的输入验证不起作用
- java - 如何在 HTML 中将字符串数组插入 Selectpicker
- microsoft-graph-api - 图团队 api 的数据延迟是多少?
- vue.js - Vuejs如何动态使用Google Analytic,Facebook Pixel