patch & added

second test node where the corners are ordered in the rgb_callback. Only when the max_depth threshold is calculated as pixel_depth we start the the depth_callback.
The test file also tries to use the approximation to calculate depths smaller than the min_depth threshold.
This commit is contained in:
2024-02-26 01:33:25 +01:00
parent 04a232534c
commit 5c113e31e8
@@ -0,0 +1,294 @@
#!/usr/bin/env python
from __future__ import print_function
import roslib
import sys
import rospy
import cv2
import time
import numpy as np
import serial
import subprocess
from std_msgs.msg import String
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
from geometry_msgs.msg import Twist
TARGET = 0
DEPTH_CAMERA_MIN_THRESHOLD = 400
DEPTH_CAMERA_MAX_THRESHOLD = 700
POSITIONS = ["left", "right", "middle"]
DEVICE = 'dev/ttyACM'
BAUD = 9600
class tutel():
def __init__(self, tutel_topic : str, astra_rgb_topic : str, astra_depth_topic : str, velocity_factor : float = 1.0):
#needed variables, velocity factor is a multiplier for the bot, might be changed later
#target_id used to remember the last id the tutel found, set to 0 at the beginning
self.vel_fac = velocity_factor
self.target_id = TARGET
#auruco init, best dictionary we found atm
self.arucoDict = cv2.aruco.getPredefinedDictionary(cv2.aruco.DICT_ARUCO_ORIGINAL)
self.arucoParams = cv2.aruco.DetectorParameters_create()
#minimal/maximal depth we recognize, still testing for values!
self.max_threshold = DEPTH_CAMERA_MAX_THRESHOLD
self.min_threshold = DEPTH_CAMERA_MIN_THRESHOLD
#Serial Pipeline init
#self.com = self.init_serial()
#self.device = DEVICE+str(self.com)
#self.baud = BAUD
#self.serial_pipeline = serial.Serial(self.device, self.baud, timeout = 1)
#Tutel_control
self.pub = rospy.Publisher(tutel_topic, Twist, queue_size = 1)
self.wait_publishers(astra_rgb_topic, astra_depth_topic)
self.t = Twist()
#self.movement_counter = 0
#cv related
#rgb related
self.position = POSITIONS[-1]
self.lastConernerTime = time.time()
self.rgb_bridge = CvBridge()
self.search = True
self.search_time = time.time()
#depth related
self.depth_bridge = CvBridge()
self.depth_state = False
self.last_depth = 10.0
self.depth_counter = 0
self.top_left = (-1,-1)
self.top_right = (-1,-1)
self.bottom_right = (-1,-1)
self.bottom_left = (-1,-1)
self.x = (0,0)
self.y = (0,0)
self.pixel_length = 0
self.pixel_depth = 10.0
#ros node related
rospy.init_node("turtle_control", anonymous=True)
#update rate can be increased
self.rate = rospy.Rate(15)
#Sub init
self.rgb_sub = rospy.Subscriber(astra_rgb_topic, Image, self.callback_rgb)
self.depth_sub = rospy.Subscriber(astra_depth_topic, Image, self.callback_depth)
#finding specific port for arduino communication
def init_serial(self):
for com in range(0,4):
subprocess.run(["fuser", "/dev/ttyACM"+str(com), "-k"])
try:
port = DEVICE+str(com)
baud = BAUD
board = serial.Serial(port, baud)
board.close()
break
except:
pass
return com
#we wait for both publishers, camera topics, to send information
def wait_publishers(self, astra_rgb_topic, astra_depth_topic):
while True:
if any(astra_rgb_topic in topic_list for topic_list in rospy.get_published_topics()) and any(astra_depth_topic in topic_list for topic_list in rospy.get_published_topics()):
break
print("Waiting for {} and {} to start.".format(astra_rgb_topic, astra_depth_topic))
rospy.sleep(1)
def callback_rgb(self, data):
try:
rgb_image = self.rgb_bridge.imgmsg_to_cv2(data, "bgr8")
(self.h, self.w) = rgb_image.shape[:2]
except CvBridgeError as e:
print(e)
(corners, ids, rejected) = cv2.aruco.detectMarkers(rgb_image, self.arucoDict, parameters = self.arucoParams)
if corners:
for id_x in ids:
if id_x != 0:
self.target_id = id_x
break
self.search = False
if self.search:
if(time.time() - self.search_time) > 31.5:
self.search_time = time.time()
#start = time.time()
if (time.time() - self.search_time) < 34.415925:
self.t.linear.x = 0.0 * self.vel_fac
self.t.angular.z = 0.2 * self.vel_fac
self.pub.publish(self.t)
#self.movement_counter += 1
(corners, ids, rejected) = cv2.aruco.detectMarkers(rgb_image, self.arucoDict, parameters = self.arucoParams)
if corners:
for id_x in ids:
if id_x != 0:
self.target_id = id_x
break
self.search = False
else:
self.t.linear.x = 0.2 * self.vel_fac
self.t.angular.z = 0.0 * self.vel_fac
self.pub.publish(self.t)
self.t.linear.x = 0.0 * self.vel_fac
self.pub.publish(self.t)
self.search_time = time.time()
(corners, ids, rejected) = cv2.aruco.detectMarkers(rgb_image, self.arucoDict, parameters = self.arucoParams)
if corners:
for id_x in ids:
if id_x != 0:
self.target_id = id_x
break
self.search = False
else:
if corners:
#self.movement_counter = 0
x = np.where(ids == self.target_id)
if len(x[0]) > 0:
fitting_corners = corners[x[0][0]]
rgb_image = self.markDetected(rgb_image, fitting_corners)
self.lastConernerTime = time.time()
elif(self.lastConernerTime - time.time()) < 1./2:
self.depth_state = False
if self.position is POSITIONS[0]:
cv2.rectangle(rgb_image, (0,0), (20, self.h), (0,0,255), cv2.FILLED)
self.t.linear.x = 0.0 * self.vel_fac
self.t.angular.z = -0.3 * self.vel_fac
self.pub.publish(self.t)
elif self.position is POSITIONS[1]:
cv2.rectangle(rgb_image, (self.w-20,0), (self.w, self.h), (0,0,255), cv2.FILLED)
self.t.linear.x = 0.0 * self.vel_fac
self.t.angular.z = 0.3 * self.vel_fac
self.pub.publish(self.t)
#some additional info on screen
id_str = "IDs: " + str(ids) + " Target_ID:" + str(self.target_id)
cv2.putText(rgb_image, id_str, (10,30), cv2.FONT_HERSHEY_TRIPLEX, 1, (255,0,0), 2, cv2.LINE_8)
depth_str = "Depth_State:" + str(self.depth_state) + " Depth:" + str(self.last_depth)
cv2.putText(rgb_image, depth_str, (10,60), cv2.FONT_HERSHEY_TRIPLEX, 1, (255,0,0), 2, cv2.LINE_8)
info_str = "Resolution: " + str(self.w) + "x" + str(self.h) + " Search_State: " + str(self.search) + " Max_Min_Depth: " + str(self.maxMinDepth)
cv2.putText(rgb_image, info_str, (10,90), cv2.FONT_HERSHEY_TRIPLEX, 1, (255,0,0), 2, cv2.LINE_8)
self.rate.sleep()
cv2.imshow("Tutel", rgb_image)
cv2.waitKey(1)
def callback_depth(self, data):
if self.depth_state:
depth_image = self.depth_bridge.imgmsg_to_cv2(data, "passthrough")
if self.depth_counter == 0:
self.last_depth = 10.0
self.x = (0,0)
self.y = (0,0)
#x and y are swapped, because
depth_values = []
for i in range(self.x[0], self.x[1]):
for j in range(self.y[0], self.y[1]):
if depth_image[j][i] > self.min_threshold and depth_image[j][i] < self.max_threshold:
depth_values.append(depth_image[j][i])
if len(depth_values)>0 and ((max(depth_values) > self.last_depth-100 and max(depth_values) < self.last_depth+100) or self.last_depth == 10):
self.last_depth = max(depth_values)
else:
self.last_depth = self.last_depth
print(self.depth_counter, self.last_depth)
if self.last_depth < self.min_threshold and self.last_depth != 10:
self.last_depth = self.pixel_length
if self.last_depth <= 50 and self.last_depth != 10:
self.depth_counter += 1
if self.depth_counter > 0:
self.t.linear.x = 0.0 * self.vel_fac
self.pub.publish(self.t)
print("We reached our destination")
#self.move_arm(self)
else:
self.depth_counter = 0
def markDetected(self, image, corners):
thresh_left = self.w//2 - 100
thresh_right = self.w//2 + 100
for markerCorner in corners:
(self.top_left, self.top_right, self.bottom_right, self.bottom_left) = markerCorner.reshape((4,2))
self.top_left = (int(self.top_left[0]), int(self.top_left[1]))
self.top_right = (int(self.top_right[0]), int(self.top_right[1]))
self.bottom_right = (int(self.bottom_right[0]), int(self.bottom_right[1]))
self.bottom_left = (int(self.bottom_left[0]), int(self.bottom_left[1]))
cv2.line(image, self.top_left, self.top_right, (0,255,0), 2)
cv2.line(image, self.top_right, self.bottom_right, (0,255,0), 2)
cv2.line(image, self.bottom_right, self.bottom_left, (0,255,0), 2)
cv2.line(image, self.bottom_left, self.top_left, (0,255,0), 2)
if (self.top_left[0] - self.bottom_left[0]) in range (-10,10):
if self.top_left[0] < self.top_right[0]: self.x = (self.top_left[0],self.top_right[0])
else: self.x = (self.top_right[0],self.top_left[0])
if self.top_left[1] < self.bottom_left[1]: self.y = (self.top_left[1],self.bottom_left[1])
else: self.y = (self.bottom_left[1],self.top_left[1])
elif (self.top_left[0] - self.top_right[0]) in range (-10,10):
if self.bottom_left[0] < self.top_left[0]: self.x = (self.bottom_left[0],self.top_left[0])
else: self.x = (self.top_left[0],self.bottom_left[0])
if self.bottom_left[1] < self.bottom_right[1]: self.y = (self.bottom_left[1],self.bottom_right[1])
else: self.y = (self.bottom_right[1],self.bottom_left[1])
self.pixel_length = (self.x[1] - self.x[0] + self.y[1] - self.y[0]) / 2
#Approximation function for the amount of marker side's pixel for a specific distance to the camera
#f(x)=2914.2987x^-1.0159, with x := distance between camera and marker. Values rounded down to 4 digits.
self.pixel_depth = ((pixel_length/2914.2987)**(-1/1.0159))*10 #*10 to get the depth value in mm as the depth image delivers them in mm
if self.pixel_depth > self.max_threshold or self.pixel_depth < self.min_threshold:
if (self.pixel_depth > self.last_depth-100 and self.pixel_depth < self.last_depth-100) or self.last_depth == 10:
self.last_depth = self.pixel_depth
else:
self.last_depth = self.last_depth
else: self.depth_state = True
#self.last_marker_position = ((self.top_left), (self.bottom_right))
if (self.x[0] > thresh_left and self.x[1] < thresh_right):
self.t.linear.x = 0.15 * self.vel_fac
self.t.angular.z = 0.0 * self.vel_fac
self.pub.publish(self.t)
elif self.x[1] < thresh_left:
self.t.linear.x = 0.0 * self.vel_fac
self.t.angular.z = 0.1 * self.vel_fac
self.pub.publish(self.t)
elif self.x[0] > thresh_right:
self.t.linear.x = 0.0 * self.vel_fac
self.t.angular.z = -0.1 * self.vel_fac
self.pub.publish(self.t)
if int(self.w / 2) > self.top_left[0]:
self.position = POSITIONS[0]
elif self.w - int(self.w / 2) < self.top_left[0]:
self.position = POSITIONS[1]
return image
def move_arm(self):
self.s.write('1'.encode('utf-8'))
time.sleep(1)
def main():
if len(sys.argv) != 4:
print("Please give the following arguments <turtlebot-navi-topic> and <camera-img-topic> and <camera-depth-topic>")
print("Like: tutel_max_value_pure_test_version.py /cmd_vel_mux/input/navi /camera/color/image_raw /camera/depth/image_raw")
return 1
ic = tutel(str(sys.argv[1]),str(sys.argv[2]),str(sys.argv[3]))
try:
rospy.spin()
except KeyboardInterrupt:
print("Shutting down")
cv2.destroyAllWindows()
if __name__ == "__main__":
main()