大家好,我正在做一个关于arduino机器人手臂的大学项目,它使用带有python/opencv的网络摄像头捕捉特定颜色的对象。
我的代码的步骤基本上如下所示:
捕获帧;
将帧bgr转换为hsv;
设置hsv的阈值,以仅获得我想要的颜色;
在脱粒机上应用腐 eclipse 和膨胀
使用cv2.findcontours在thresh上查找轮廓
在for循环中,使用矩获取每个轮廓的质心
绘制轮廓,在质心上用质心坐标(cx | cy)画一个点(小圆),并在框架上写下对象标签(环上i的位置)
在此之前,一切都很顺利,但我遇到了一个问题,当我切换对象的位置(特别是y轴)时,他们在循环上切换i位置,我想要的是算法知道“该对象是nº1,即使他在nº2和nº3的上方或下方”。我还想知道是否有一种方法可以在对象0(即机器人手臂)的位置和所有其他对象之间画一条线,这样我就可以得到对象的位置,并且可以移动机器人来捕捉它们。
你们知道我是怎么做到的吗?对不起,如果有任何英语错误,我还在学英语。
这里是我到目前为止所做的代码和正在运行的代码的打印。
# Importing libraries
import cv2
import numpy as np
# Creating callback function and Trackbars
def callback(x):
pass
cv2.namedWindow('Trackbars', cv2.WINDOW_FREERATIO)
cv2.createTrackbar('LH', 'Trackbars', 0, 255, callback)
cv2.createTrackbar('LS', 'Trackbars', 0, 255, callback)
cv2.createTrackbar('LV', 'Trackbars', 0, 255, callback)
cv2.createTrackbar('UH', 'Trackbars', 255, 255, callback)
cv2.createTrackbar('US', 'Trackbars', 255, 255, callback)
cv2.createTrackbar('UV', 'Trackbars', 255, 255, callback)
# Define a capture object and resizes to 640x360
cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 360)
while True:
# Capturing the frame
_, frame = cap.read()
# Converting to HSV
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
# Getting Trackbars value
l_h = cv2.getTrackbarPos('LH', 'Trackbars')
l_s = cv2.getTrackbarPos('LS', 'Trackbars')
l_v = cv2.getTrackbarPos('LV', 'Trackbars')
u_h = cv2.getTrackbarPos('UH', 'Trackbars')
u_s = cv2.getTrackbarPos('US', 'Trackbars')
u_v = cv2.getTrackbarPos('UV', 'Trackbars')
# Creating Lower and Upper arrays with the data of trackbars
l_c = np.array([l_h, l_s, l_v])
u_c = np.array([u_h, u_s, u_v])
# Creating thresh
thresh = cv2.inRange(hsv, l_c, u_c)
# Applying Morphological transformations: Erosion and dilation on the thresh
erode = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5))
dilate = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5))
thresh = cv2.erode(thresh,erode,iterations = 2)
thresh = cv2.dilate(thresh,dilate,iterations = 2)
# Finding and drawing contours, centroid and centroid positions
try:
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for i, c in enumerate(contours):
M = cv2.moments(c)
cx = int(M["m10"] / M["m00"])
cy = int(M["m01"] / M["m00"])
cv2.drawContours(frame, contours, -1, (0, 255, 0), 2)
cv2.putText(frame, "OBJECT "+(str(i)), (cx-35,cy-30),1,1,(0,0,255),1)
cv2.circle(frame,(cx,cy),1,(0,0,255),2)
cv2.putText(frame, str(cx)+","+ str(cy), (cx-35,cy+30),1,1,(0,0,255),1)
except:
pass
# Showing frame and thresh
cv2.imshow('frame',frame)
cv2.imshow('thresh',thresh)
# 'Esc' key break the loop and destroy all windows
key = cv2.waitKey(1)
if key == 27:
cv2.destroyAllWindows()
break
对象0、1、2、3
当对象1在y轴上上升时,在for的i轴上改变位置,转到i=3
谢谢
暂无答案!
目前还没有任何答案,快来回答吧!